Skip to content

Negate floats as -0 - x and parenthesize ** under prefix operators - #9422

Merged
cknitt merged 2 commits into
rescript-lang:masterfrom
illusionalsagacity:fix-unary-minus-printing
Nov 27, 2026
Merged

cknitt merged 2 commits into
rescript-lang:masterfrom
illusionalsagacity:fix-unary-minus-printing

Conversation

@illusionalsagacity

@illusionalsagacity illusionalsagacity commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

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

Problem

The JS IR represents a negation as a subtraction from zero, and the printer printed every 0 - x as -x. For floats that is wrong: 0. -. x is 0 when x is 0., but -x is -0.

let fromLiteral = x => 0. -. x
let fromInt = x => Float.fromInt(0) -. x
let negate = x => -.x
let negateInt = (x: int) => -x

Before:

function fromLiteral(x) {
  return - x;
}

function fromInt(x) {
  return -x;
}

function negate(x) {
  return - x;
}

function negateInt(x) {
  return -x | 0;
}

After:

function fromLiteral(x) {
  return 0 - x;
}

function fromInt(x) {
  return 0 - x;
}

function negate(x) {
  return - x;
}

function negateInt(x) {
  return -x | 0;
}

A subtraction from a negative zero literal was printed in full:

let f = x => -0. -. x

Before: return -0 - x;. After: return - x;.

Prefix operators (float negation, ~ on a bigint, typeof, await) also printed a power without parentheses, which is a syntax error:

let negate = (a: float, b: float) => -.(a ** b)
let bitNot = (a: bigint, b: bigint) => ~~~(a ** b)
let typeOf = (a: float, b: float) => typeof(a ** b)
let wait = async (a: float, b: float) => await Obj.magic(a ** b)

Before:

function negate(a, b) {
  return - a ** b;
}

function bitNot(a, b) {
  return ~a ** b;
}

function typeOf(a, b) {
  return typeof a ** b;
}

async function wait(a, b) {
  return await a ** b;
}

After:

function negate(a, b) {
  return - (a ** b);
}

function bitNot(a, b) {
  return ~(a ** b);
}

function typeOf(a, b) {
  return typeof (a ** b);
}

async function wait(a, b) {
  return await (a ** b);
}

Where an int negation is printed as -x, an operand that itself prints with a leading minus is kept apart by a space, so -(%raw("-5"): int) prints - -5 | 0 and not --5 | 0 (a syntax error). This uses prints_with_leading_minus from #9415, which also knows negative float and bigint literals, raw JavaScript and JSON literals. Of the subtractions, only -0 - x now prints with a leading minus, so that is the one subtraction it matches.

Fix

  • A float negation is a subtraction from -0., which equals -x for every x, and only that prints as - x.
  • An int negation stays 0 - x. It prints as -x only as the operand of a bitwise operator, such as the | 0 of every int subtraction, which drops the sign of a zero.
  • The operands of all prefix operators go through unary_operand.

Tests

unary_minus_test.res covers negation, powers under every prefix operator, negated operands on both sides of every bitwise operator, and int negation of raw JavaScript, a negative zero, a float negation and a negative bigint. The bigint case prints - -5n | 0, which parses and then throws a TypeError for mixing a bigint and an int; the test checks for that TypeError. Three %identity externals are needed to reach some of these shapes.

In float_add_fold_test.mjs from #9415, subtractions from a zero int such as - -5 now print as 0 - -5, which is still correct. Its case Float.fromInt(0) -. (Obj.magic(-5n): float) would print 0 - -5n and throw "Cannot mix BigInt and other types", so it now negates the bigint with -.(Obj.magic(-5n): float), which prints - -5n.

Merging

Based on #9415 (fix-float-add-fold), so its commit shows up here until it merges. This should merge after #9415.

12.x

12.x has the same bug: there unary_minus_test doesn't even load ("Unary operator used immediately before exponentiation expression"). 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

❌ Patch coverage is 77.77778% with 8 lines in your changes missing coverage. Please review.
✅ Project coverage is 82.25%. Comparing base (6a7e3b8) to head (bb6811d).

Files with missing lines Patch % Lines
compiler/backend/js_dump.ml 76.47% 8 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master    #9422      +/-   ##
==========================================
- Coverage   82.25%   82.25%   -0.01%     
==========================================
  Files         462      462              
  Lines       65650    65672      +22     
