Skip to content

Give each for loop iteration its own variable when the start must run before the end - #9417

Merged
cknitt merged 4 commits into
rescript-lang:masterfrom
illusionalsagacity:fix-for-loop-closure
Nov 28, 2026
Merged

cknitt merged 4 commits into
rescript-lang:masterfrom
illusionalsagacity:fix-for-loop-closure

Conversation

@illusionalsagacity

@illusionalsagacity illusionalsagacity commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

Builds on #9423, so the first commit here is #9423's; review from "Give each for loop iteration its own variable…" on. #9423's handling of in in a loop header covers the header binding of the end that this PR adds (Codex finding below).

Part of #9398 (item 10).

Problem

When a for loop's start can't be delayed (a call, or a mutable read) 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, 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:

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);
}

Fix

The start is held in a temporary (i_start, through evaluate_now) 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 instead of an option.

A loop whose start is constant or immutable is unchanged. The loop bound being read again on each iteration (#9356) is not touched here. The _start and _finish names are now readable for an uppercase exotic loop variable (Bar_finish instead of $unknown$unknownBar$unknown_finish).

The _finish temporary also no longer takes the name of a JS global the end refers to. With @val external iFinish: unit => int = "i_finish", for i in 2 to iFinish() printed for (let i = 2, i_finish = i_finish(); ...), which throws a ReferenceError because the end reads the temporary before it is initialized. It now prints i_finish$1 = i_finish(). The printer creates this temporary after Js_pass_external_shadow has run, so the new Ext_pp_scope.printer_ident gives it a name that none of the file's raw JS names uses. Master has this bug for a lowercase loop variable. The readable exotic names above would have added it for exotic ones too (End_finish).

Tests

for_loop_closure_test.res covers to, downto, an empty range and that the start runs before the end's statements. for_loop_finish_global_test.res covers an end that calls a global named like the temporary, for a lowercase and an uppercase exotic loop variable. One existing output changes: the loop in argument_evaluation_order_test.mjs now declares i in its header.

12.x

12.x has the same bug, and I have a backport ready on fix-for-loop-closure-12.x. I'll open it against maintenance/12.x once this one is reviewed.

The fix was written by Claude. A second Claude agent reviewed the first version; this version addresses that review and has not been reviewed again.

@github-actions

github-actions Bot commented Nov 26, 2026 •

Copy link
Copy Markdown

Changelog

🐛 Bug fix

  • Fix closures in a for loop all seeing the loop variable's final value when the loop's start is a call or a mutable read and its end needs statements, as in a try or switch.
  • Fix a temporary the compiler names, such as a for loop's i_finish, capturing a JS name the code refers to, a global or a function declared in %%raw, which threw a ReferenceError or a TypeError: a temporary no longer takes such a name.

Semantic Diff

4 commits · Full page

Give each for loop iteration its own variable when the start must run before the end

fb5c6fb · illusionalsagacity · Nov 23, 2026, 20:27 UTC

Why

When a for loop's start is not safe to delay (a call, or a read of a mutable variable or field) 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. The start is now held in a temporary named after the loop variable (i_start, through evaluate_now) and the loop declares i itself. No loop is built without a start any more, so J.ForRange and S.for_ now take the start expression rather than an option. Both temporaries of a loop, i_start and i_finish, now drop the quotes of an uppercase exotic loop variable rather than mangle them.

JS modified (for loop with a start evaluated before its end)

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

js

-let i = id(0);
+let i_start = id(0);
 
 let tmp;
 
 try {
   tmp = id(1);
 } catch (exn) {
   tmp = 0;
 }
 
-for (; i <= tmp; ++i) {
+for (let i = i_start; i <= tmp; ++i) {
   fs.push(() => i);
 }

JS modified (temporaries of an uppercase exotic loop variable)

@inline(never) let id = x => x
let fs = []
for \"End" in 3 to id(4) {
  fs->Array.push(() => \"End")
}

js

-for (let End = 3, $unknown$unknownEnd$unknown_finish = id(4); End <= $unknown$unknownEnd$unknown_finish; ++End) {
+for (let End = 3, End_finish = id(4); End <= End_finish; ++End) {
   fs.push(() => End);
 }

Review

  • Are loops with a constant or immutable start affected? No: such a start is delay safe and stays in the loop header as before.
  • Is the end still re-read each iteration when it is a variable? Yes, unchanged here; A for loop reads its upper bound from a local ref on every iteration #9356 tracks it.
  • Which checked-in outputs change? argument_evaluation_order_test.mjs, whose loop now declares i in its header.
Keep a for loop's end temporary from capturing a JS global of its name

247bd56 · illusionalsagacity · Nov 26, 2026, 22:09 UTC

Why

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. This answers Codex's review finding on #9417: the previous commit made the temporary of an uppercase exotic loop variable readable (End_finish), so it could now equal a global's name; a lowercase loop variable had the same bug before.

JS modified (end of a for loop calling a global named like its temporary)

@val external iFinish: unit => int = "i_finish"
let fs = []
for i in 2 to iFinish() {
  fs->Array.push(() => i)
}

js

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

Review

  • Does the start's temporary need the same? No: lam_compile creates i_start before Js_pass_external_shadow runs, which rewrites a reference to a global i_start in its scope to globalThis.i_start.
  • Which checked-in outputs change? None besides the new for_loop_finish_global_test.mjs.
Keep compiler temporaries clear of the raw JS names a module uses

53c3c63 · illusionalsagacity · Nov 27, 2026, 21:32 UTC

Why

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. The printer's i_finish is created with create_tmp too, which replaces Ext_pp_scope.printer_ident. This answers Codex's review finding on #9417.

JS modified (start of a for loop calling a raw function named like its temporary)

%%raw(`
function i_start() { return 1 }
`)
@val external start: unit => int = "i_start"
let f = g => {
  let fs = []
  for i in start() to {
    try g() catch { | _ => 0 }
  } {
    fs->Array.push(() => i)
  }
  fs->Array.map(h => h())
}

js

-let i_start = globalThis.i_start();
+let i_start$1 = i_start();

Review

  • Which other outputs can change? Any temporary from create_tmp, such as tmp, named like a raw JS name in its scope now gets a $N suffix instead of the reference going through globalThis. No checked-in output besides for_loop_finish_global_test.mjs changes.
Test a for loop's end temporary that uses in

509986a · illusionalsagacity · Nov 27, 2026, 21:41 UTC

The first commit prints the end of a loop whose start must run before the end as the end temporary in the loop header. An end that binds through a try and then tests Dict.has, from Codex's review of #9417, and a conditional end using Dict.has print an in there, which JavaScript reads as a for...in unless it is in parentheses. #9423's handling of the loop header gives them parentheses; these tests check that both loops run.

@codecov

codecov Bot commented Nov 26, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 96.00000% with 1 line in your changes missing coverage. Please review.
✅ Project coverage is 82.31%. Comparing base (3172330) to head (509986a).

Files with missing lines Patch % Lines
compiler/backend/js_pass_external_shadow.ml 0.00% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master    #9417      +/-   ##
==========================================
- Coverage   82.32%   82.31%   -0.01%     
==========================================
  Files         462      462              
  Lines       65749    65750       +1     
==========================================
  Hits        54125    54125              
- Misses      11624    11625       +1     
Files with missing lines Coverage Δ
compiler/backend/ext_pp_scope.ml 100.00% <100.00%> (ø)
compiler/backend/j.ml 100.00% <ø> (ø)
compiler/backend/js_dump.ml 92.59% <100.00%> (+0.06%) ⬆️
compiler/backend/js_record_fold.ml 93.03% <ø> (ø)
compiler/backend/js_record_iter.ml 100.00% <ø> (ø)
compiler/backend/js_record_map.ml 100.00% <ø> (ø)
compiler/backend/lam_compile.ml 90.72% <100.00%> (-0.04%) ⬇️
compiler/typing/ext_ident.ml 81.96% <100.00%> (+1.26%) ⬆️
compiler/backend/js_pass_external_shadow.ml 98.21% <0.00%> (ø)

... and 1 file with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@pkg-pr-new

pkg-pr-new Bot commented Nov 26, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

rescript

npm i https://pkg.pr.new/rescript@9417

@rescript/belt

npm i https://pkg.pr.new/@rescript/belt@9417

@rescript/darwin-arm64

npm i https://pkg.pr.new/@rescript/darwin-arm64@9417

@rescript/linux-arm64

npm i https://pkg.pr.new/@rescript/linux-arm64@9417

@rescript/linux-x64

npm i https://pkg.pr.new/@rescript/linux-x64@9417

@rescript/runtime

npm i https://pkg.pr.new/@rescript/runtime@9417

@rescript/win32-x64

npm i https://pkg.pr.new/@rescript/win32-x64@9417

commit: 509986a

@cknitt

cknitt commented Nov 26, 2026

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 26, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-28T05:54:24.283619Z bebfad9 Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 876e3b79bc

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread compiler/backend/js_dump.ml Outdated
let id =
Ext_ident.create (Ident.name id ^ "_finish")
Ext_ident.create
(Ext_ident.derived_name id ~suffix:"_finish")

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Keep exotic finish temporaries from capturing JS globals

For an uppercase exotic counter named End, a bound such as finish() with @val external finish: unit => int = "End_finish" now produces a loop-header declaration End_finish = End_finish(), causing a TDZ ReferenceError; the parent’s mangled temporary did not shadow that global. Js_pass_external_shadow only knows the counter, since this temporary is created later by the dumper, and Ext_pp_scope permits reserved raw names when no numeric suffix is needed. Ensure the finish temporary avoids raw JS global names, or introduce it before shadow analysis.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reproduced. With @val external finish: unit => int = "End_finish", for \"End" in 0 to finish() compiled to for (let End = 0, End_finish = End_finish(); ...), and node throws ReferenceError: Cannot access 'End_finish' before initialization. A lowercase loop variable has the same bug on master: for i in 0 to iFinish() with iFinish bound to "i_finish" prints i_finish = i_finish(). This PR's readable exotic names made the exotic case reachable as well.

Fixed in c65c375. The printer creates this temporary after Js_pass_external_shadow has run. Ext_pp_scope let any binding take a reserved raw name if it needed no suffix, which is only safe for bindings that pass has seen. The new Ext_pp_scope.printer_ident names a binding the printer creates so it avoids every reserved raw name. The loop now prints End_finish$1 = End_finish() and i_finish$1 = i_finish(). The _start temporary didn't need a change: lam_compile creates it before the shadow pass, which already rewrites the reference to globalThis.End_start(). The regression test tests/tests/src/for_loop_finish_global_test.res covers both cases, and no other checked-in output changes.

Investigated by Claude.

illusionalsagacity added a commit to illusionalsagacity/rescript-compiler that referenced this pull request Nov 26, 2026
Why:
    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. This
    answers Codex's review finding on rescript-lang#9417: the previous commit made the
    temporary of an uppercase exotic loop variable readable (`End_finish`),
    so it could now equal a global's name; a lowercase loop variable had
    the same bug before.

JS modified (end of a for loop calling a global named like its temporary):
Example:
    @Val external iFinish: unit => int = "i_finish"
    let fs = []
    for i in 2 to iFinish() {
      fs->Array.push(() => i)
    }
Before (js):
    for (let i = 2, i_finish = i_finish(); i <= i_finish; ++i) {
      fs.push(() => i);
    }
After (js):
    for (let i = 2, i_finish$1 = i_finish(); i <= i_finish$1; ++i) {
      fs.push(() => i);
    }

Review: Does the start's temporary need the same? No: lam_compile creates
    `i_start` before Js_pass_external_shadow runs, which rewrites a
    reference to a global `i_start` in its scope to `globalThis.i_start`.
Review: Which checked-in outputs change? None besides the new
    for_loop_finish_global_test.mjs.
Signed-off-by: Rob <illusionalsagacity@users.noreply.github.com>
@cknitt

cknitt commented Nov 27, 2026

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: c65c375dda

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread compiler/backend/js_dump.ml Outdated
let cxt = pp_var_assign cxt f id in
(expression ~level:0 cxt f ident_expression, None)
| Some ident_expression, _ ->
| ident_expression, _ ->

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve in parentheses for formerly hoisted loop starts

When a loop's start is a call and its end first binds n through a try, then returns if Dict.has(d, "x") { n } else { 2 }, the remaining end expression is a conditional containing in. This newly shared branch prints it at level 1, yielding for (let i = i_start, i_finish = "x" in d ? n : 2; ...), which Node rejects as an invalid for-in declaration, preventing the module from loading. The removed None branch printed the end at level 15 and therefore kept it parenthesized. Preserve that protection, or explicitly handle the NoIn grammar, when routing these loops through this branch.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Real. The start and the end temporary of a loop are declaration initializers in the for header, where an unbracketed in (what Dict.has compiles to) makes JavaScript read a for...in, so the module fails to load with a SyntaxError. A bare in in a loop header predates this PR (for i in 0 to (Dict.has(d, "x") ? 3 : 2) already printed i_finish = "x" in d ? 3 : 2), and that is what #9423 fixes. This PR now builds on #9423, whose NoIn handling covers every initializer of the header, including the end binding this PR adds, which now prints i_finish = ("x" in d) ? n : 2.

Regression tests: "an end using in after a start that runs first" (your case) and "an end using in in a conditional" in for_loop_closure_test, added in bebfad9.

Investigated by Claude.

closures in the body would all see its final value. *)
let held, e1 =
evaluate_now
~name:(Ext_ident.derived_name id ~suffix:"_start")

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Keep synthesized start names clear of raw FFI names

When the end needs statements, a loop inside a function using @val external start: unit => int = "i_start", backed by a module-local %%raw function named i_start, now gains a local binding of exactly that name. Js_pass_external_shadow consequently rewrites the start call to globalThis.i_start(). Module-local raw declarations are not properties of globalThis, so this throws TypeError instead of calling the function; the parent had no synthesized i_start binding and worked. Keep this synthesized start name clear of raw JS names too, rather than relying on the shadow pass's globalThis rewrite.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Real. With %%raw("function i_start() { return 1 }") and @val external start: unit => int = "i_start", for i in start() to { try g() catch { | _ => 0 } } compiled to let i_start = globalThis.i_start();, and Node threw TypeError: globalThis.i_start is not a function.

Fixed in c5baa2c. Ext_ident.create_tmp now flags its identifier as synthesized. Ext_pp_scope gives a synthesized identifier a name that is none of the raw JS names the module uses, and Js_pass_external_shadow no longer counts it as shadowing. The start now prints as let i_start$1 = i_start();. The printer's i_finish uses create_tmp as well, which replaces Ext_pp_scope.printer_ident, so every compiler temporary follows the same rule. Regression test: "start calling a raw function named like its temporary" in for_loop_finish_global_test.

Investigated by Claude.

illusionalsagacity added a commit to illusionalsagacity/rescript-compiler that referenced this pull request Nov 27, 2026
Why:
    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. This
    answers Codex's review finding on rescript-lang#9417: the previous commit made the
    temporary of an uppercase exotic loop variable readable (`End_finish`),
    so it could now equal a global's name; a lowercase loop variable had
    the same bug before.

JS modified (end of a for loop calling a global named like its temporary):
Example:
    @Val external iFinish: unit => int = "i_finish"
    let fs = []
    for i in 2 to iFinish() {
      fs->Array.push(() => i)
    }
Before (js):
    for (let i = 2, i_finish = i_finish(); i <= i_finish; ++i) {
      fs.push(() => i);
    }
After (js):
    for (let i = 2, i_finish$1 = i_finish(); i <= i_finish$1; ++i) {
      fs.push(() => i);
    }

Review: Does the start's temporary need the same? No: lam_compile creates
    `i_start` before Js_pass_external_shadow runs, which rewrites a
    reference to a global `i_start` in its scope to `globalThis.i_start`.
Review: Which checked-in outputs change? None besides the new
    for_loop_finish_global_test.mjs.
Signed-off-by: Rob <illusionalsagacity@users.noreply.github.com>
illusionalsagacity added a commit to illusionalsagacity/rescript-compiler that referenced this pull request Nov 27, 2026
Why:
    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. The printer's `i_finish` is created
    with create_tmp too, which replaces Ext_pp_scope.printer_ident. This
    answers Codex's review finding on rescript-lang#9417.

JS modified (start of a for loop calling a raw function named like its temporary):
Example:
    %%raw(`
    function i_start() { return 1 }
    `)
    @Val external start: unit => int = "i_start"
    let f = g => {
      let fs = []
      for i in start() to {
        try g() catch { | _ => 0 }
      } {
        fs->Array.push(() => i)
      }
      fs->Array.map(h => h())
    }
Before (js):
    let i_start = globalThis.i_start();
After (js):
    let i_start$1 = i_start();

Review: Which other outputs can change? Any temporary from create_tmp,
    such as `tmp`, named like a raw JS name in its scope now gets a
    `$N` suffix instead of the reference going through `globalThis`. No
    checked-in output besides for_loop_finish_global_test.mjs changes.
Signed-off-by: Rob <illusionalsagacity@users.noreply.github.com>
illusionalsagacity added a commit to illusionalsagacity/rescript-compiler that referenced this pull request Nov 27, 2026
The first commit prints the end of a loop whose start must run before
the end as the end temporary in the loop header. An end that binds
through a `try` and then tests `Dict.has`, from Codex's review of
rescript-lang#9417, and a conditional end using `Dict.has` print an `in` there,
which JavaScript reads as a `for...in` unless it is in parentheses.
rescript-lang#9423's handling of the loop header gives them parentheses; these tests
check that both loops run.

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

cknitt commented Nov 28, 2026

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep it up!

Reviewed commit: bebfad9a92

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

… before the end

Why:
    When a `for` loop's start is not safe to delay (a call, or a read of a
    mutable variable or field) 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. The
    start is now held in a temporary named after the loop variable
    (`i_start`, through `evaluate_now`) and the loop declares `i` itself.
    No loop is built without a start any more, so `J.ForRange` and
    `S.for_` now take the start expression rather than an option.
    Both temporaries of a loop, `i_start` and `i_finish`, now drop the
    quotes of an uppercase exotic loop variable rather than mangle them.

JS modified (for loop with a start evaluated before its end):
Example:
    @inline(never) let id = x => x
    let fs = []
    for i in id(0) to try { id(1) } catch { | _ => 0 } {
      fs->Array.push(() => i)
    }
Before (js):
    let i = id(0);

    let tmp;

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

    for (; i <= tmp; ++i) {
      fs.push(() => i);
    }
After (js):
    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);
    }

