Skip to content

Evaluate self tail call arguments left to right - #9419

Merged
cknitt merged 2 commits into
rescript-lang:masterfrom
illusionalsagacity:fix-tail-call-argument-order
Nov 28, 2026
Merged

cknitt merged 2 commits into
rescript-lang:masterfrom
illusionalsagacity:fix-tail-call-argument-order

Conversation

@illusionalsagacity

Copy link
Copy Markdown
Contributor

Part of #9398 (item 12).

Problem

A self tail call is compiled to a loop that reassigns the parameters. The assignments were emitted in reverse order, so the arguments were evaluated right to left, unlike any other call. If a later argument mutates state that an earlier one reads, the result is wrong.

let rec f = (a, b, n) =>
  n == 0 ? a + b : f(Console.log("a") == () ? a : 0, Console.log("b") == () ? b : 0, n - 1)

Before:

_n = n - 1 | 0;
_b = (console.log("b"), undefined) === undefined ? b : 0;
_a = (console.log("a"), undefined) === undefined ? a : 0;
continue;

After:

_a = (console.log("a"), undefined) === undefined ? a : 0;
_b = (console.log("b"), undefined) === undefined ? b : 0;
_n = n - 1 | 0;
continue;

Reviewing this turned up a crash in the same code: a self tail call whose argument count differs from the parameter count, possible through a cast:

let rec f = (a, b) => a == 0 ? b : (Obj.magic(f): int => int)(a - 1)

Before:

Fatal error: exception Invalid_argument("List.fold_left2")

After:

function f(a, b) {
  if (a === 0) {
    return b;
  } else {
    return f(a - 1 | 0);
  }
}

It also turned up a () function dropping its argument's side effects, which can loop forever:

let left = ref(3)
@inline(never) let tick = () => left := left.contents - 1
let rec drain = () => if left.contents > 0 { drain(tick()) } else { 0 }

Before:

function drain() {
  while (true) {
    if (left.contents <= 0) {
      return 0;
    }
    continue;
  };
}

After:

function drain() {
  while (true) {
    if (left.contents <= 0) {
      return 0;
    }
    tick();
    continue;
  };
}

Fix

The assignments are emitted in argument order. Each argument reads the loop's local copies of the parameters, so only the order of side effects changes. A self tail call with a different argument count is compiled as an ordinary call, which uses stack. A () function's argument is evaluated for its side effects.

Code that relied on the old order changes behaviour. Belt's reduce on HashMap, HashSet and MutableSet did: it read the next entry after the callback, so it skipped entries the callback removed. These now bind the callback's result first, so they still do, as forEach does.

Tests

