Repository navigation
Give each for loop iteration its own variable when the start must run before the end - #9417
Conversation
Changelog🐛 Bug fix
Semantic Diff4 commits · Full page Give each for loop iteration its own variable when the start must run before the endfb5c6fb · illusionalsagacity · Nov 23, 2026, 20:27 UTC
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)
}
-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")
}
-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
Keep a for loop's end temporary from capturing a JS global of its name247bd56 · illusionalsagacity · Nov 26, 2026, 22:09 UTC
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)
}
-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
Keep compiler temporaries clear of the raw JS names a module uses53c3c63 · illusionalsagacity · Nov 27, 2026, 21:32 UTC
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())
}
-let i_start = globalThis.i_start();
+let i_start$1 = i_start();Review
Test a for loop's end temporary that uses
|
Codecov Report❌ Patch coverage is
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
🚀 New features to boost your workflow:
|
rescript
@rescript/belt
@rescript/darwin-arm64
@rescript/linux-arm64
@rescript/linux-x64
@rescript/runtime
@rescript/win32-x64
commit: |
|
@codex review |
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 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".
| let id = | ||
| Ext_ident.create (Ident.name id ^ "_finish") | ||
| Ext_ident.create | ||
| (Ext_ident.derived_name id ~suffix:"_finish") |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
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>
|
@codex review |
There was a problem hiding this comment.
💡 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".
| let cxt = pp_var_assign cxt f id in | ||
| (expression ~level:0 cxt f ident_expression, None) | ||
| | Some ident_expression, _ -> | ||
| | ident_expression, _ -> |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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") |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
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>
c65c375 to
bebfad9
Compare
|
@codex review |
|
Codex Review: Didn't find any major issues. Keep it up! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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>
bebfad9 to
509986a
Compare
cknitt
left a comment
There was a problem hiding this comment.
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.
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
inin 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
forloop's start can't be delayed (a call, or a mutable read) and its end needs statements (atryor aswitch), 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.Before:
After:
Fix
The start is held in a temporary (
i_start, throughevaluate_now) and the loop declaresiitself. No loop is built without a start any more, soJ.ForRangeandS.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
_startand_finishnames are now readable for an uppercase exotic loop variable (Bar_finishinstead of$unknown$unknownBar$unknown_finish).The
_finishtemporary 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()printedfor (let i = 2, i_finish = i_finish(); ...), which throws aReferenceErrorbecause the end reads the temporary before it is initialized. It now printsi_finish$1 = i_finish(). The printer creates this temporary afterJs_pass_external_shadowhas run, so the newExt_pp_scope.printer_identgives 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.rescoversto,downto, an empty range and that the start runs before the end's statements.for_loop_finish_global_test.rescovers 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 inargument_evaluation_order_test.mjsnow declaresiin 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 againstmaintenance/12.xonce 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.