==========================================
+ Hits        53999    54016      +17     
- Misses      11651    11656       +5     
Files with missing lines Coverage Δ
compiler/backend/js_exp_make.ml 67.53% <100.00%> (+0.04%) ⬆️
compiler/backend/lam_compile_primitive.ml 81.49% <100.00%> (ø)
compiler/backend/js_dump.ml 92.35% <76.47%> (-0.61%) ⬇️

... 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 0. -. x and Float.fromInt(0) -. x giving -0 instead of 0 when x is 0., and a syntax error in the generated JavaScript for ** as the operand of a float negation, ~~~ on a bigint, typeof or await.

Semantic Diff

2 commits · Full page

Negate floats as -0 - x and parenthesize ** under prefix operators

c889611 · illusionalsagacity · Nov 25, 2026, 19:30 UTC

Why

The JS IR represents a negation as a subtraction from zero, and the printer printed every 0 - x as -x. That is wrong for a float subtraction: 0. -. x is 0 when x is 0., but -x is -0. A float negation is now a subtraction from -0., which equals -x for every x, and only that is printed as - x. An int negation stays 0 - x; it is printed as -x only as the operand of a bitwise operator, such as the | 0 of every int subtraction, which drops the sign of a zero. Prefix operators also printed their operand at the level of **, so a power had no parentheses there, which JavaScript rejects. This concerned a float negation, ~ on a bigint, typeof and await; the operands of all prefix operators now go through unary_operand. Where 0 - x is printed as -x, an x that prints with a leading minus is kept apart by a space, as found by prints_with_leading_minus; of the subtractions, only -0 - x prints with a leading minus now.

JS modified (subtraction from zero)

let fromLiteral = x => 0. -. x
let fromInt = x => Float.fromInt(0) -. x
let negate = x => -.x
let negateInt = (x: int) => -x

js

 function fromLiteral(x) {
-  return - x;
+  return 0 - x;
 }
 
 function fromInt(x) {
-  return -x;
+  return 0 - x;
 }
 
 function negate(x) {
   return - x;
 }
 
 function negateInt(x) {
   return -x | 0;
 }

JS modified (subtraction from a negative zero literal)

let f = x => -0. -. x

js

-return -0 - x;
+return - x;

JS modified (power under a prefix operator)

let negate = (a: float, b: float) => -.(a ** b)
let bitNot = (a: bigint, b: bigint) => ~~~(a ** b)
let typeOf = (a: float, b: float) => typeof(a ** b)
let wait = async (a: float, b: float) => await Obj.magic(a ** b)

js · Before: a syntax error

 function negate(a, b) {
-  return - a ** b;
+  return - (a ** b);
 }
 
 function bitNot(a, b) {
-  return ~a ** b;
+  return ~(a ** b);
 }
 
 function typeOf(a, b) {
-  return typeof a ** b;
+  return typeof (a ** b);
 }
 
 async function wait(a, b) {
-  return await a ** b;
+  return await (a ** b);
 }

Review

  • Why decide the int case by the enclosing operator? Inlining can put an int literal into a float subtraction, so a left operand 0 does not tell an int from a float, but the sign of a zero never survives a bitwise operator.
  • Which checked-in outputs change? Only float_add_fold_test.mjs: a subtraction from a zero int such as - -5 now prints as 0 - -5. Its case for a negative bigint, which this would turn into 0 - -5n and a "Cannot mix BigInt" error, negates the bigint with -. instead.
Test int negation of operands printed with a leading minus

bb6811d · illusionalsagacity · Nov 27, 2026, 16:03 UTC

Why

Under a bitwise operator, 0 - x is printed as -x, and an x that prints with a leading minus is kept apart by a space. The tests only covered int and float literals, so they now also negate raw JavaScript, a raw literal in an identity Some, a negative zero, a float negation and a negative bigint, whose - -5n | 0 parses and then throws a TypeError. is_pow lists every expression kind instead of ending in a wildcard, so a new kind has to be decided there, and a test case that appeared twice is gone.

Review

  • Does any output change? No compiler output does; only the tests of unary_minus_test.res are added or moved.

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

@rescript/belt

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

@rescript/darwin-arm64

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

@rescript/linux-arm64

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

@rescript/linux-x64

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

@rescript/runtime

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

@rescript/win32-x64

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

commit: bb6811d

@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-27T19:43:05.232707Z 458fb9c 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. 🎉

Reviewed commit: 53b0747d09

ℹ️ 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 commented Nov 27, 2026