tail_call_argument_order_test.res and belt_reduce_removal_test.res. About 30 checked-in outputs change (Stdlib_List, Primitive_list, the rewatch test repo's Array.mjs and several tests), each only in the order of these assignments.

12.x

12.x has the same bug, and I have a backport ready on fix-tail-call-argument-order-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 a self tail call evaluating its arguments right to left instead of left to right.
  • Fix a self tail call of a () function dropping its argument's side effects.
  • Fix the compiler crashing on a self tail call whose argument count a cast such as Obj.magic makes differ from the parameter count; it is now compiled as an ordinary call.

Semantic Diff

2 commits · Full page

Evaluate self tail call arguments left to right

ecb0119 · illusionalsagacity · Nov 23, 2026, 20:40 UTC

Why

A self tail call is compiled to a loop that reassigns the parameters, and the assignments were emitted in reverse parameter order, so the arguments were evaluated right to left, unlike any other call. When a later argument mutated state an earlier one read, the earlier one saw the mutated value and the function returned a wrong result. The assignments are now emitted in argument order.

A self tail call whose argument count differs from the parameter count, possible through a cast such as Obj.magic, made the compiler crash; it is now compiled as an ordinary call. A self tail call of a () function, which has no JS parameters, dropped its argument together with the argument's side effects, so a loop could run forever; the side effects are now kept. Such a function still loops whatever a cast passes to it.

JS modified (self tail call loops)

let rec f = (a, b, n) =>
  n == 0 ? a + b : f(Console.log("a") == () ? a : 0, Console.log("b") == () ? b : 0, n - 1)

js

-_n = n - 1 | 0;
-_b = (console.log("b"), undefined) === undefined ? b : 0;
 _a = (console.log("a"), undefined) === undefined ? a : 0;
+_b = (console.log("b"), undefined) === undefined ? b : 0;
+_n = n - 1 | 0;
 continue;

Diagnostic modified (self tail call with a different argument count)

let rec f = (a, b) => a == 0 ? b : (Obj.magic(f): int => int)(a - 1)

diagnostic · Before

Fatal error: exception Invalid_argument("List.fold_left2")

js · After

function f(a, b) {
  if (a === 0) {
    return b;
  } else {
    return f(a - 1 | 0);
  }
}

JS modified (self tail call of a () function)

let left = ref(3)
@inline(never) let tick = () => left := left.contents - 1
let rec drain = () => if left.contents > 0 { drain(tick()) } else { 0 }

js

 function drain() {
   while (true) {
     if (left.contents <= 0) {
       return 0;
     }
+    tick();
     continue;
   };
 }

Review

  • Can reordering the assignments change which values the arguments read? No: each argument reads the loop's local copies of the parameters, never the reassigned ones, so only the order of side effects changes; arguments that compile to statements are held in temporaries before any assignment.
  • Does Belt rely on the old order? The reduce of HashMap, HashSet and MutableSet read the rest of the container after its callback only because of it. They now bind the callback's result first, so they still skip entries the callback removes, as forEach does. The other reordered loops of the runtime and Belt only read immutable data or values no callback can change.
  • Which checked-in outputs change? Stdlib_List, Primitive_list, the rewatch test repo's Array.mjs and several tests, each only in the order of those assignments.
✨ Update unary_minus_test output for left-to-right tail call arguments

d53d2b4 · cknitt + Claude · Nov 28, 2026, 06:17 UTC · new

Why

unary_minus_test, added on master by #9422, has a self tail call. With this change its parameters are assigned in argument order, so the checked-in output changes.

JS modified

countdown(_start, _x): _start = 0; is now assigned before _x = x - 1;.

@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.31%. Comparing base (64cdd3c) to head (d53d2b4).

Additional details and impacted files
@@           Coverage Diff           @@
##           master    #9419   +/-   ##
=======================================
  Coverage   82.30%   82.31%           
=======================================
  Files         462      462           
  Lines       65735    65740    +5     
=======================================
+ Hits        54106    54115    +9     
+ Misses      11629    11625    -4     
Files with missing lines Coverage Δ
compiler/backend/lam_compile.ml 90.75% <100.00%> (+0.05%) ⬆️

... and 3 files 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@9419

@rescript/belt

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

@rescript/darwin-arm64

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

@rescript/linux-arm64

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

@rescript/linux-x64

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

@rescript/runtime

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

@rescript/win32-x64

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

commit: d53d2b4

@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-26T20:24:33.361841Z 70de48c 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. Can't wait for the next one!

Reviewed commit: 70de48c3de

ℹ️ 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:
    A self tail call is compiled to a loop that reassigns the parameters,
    and the assignments were emitted in reverse parameter order, so the
    arguments were evaluated right to left, unlike any other call. When a
    later argument mutated state an earlier one read, the earlier one saw
    the mutated value and the function returned a wrong result. The
    assignments are now emitted in argument order.

    A self tail call whose argument count differs from the parameter
    count, possible through a cast such as `Obj.magic`, made the compiler
    crash; it is now compiled as an ordinary call. A self tail call of a
    `()` function, which has no JS parameters, dropped its argument together
    with the argument's side effects, so a loop could run forever; the side
    effects are now kept. Such a function still loops whatever a cast passes
    to it.

JS modified (self tail call loops):
Example:
    let rec f = (a, b, n) =>
      n == 0 ? a + b : f(Console.log("a") == () ? a : 0, Console.log("b") == () ? b : 0, n - 1)
Before (js):
    _n = n - 1 | 0;
    _b = (console.log("b"), undefined) === undefined ? b : 0;
    _a = (console.log("a"), undefined) === undefined ? a : 0;
    continue;
After (js):
    _a = (console.log("a"), undefined) === undefined ? a : 0;
    _b = (console.log("b"), undefined) === undefined ? b : 0;
    _n = n - 1 | 0;
    continue;

Diagnostic modified (self tail call with a different argument count):
Example:
    let rec f = (a, b) => a == 0 ? b : (Obj.magic(f): int => int)(a - 1)
Before (diagnostic):
    Fatal error: exception Invalid_argument("List.fold_left2")
After (js):
    function f(a, b) {
      if (a === 0) {
        return b;
      } else {
        return f(a - 1 | 0);
      }
    }

JS modified (self tail call of a `()` function):
Example:
    let left = ref(3)
    @inline(never) let tick = () => left := left.contents - 1
    let rec drain = () => if left.contents > 0 { drain(tick()) } else { 0 }
Before (js):
    function drain() {
      while (true) {
        if (left.contents <= 0) {
          return 0;
        }
        continue;
      };
    }
After (js):
    function drain() {
      while (true) {
        if (left.contents <= 0) {
          return 0;
        }
        tick();
        continue;
      };
    }

Review: Can reordering the assignments change which values the arguments
    read? No: each argument reads the loop's local copies of the
    parameters, never the reassigned ones, so only the order of side
    effects changes; arguments that compile to statements are held in
    temporaries before any assignment.
Review: Does Belt rely on the old order? The `reduce` of `HashMap`,
    `HashSet` and `MutableSet` read the rest of the container after its
    callback only because of it. They now bind the callback's result first,
    so they still skip entries the callback removes, as `forEach` does. The
    other reordered loops of the runtime and Belt only read immutable data
    or values no callback can change.
Review: Which checked-in outputs change? Stdlib_List, Primitive_list, the
    rewatch test repo's Array.mjs and several tests, each only in the
    order of those assignments.
Signed-off-by: Rob <illusionalsagacity@users.noreply.github.com>
@cknitt
cknitt force-pushed the fix-tail-call-argument-order branch from 70de48c to ecb0119 Compare November 28, 2026 05:50
Why:
    unary_minus_test, added on master by rescript-lang#9422, has a self tail call.
    With this change its parameters are assigned in argument order, so
    the checked-in output changes.

JS modified:
    countdown(_start, _x): `_start = 0;` is now assigned before
    `_x = x - 1;`.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Kbf3gLsfh9mi4MGnZuqcRb
Signed-off-by: Christoph Knittel <ck@cca.io>

@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 built it and checked parameter swaps and rotations, labeled and optional arguments, arguments that compile to statements, and the Belt changes against master. I rebased it onto master and added one commit with the regenerated unary_minus_test output (that test came in with #9422 and has a self tail call).

This review was done by Claude.

@cknitt
cknitt merged commit 3b9f159 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