Skip to content

[12.x] Give each for loop iteration its own variable when the start must run before the end - #9465

Open
illusionalsagacity wants to merge 7 commits into
rescript-lang:maintenance/12.xfrom
illusionalsagacity:fix-for-loop-closure-12.x
Open

illusionalsagacity wants to merge 7 commits into
rescript-lang:maintenance/12.xfrom
illusionalsagacity:fix-for-loop-closure-12.x

Conversation

@illusionalsagacity

Copy link
Copy Markdown
Contributor

Backport of #9417 to 12.x. Builds on the backports of #9423 (fix-for-loop-in-operator-12.x, #9462, which builds on #9455, fix-printer-operand-levels-12.x), #8778 (fix-shadow-dollar-12.x, #9463) and #8785 (fix-external-shadow-scope-12.x, #9464), in that order. One of the tests has an end temporary using in, which needs #9423's parentheses in the loop header; on master #9417 likewise builds on #9423. The second and third commits build on the raw JS names that Ext_pp_scope reserves since #8778 and on #8785's globalThis rewriting, which were on master before #9417.

Problem

When a for loop's start is not safe to delay (a call, or a read of a mutable variable, field or array element) and its end needs statements (a try or a switch), the start must be evaluated before those statements. The compiler did that by declaring the loop variable itself before the loop and emitting for (; i <= tmp; ++i), so every iteration shared one variable and closures created in the body all saw its final value.

@inline(never) let id = x => x
let fs = []
for i in id(0) to try { id(1) } catch { | _ => 0 } {
  fs->Array.push(() => i)
}

Before (every closure returns 2):

let i = id(0);

let tmp;

try {
  tmp = id(1);
} catch (exn) {
  tmp = 0;
}

for (; i <= tmp; ++i) {
  fs.push(() => i);
}

After:

let i_start = id(0);

let tmp;

try {
  tmp = id(1);
} catch (exn) {
  tmp = 0;
}

for (let i = i_start; i <= tmp; ++i) {
  fs.push(() => i);
}

A loop's temporaries could also capture a JS name the module refers to. The printer binds the end to i_finish, which could take the name of a global the end calls, so let i_finish = i_finish() threw a ReferenceError. And the i_start temporary could take the name of a function declared in %%raw; Js_pass_external_shadow then read it through globalThis, where a module's function isn't, so the call threw a TypeError.

%%raw(`
function i_finish() { return 3 }
function j_start() { return 1 }
`)
@val external iFinish: unit => int = "i_finish"
@val external jStart: unit => int = "j_start"

let toplevelLowercase = []
for i in 2 to iFinish() {
  toplevelLowercase->Array.push(() => i)
}

let startBeforeStatements = g => {
  let fs = []
  for j in jStart() to {
    try g() catch {
    | _ => 0
    }
  } {
    fs->Array.push(() => j)
  }
  fs->Array.map(f => f())
}

Before (with the first commit):

for (let i = 2, i_finish = i_finish(); i <= i_finish; ++i) {
  toplevelLowercase.push(() => i);
}