Copy link
Copy Markdown
Member

The float fixes and the ** parentheses look right to me.

One case of -- is still printed, so the changelog's claim isn't fully true yet:

let f = () => -(%raw("-5"): int)       // return --5 | 0;   SyntaxError
let g = () => -(Obj.magic(-5n): int)   // return --5n | 0;  SyntaxError

starts_with_minus in int32_operand only knows int/float literals, -0 - x and an identity Some. It doesn't know raw JS code, JSON literals or negative bigints that start with -.

#9415 adds prints_with_leading_minus, which covers all of these, and the two PRs conflict in that same printer case. I'd land #9415 first and rebase this one onto it. Use prints_with_leading_minus instead of starts_with_minus, and change its Bin (Minus, Int 0l | Float "0.") case to Bin (Minus, Float "-0."), because after this PR only -0 - x prints with a leading -. I tried that locally: it builds, fixes the cases above, and gives the same unary_minus_test output as this PR.

After that rebase, #9415's float_add_fold_test output changes (- -5 becomes 0 - -5 and so on, all still correct). Its Float.fromInt(0) -. (Obj.magic(-5n): float) case then throws "Cannot mix BigInt and other types", so that test case should be dropped or changed.

Small things: is_pow and starts_with_minus end in | _ -> false. Listing the constructors, as #9415 does, would make sure new expression kinds get handled. Also, -id(5) &&& 3 is tested twice.

This review was done by Claude.

@illusionalsagacity

Copy link
Copy Markdown
Contributor Author

Thanks. I rebased this onto #9415, so its commit shows up here until #9415 merges. This should merge after #9415.

  • -- for raw code, JSON and negative bigints: int32_operand now uses prints_with_leading_minus. starts_with_minus is gone. That change is in 4dc8f05 and not in a separate commit: the rebase removes Fold float addition of int literals only when the sum is exact #9415's only call of prints_with_leading_minus, so the commit wouldn't build if that call weren't moved. -(%raw("-5"): int) now prints - -5 | 0, and -(Obj.magic(-5n): int) prints - -5n | 0.
  • Bin (Minus, Float "-0.") case: changed as you suggested, also in 4dc8f05. I checked the printer: the only subtraction case left in expression_desc is -0 - x, printed as - x. 0 - x prints as -x only from int32_operand, and its operand goes through unary_operand at level 13 or 14, so a nested 0 - y there is parenthesized. The doc comment now says this too.
  • float_add_fold_test: the output changes as you described (- -5 becomes 0 - -5 and so on). I kept the bigint case and made it a float negation, -.(Obj.magic(-5n): float), which prints - -5n and gives 5n. It still checks that a negative bigint operand gets a space. This is in 4dc8f05 along with the regenerated .mjs, so every commit passes its tests.
  • Tests for the new leading-minus forms (458fb9c): unary_minus_test now negates as an int: %raw("-5"), the same value inside an identity Some, %raw("-5") as a bitwise operand, Obj.magic(-5.5), Obj.magic(-0.), and a float negation. The negative bigint case parses but then throws a TypeError for mixing a bigint and an int, so the test checks for that TypeError. A JSON literal can't be reached as the operand from source: @as(json\...`)` only appears as an argument of an external call. So that case has no test.
  • | _ -> false catch-alls: is_pow now lists every expression kind, the same way prints_with_leading_minus does (458fb9c). starts_with_minus no longer exists.
  • Duplicate -id(5) &&& 3: removed (458fb9c). 1 << -id(-3) was duplicated the same way, so that one is removed too.
  • Changelog: -- is now only claimed in Fold float addition of int literals only when the sum is exact #9415's fragment. This PR's fragment covers the -0 result and the ** syntax errors.

Investigated by Claude.

@cknitt

cknitt commented Nov 27, 2026

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 458fb9cb46

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

Thanks, all points are addressed. This should merge after #9415.

This review was done by Claude.

Why:
    The JS IR represents a negation as a subtraction from zero, and the
    printer printed every `0 - x` as `-x`. That is wrong for a float
    subtraction: `0. -. x` is `0` when `x` is `0.`, but `-x` is `-0`.
    A float negation is now a subtraction from `-0.`, which equals `-x`
    for every `x`, and only that is printed as `- x`. An int negation
    stays `0 - x`; it is printed as `-x` only as the operand of a bitwise
    operator, such as the `| 0` of every int subtraction, which drops the
    sign of a zero.
    Prefix operators also printed their operand at the level of `**`, so a
    power had no parentheses there, which JavaScript rejects. This concerned
    a float negation, `~` on a bigint, `typeof` and `await`; the operands
    of all prefix operators now go through `unary_operand`.
    Where `0 - x` is printed as `-x`, an `x` that prints with a leading
    minus is kept apart by a space, as found by `prints_with_leading_minus`;
    of the subtractions, only `-0 - x` prints with a leading minus now.

