Starlight-JS / starlight

JS engine in Rust
https://teletype.in/@starlight-js
Mozilla Public License 2.0
509 stars 9 forks source link

Variables broken #119

Open playXE opened 3 years ago

playXE commented 3 years ago
let x = 0;
function f() {
  let x = 1;
  g();
  print(x);
}

function g() {
  print(x);
  x = 2;
}
Code block 'f' at 0x7f4e715d3718: 
 is strict?=false
0000: push_int <1>
0005: decl_let 0
0010: push_undefined
0011: get_environment 1
0016: get_local 1
0021: call <0>
0026: pop
0027: push_undefined
0028: global_object
0029: try_get_by_id 0, fdbk 0
0038: get_environment 0->get_local 0
0043: call <1>
0048: pop
0049: push_undefined
0050: ret

Code block 'g' at 0x7f4e715d35d8: 
 is strict?=false
0000: push_undefined
0001: global_object
0002: try_get_by_id 0, fdbk 0 // this is lookup for `x` but it should just use get_environment 1 -> get_local
0011: global_object
0012: try_get_by_id 1, fdbk 1
0021: call <1>
0026: pop
0027: push_int <2>
0032: global_object
0033: put_by_id 1, fdbk 2
0042: push_undefined
0043: ret

Code block '<script>' at 0x7f4e715d3858: 
 is strict?=false
0000: get_function 0
0005: get_environment 0->set_local 2
0010: get_function 1
0015: get_environment 0->set_local 1
0020: push_int <0>
0025: decl_let 3
0030: push_undefined
0031: ret
playXE commented 3 years ago

I know the source of problem: we first analyze block of code and then compile functions instead of compiling functions when emitting code so they do not see variables