JS modified (temporaries of an uppercase exotic loop variable):
Example:
    @inline(never) let id = x => x
    let fs = []
    for \"End" in 3 to id(4) {
      fs->Array.push(() => \"End")
    }
Before (js):
    for (let End = 3, $unknown$unknownEnd$unknown_finish = id(4); End <= $unknown$unknownEnd$unknown_finish; ++End) {
      fs.push(() => End);
    }
After (js):
    for (let End = 3, End_finish = id(4); End <= End_finish; ++End) {
      fs.push(() => End);
    }

Review: Are loops with a constant or immutable start affected? No: such a
    start is delay safe and stays in the loop header as before.
Review: Is the end still re-read each iteration when it is a variable? Yes,
    unchanged here; rescript-lang#9356 tracks it.
Review: Which checked-in outputs change? argument_evaluation_order_test.mjs,
    whose loop now declares `i` in its header.
Signed-off-by: Rob <illusionalsagacity@users.noreply.github.com>
Why:
    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. This
    answers Codex's review finding on rescript-lang#9417: the previous commit made the
    temporary of an uppercase exotic loop variable readable (`End_finish`),
    so it could now equal a global's name; a lowercase loop variable had
    the same bug before.

JS modified (end of a for loop calling a global named like its temporary):
Example:
    @Val external iFinish: unit => int = "i_finish"
    let fs = []
    for i in 2 to iFinish() {
      fs->Array.push(() => i)
    }