JS modified (subtraction from zero):
Example:
    let fromLiteral = x => 0. -. x
    let fromInt = x => Float.fromInt(0) -. x
    let negate = x => -.x
    let negateInt = (x: int) => -x
Before (js):
    function fromLiteral(x) {
      return - x;
    }

    function fromInt(x) {
      return -x;
    }

    function negate(x) {
      return - x;
    }

    function negateInt(x) {
      return -x | 0;
    }
After (js):
    function fromLiteral(x) {
      return 0 - x;
    }

    function fromInt(x) {
      return 0 - x;
    }

    function negate(x) {
      return - x;
    }

    function negateInt(x) {
      return -x | 0;
    }

JS modified (subtraction from a negative zero literal):
Example:
    let f = x => -0. -. x
Before (js): return -0 - x;
After (js): return - x;

JS modified (power under a prefix operator):
Example:
    let negate = (a: float, b: float) => -.(a ** b)
    let bitNot = (a: bigint, b: bigint) => ~~~(a ** b)
    let typeOf = (a: float, b: float) => typeof(a ** b)
    let wait = async (a: float, b: float) => await Obj.magic(a ** b)
Before (js): a syntax error
    function negate(a, b) {
      return - a ** b;
    }

    function bitNot(a, b) {
      return ~a ** b;
    }

    function typeOf(a, b) {
      return typeof a ** b;
    }

    async function wait(a, b) {
      return await a ** b;
    }
After (js):
    function negate(a, b) {
      return - (a ** b);
    }

    function bitNot(a, b) {
      return ~(a ** b);
    }

    function typeOf(a, b) {
      return typeof (a ** b);
    }

    async function wait(a, b) {
      return await (a ** b);
    }

Review: Why decide the int case by the enclosing operator? Inlining can put
    an int literal into a float subtraction, so a left operand `0` does not
    tell an int from a float, but the sign of a zero never survives a bitwise
    operator.
Review: Which checked-in outputs change? Only float_add_fold_test.mjs: a
    subtraction from a zero int such as `- -5` now prints as `0 - -5`. Its
    case for a negative bigint, which this would turn into `0 - -5n` and a
    "Cannot mix BigInt" error, negates the bigint with `-.` instead.

Signed-off-by: Rob <illusionalsagacity@users.noreply.github.com>
Why:
    Under a bitwise operator, `0 - x` is printed as `-x`, and an `x`
    that prints with a leading minus is kept apart by a space. The tests
    only covered int and float literals, so they now also negate raw
    JavaScript, a raw literal in an identity `Some`, a negative zero, a
    float negation and a negative bigint, whose `- -5n | 0` parses and
    then throws a TypeError. `is_pow` lists every expression kind
    instead of ending in a wildcard, so a new kind has to be decided
    there, and a test case that appeared twice is gone.

Review: Does any output change? No compiler output does; only the
    tests of unary_minus_test.res are added or moved.
Signed-off-by: Rob <illusionalsagacity@users.noreply.github.com>
@cknitt
cknitt force-pushed the fix-unary-minus-printing branch from 458fb9c to bb6811d Compare November 27, 2026 19:52
@illusionalsagacity
illusionalsagacity marked this pull request as ready for review November 27, 2026 20:00
@cknitt
cknitt merged commit ccfc979 into rescript-lang:master Nov 27, 2026
23 checks passed
@illusionalsagacity
illusionalsagacity deleted the fix-unary-minus-printing branch November 27, 2026 20:22
cknitt added a commit to illusionalsagacity/rescript-compiler that referenced this pull request Nov 28, 2026
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 added a commit that referenced this pull request Nov 28, 2026
* Evaluate self tail call arguments left to right

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>

* Update unary_minus_test output for left-to-right tail call arguments

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

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>

---------

Signed-off-by: Rob <illusionalsagacity@users.noreply.github.com>
Signed-off-by: Christoph Knittel <ck@cca.io>
Co-authored-by: Christoph Knittel <ck@cca.io>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.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