facebook/hermes

Incorrect variable capture in for loop

trossimel-sc opened this issue · 4 comments

Bug Description

The following code prints iter1 iter1 in hermes, but it should print iter0 iter1

iters = [];
for (let i = 0; i < 2; i++) {
  const iter = 'iter' + i;
  iters.push(function() {
    print(iter);
  });
}

for (let i = 0; i < 2; i++) {
  iters[i]();
}

Steps To Reproduce

Copy and execute the code snippet to see the output. I tested it using the static_h branch

The Expected Behavior

The code should print iter0 iter1, similarly to other engines. Is this behaviour expected?

Hi, we are aware of this - we have a stack of diffs implementing captured block scoped variables in loops, but the changes to the VM, the optimization pipeline, the debugger, etc, are so profound that we have been delaying landing them.

I will comment here with more about our plans with regards to block scoping.

Thank you @tmikov!

@trossimel-sc we are going to make sure to land these changes in the coming days. They will be behind a flag.

Hi, this is now fixed. The new behavior is controlled by the CLI option -Xes6-block-scoping.