Before (js):
    for (let i = 2, i_finish = i_finish(); i <= i_finish; ++i) {
      fs.push(() => i);
    }
After (js):
    for (let i = 2, i_finish$1 = i_finish(); i <= i_finish$1; ++i) {
      fs.push(() => i);
    }

Review: Does the start's temporary need the same? No: lam_compile creates
    `i_start` before Js_pass_external_shadow runs, which rewrites a
    reference to a global `i_start` in its scope to `globalThis.i_start`.
Review: Which checked-in outputs change? None besides the new
    for_loop_finish_global_test.mjs.
Signed-off-by: Rob <illusionalsagacity@users.noreply.github.com>
Why:
    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. The printer's `i_finish` is created
    with create_tmp too, which replaces Ext_pp_scope.printer_ident. This
    answers Codex's review finding on rescript-lang#9417.

JS modified (start of a for loop calling a raw function named like its temporary):
Example:
    %%raw(`
    function i_start() { return 1 }
    `)
    @Val external start: unit => int = "i_start"
    let f = g => {
      let fs = []
      for i in start() to {
        try g() catch { | _ => 0 }
      } {
        fs->Array.push(() => i)
      }
      fs->Array.map(h => h())
    }
Before (js):
    let i_start = globalThis.i_start();
After (js):
    let i_start$1 = i_start();

Review: Which other outputs can change? Any temporary from create_tmp,
    such as `tmp`, named like a raw JS name in its scope now gets a
    `$N` suffix instead of the reference going through `globalThis`. No
    checked-in output besides for_loop_finish_global_test.mjs changes.
Signed-off-by: Rob <illusionalsagacity@users.noreply.github.com>
The first commit prints the end of a loop whose start must run before
the end as the end temporary in the loop header. An end that binds
through a `try` and then tests `Dict.has`, from Codex's review of
rescript-lang#9417, and a conditional end using `Dict.has` print an `in` there,
which JavaScript reads as a `for...in` unless it is in parentheses.
rescript-lang#9423's handling of the loop header gives them parentheses; these tests
check that both loops run.

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

@cknitt cknitt left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good to me. I checked the new commits (end temporaries vs JS globals, synthesized names vs raw JS names, in in the end temporary), built it merged with current master and regenerated all test outputs: no diffs, all tests pass. I rebased it onto master after #9423 was merged.

This review was done by Claude.

@cknitt
cknitt merged commit 3b2d03e into rescript-lang:master Nov 28, 2026
23 checks passed
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.

2 participants