Skip to content

Parenthesise the in operator in a for loop's header - #9423

Merged
cknitt merged 1 commit into
rescript-lang:masterfrom
illusionalsagacity:fix-for-loop-in-operator
Nov 28, 2026
Merged

cknitt merged 1 commit into
rescript-lang:masterfrom
illusionalsagacity:fix-for-loop-in-operator

Conversation

@illusionalsagacity

@illusionalsagacity illusionalsagacity commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

Part of #9398 (item 37). Found while reviewing the fixes for it.

Problem

JS doesn't allow a bare in in the initializer of a for header, so a start or end using Dict.has was a syntax error.

let f = (d, g) => {
  for i in 0 to d->Dict.has("a") ? 5 : 4 {
    g(i)
  }
}

Before:

for (let i = 0, i_finish = "a" in d ? 5 : 4; i <= i_finish; ++i) {
  g(i);
}

After:

for (let i = 0, i_finish = ("a" in d) ? 5 : 4; i <= i_finish; ++i) {
  g(i);
}

Fix

While Js_dump prints the initializer, Ext_pp records that in is forbidden until the next brackets, and In is printed in parentheses there.

Tests

for_loop_in_operator_test.res. No existing output changes.

Merging

Conflicts in js_dump.ml with fix-printer-operand-levels. I'll rebase whichever lands later.

12.x

12.x has the same bug: there for_loop_in_operator_test doesn't load ("Invalid left-hand side in for-in loop"). I'll backport once this one is reviewed.

The fix was written by Claude.

@codecov

codecov Bot commented Nov 26, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 82.28%. Comparing base (ecb21d0) to head (96b9d93).

Additional details and impacted files
@@           Coverage Diff           @@
##           master    #9423   +/-   ##
=======================================
  Coverage   82.27%   82.28%           
=======================================
  Files         462      462           
  Lines       65674    65683    +9     
=======================================
+ Hits        54035    54045   +10     
+ Misses      11639    11638    -1     
Files with missing lines Coverage Δ
compiler/backend/ext_pp.ml 95.95% <100.00%> (+0.26%) ⬆️
compiler/backend/js_dump.ml 92.52% <100.00%> (+0.02%) ⬆️

... 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.

@github-actions

github-actions Bot commented Nov 26, 2026 •

Copy link
Copy Markdown

Changelog

🐛 Bug fix

  • Fix invalid JavaScript for a for loop whose start or end uses the in operator, as from Dict.has.

Semantic Diff

1 commit · Full page

Parenthesise the in operator in a for loop's header

96b9d93 · illusionalsagacity · Nov 25, 2026, 19:31 UTC

Why

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.

JS modified (for loop whose end uses in)

let f = (d, g) => {
  for i in 0 to d->Dict.has("a") ? 5 : 4 {
    g(i)
  }
}

js · Before: a syntax error

-for (let i = 0, i_finish = "a" in d ? 5 : 4; i <= i_finish; ++i) {
+for (let i = 0, i_finish = ("a" in d) ? 5 : 4; i <= i_finish; ++i) {
   g(i);
 }

JS modified (for loop whose start uses in)

let f = (d, g) => {
  for i in d->Dict.has("a") ? 1 : 2 to 3 {
    g(i)
  }
}

js · Before: a syntax error

-for (let i = "a" in d ? 1 : 2; i <= 3; ++i) {
+for (let i = ("a" in d) ? 1 : 2; i <= 3; ++i) {
   g(i);
 }

Review

  • Does an in already inside brackets, such as a call's argument, get parentheses? No: every bracket the printer opens through Ext_pp allows in again. Only brackets it writes as plain strings, such as a template's ${…}, don't, so an in there gets redundant but valid parentheses.
  • Which checked-in outputs change? None, besides the new test's.

@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@9423

@rescript/belt

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

@rescript/darwin-arm64

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

@rescript/linux-arm64

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

@rescript/linux-x64

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

@rescript/runtime

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

@rescript/win32-x64

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

commit: 96b9d93

@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:52:00.638103Z 96b9d93 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

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Delightful!

Reviewed commit: 3ccb78aa18

ℹ️ 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".

@illusionalsagacity
illusionalsagacity marked this pull request as ready for review November 27, 2026 20:00
Why:
    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.

JS modified (for loop whose end uses `in`):
Example:
    let f = (d, g) => {
      for i in 0 to d->Dict.has("a") ? 5 : 4 {
        g(i)
      }
    }
Before (js): a syntax error
    for (let i = 0, i_finish = "a" in d ? 5 : 4; i <= i_finish; ++i) {
      g(i);
    }
After (js):
    for (let i = 0, i_finish = ("a" in d) ? 5 : 4; i <= i_finish; ++i) {
      g(i);
    }

JS modified (for loop whose start uses `in`):
Example:
    let f = (d, g) => {
      for i in d->Dict.has("a") ? 1 : 2 to 3 {
        g(i)
      }
    }
Before (js): a syntax error
    for (let i = "a" in d ? 1 : 2; i <= 3; ++i) {
      g(i);
    }
After (js):
    for (let i = ("a" in d) ? 1 : 2; i <= 3; ++i) {
      g(i);
    }

Review: Does an `in` already inside brackets, such as a call's argument, get
    parentheses? No: every bracket the printer opens through `Ext_pp` allows
    `in` again. Only brackets it writes as plain strings, such as a template's
    `${…}`, don't, so an `in` there gets redundant but valid parentheses.
Review: Which checked-in outputs change? None, besides the new test's.
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. Bravo.

Reviewed commit: 96b9d93143

ℹ️ 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".

@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 rebase onto #9428 (the In case keeps #9428's levels and adds the for-header check), built it merged with current master, and regenerated all test outputs: no diffs, all tests pass.

This review was done by Claude.

@cknitt
cknitt merged commit 3172330 into rescript-lang:master Nov 28, 2026
37 of 38 checks passed
cknitt pushed a commit to illusionalsagacity/rescript-compiler that referenced this pull request Nov 28, 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 pushed a commit that referenced this pull request Nov 28, 2026
… before the end (#9417)

* Give each for loop iteration its own variable when the start must run 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; #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>

* Keep a for loop's end temporary from capturing a JS global of its name

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):
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>

* Keep compiler temporaries clear of the raw JS names a module uses

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):
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>

* Test a for loop's end temporary that uses `in`

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.

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

---------

Signed-off-by: Rob <illusionalsagacity@users.noreply.github.com>
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