function startBeforeStatements(g) {
  let fs = [];
  let j_start = globalThis.j_start();
  ...

After:

for (let i = 2, i_finish$1 = i_finish(); i <= i_finish$1; ++i) {
  toplevelLowercase.push(() => i);
}

function startBeforeStatements(g) {
  let fs = [];
  let j_start$1 = j_start();
  ...

Fix

As on master:

  • The start is held in a temporary named after the loop variable (i_start) and the loop declares i itself.
  • No loop is built without a start any more, so J.ForRange and S.for_ take the start expression rather than an option.
  • The temporaries i_start and i_finish drop the quotes of an uppercase exotic loop variable rather than mangle them (End_finish instead of $unknown$unknownEnd$unknown_finish).
  • Ext_ident.create_tmp flags the identifiers it creates as synthesized, and the printer's i_finish comes from it. Ext_pp_scope names a synthesized identifier so that it is none of the reserved raw JS names, and Js_pass_external_shadow doesn't count it as shadowing anything. The second commit's Ext_pp_scope.printer_ident is replaced by this in the third, as on master.

Differences from master:

  • 12.x has no delay_safe / evaluate_now (from Bind elements and inlined arguments read from assigned variables #9284), and kept a start without side effects in the loop header after the end's statements even when it read a mutable variable, field or array element that they change. A local may_change check in lam_compile.ml decides instead: only a number, or a local variable the end doesn't assign, stays in the loop header. The tests for mutable starts are 12.x-only for that reason.
  • 12.x also has js_fold.ml, whose ForRange case is updated like the record folds.
  • Ext_pp_scope uses 12.x's data-first Map_string, Map_int and Set_string, and Ext_ident is in compiler/ext (compiler/typing on master).
  • for_loop_finish_global_test has two 12.x-only cases, loops at the toplevel before any function. On 12.x the globals a function refers to are added to the printer's scope, so a loop inside such a function, or after it, already got i_finish$N, and master's two i_finish cases pass on 12.x without the fix. The toplevel loops threw a ReferenceError when the module loaded. The temporaries inside the functions are numbered differently from master (i_finish$3 instead of i_finish$1) for the same reason.
  • The CHANGELOG has a second entry for the temporaries, like master's second changes/ fragment.

Tests

tests/tests/src/for_loop_closure_test.res has master's cases (closures with to and downto, an empty range, start before end, uppercase exotic loop variables, and an end using in, alone and after a start that runs first), plus 12.x cases for a start in the header before an end without statements, mutable variable, field and array element starts, and an immutable start. The .mjs of master's cases is the same as on master. tests/tests/src/for_loop_finish_global_test.res has master's cases (an end calling a global named like its temporary, for an uppercase exotic and a lowercase loop variable, and a start calling a %%raw function named like its temporary) and the two toplevel loops. Without the second and third commits, the module throws a ReferenceError when it loads, and the %%raw case throws a TypeError.

No other module in tests/tests changes output (12.x has no argument_evaluation_order_test, whose output changes on master).

Investigated by Claude.

Js_dump printed both operands of the `in` operator, which Dict.has
compiles to, at level 0, so that a conditional, a sequence or a
comparison got no parentheses and JavaScript took only part of it as the
operand. It also printed an `in` without parentheses at levels up to
12, so that an `in` on the right of a comparison, or an operand of `+`,
was split the same way. `In` now takes its levels from `instanceof`,
which is in the same class of operators.

The start of a `for` loop whose end is a number or a variable was
printed at level 0 as well. JavaScript reads a comma in the start as the
next declaration, so a sequence was a syntax error, or, in a start ending
in a variable, a second loop variable. It is now printed at level 1.

12.x has no `for...of` or `for await...of`, so the master change to
their iterables and the tests of them don't apply here.

Signed-off-by: Rob <illusionalsagacity@users.noreply.github.com>
(cherry picked from commit ecb21d0)
JavaScript doesn't allow a bare `in` operator in the initializer of a
`for` header, where the printer puts the start of a ReScript `for` loop
and an end that is neither a number nor a variable. A start or end using
`Dict.has` was therefore printed as a syntax error. While `Js_dump`
prints the initializer, `Ext_pp` now records that `in` is forbidden until
the next brackets, and `In` is printed in parentheses there.

On 12.x, `Ext_pp` lives in compiler/ext and has no source map position
tracking, so only the new field is added to its record.

(cherry picked from commit 3172330)
Signed-off-by: Rob <illusionalsagacity@users.noreply.github.com>
Backport of rescript-lang#8778 to 12.x.

Track printed names in Ext_pp_scope so a suffix like x$1 is never reused
for an identifier that already contains $, and reserve the raw JS names a
program refers to, so a renamed local like x$2 can't capture an external
with that name.

Differs from master only in using 12.x's Map_string, Map_int and
Set_string (data-first, where master uses the stdlib Map and Set), and in
keeping Ext_pp_scope.print, which 12.x still has, adapted to the new scope
type.

Signed-off-by: Rob <illusionalsagacity@users.noreply.github.com>
…n scope

Backport of rescript-lang#8785 to 12.x.

A reference to a @Val global compiled to its bare name, which reads a
binding with that name if one is in scope. Previously this was only handled
inside the binding's own initializer. The cases of a switch share one
scope, and the discriminant is read outside of it.

Differences from master:
- 12.x has no rescript-lang#8772, which replaced the per-binding rewrite of an
  initializer with a single walk; rescript-lang#8785 replaces that code as a whole, so
  the pass here is master's rescript-lang#8785 version without rescript-lang#8772 in between, and
  rescript-lang#8772's ExternalShadow tests are not included.
- 12.x's J.ForRange has five fields and there is no ForOf or ForAwaitOf.
- Js_call_info.na_full_call takes the transformed-JSX flag on 12.x.
- ppx_apply_test.mjs: 12.x already printed the toplevel `xx` unsuffixed,
  so only the read of the global changes to `globalThis.xx` (on 12.x it
  read the local `xx = 6`).

Signed-off-by: Rob <illusionalsagacity@users.noreply.github.com>
… before the end

When a for loop's start has side effects and its end needs statements (a
try or a switch), the start must be evaluated before those statements.
The compiler did that by declaring the loop variable itself before the
loop and emitting `for (; i <= tmp; ++i)`, so every iteration shared one
variable and closures created in the body all saw its final value.

Hold the start in a temporary named after the loop variable (`i_start`)
instead, and let the loop declare its own variable. No loop is built
without a start any more, so `J.ForRange` and `S.for_` now take the
start expression rather than an option.

A start without side effects was evaluated after the end's statements, also
when it read a mutable variable, field or array element that they change.
Hold such a start too. Only a number or a local variable that the end does
not assign stays in the loop header. (On master, the delay_safe check from

The temporaries of a loop, i_start and i_finish, now drop the quotes of an
uppercase exotic loop variable rather than mangle them.

Also tests an end temporary that uses `in`, which the rescript-lang#9423 backport
parenthesises in the loop header.

(cherry picked from commit 3b2d03e)
Signed-off-by: Rob <illusionalsagacity@users.noreply.github.com>
Backport of the second commit of rescript-lang#9417 to 12.x.

The printer binds a `for` loop's end in the loop header to a temporary
named after the loop variable (`i_finish`). A JS global the end refers
to may have that name, and the binding then captures it: `let i_finish
= i_finish()` reads the temporary before it is initialized and throws
a ReferenceError. Js_pass_external_shadow rewrites such references to
`globalThis.x` for the bindings it sees, but the printer creates this
one after that pass, and Ext_pp_scope let any binding take a reserved
raw name unsuffixed. Ext_pp_scope.printer_ident now names a binding the
printer introduces so that it is none of the reserved raw names.

Differences from master:
- Ext_pp_scope uses 12.x's data-first Map_string, Map_int and Set_string.
- The test adds loops at the toplevel, before the functions. On 12.x a
  loop inside a function, or after a function referring to the global,
  already got a suffixed temporary (the globals a function refers to are
  added to the printer's scope), so master's cases pass here without the
  fix; the toplevel loops threw a ReferenceError when the module loaded.
- 12.x has CHANGELOG.md in place of master's changes/ fragment.

Signed-off-by: Rob <illusionalsagacity@users.noreply.github.com>
Backport of the third commit of rescript-lang#9417 to 12.x.

A temporary the compiler creates, such as the `i_start` the previous
commits hold a loop's start in, could take the name of a raw JS name
the module refers to. Js_pass_external_shadow then rewrote the
references to that name in its scope to `globalThis.x`, which is
wrong when a `%%raw` declaration in the module binds the name: such a
function is no property of `globalThis`, so the call threw a
TypeError. Ext_ident.create_tmp now flags the identifier as
synthesized. Ext_pp_scope names a synthesized identifier so that it is
none of the reserved raw names, and Js_pass_external_shadow does not
count it as shadowing anything. This replaces
Ext_pp_scope.printer_ident: the printer's `i_finish` is created with
create_tmp.

Differences from master:
- Ext_ident is in compiler/ext on 12.x (compiler/typing on master).
- The printer's `i_finish` already came from create_tmp on 12.x, so
  only the call to printer_ident changes back to Ext_pp_scope.ident in
  js_dump.ml.
- 12.x has CHANGELOG.md in place of master's changes/ fragment.

Signed-off-by: Rob <illusionalsagacity@users.noreply.github.com>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant