Semantic Diff

#9400 Fold compare against 0 only where JS operators agree

1 commit

45dba2c9137d6be765c1d8d45f287d739e028498..pr-9400

5e95fc524 · illusionalsagacity · Nov 23, 2026, 20:29 UTC

Fold compare against 0 only where the JS operators agree

Why

Js_exp_make.int_comp rewrites a runtime compare(a, b) that is compared with 0 into the JS operator on a and b. It matched any runtime function named compare without looking at its module, so the structural Primitive_object.compare and Primitive_float.compare were rewritten as well: equal records compared unequal, arrays were ordered as strings, and compare(nan, nan) == 0 was false. The fold now applies only to the compare of Primitive_int, Primitive_bool, Primitive_string and Primitive_bigint.

The same fold read the left of two int constants as unsigned and the right one as signed, so a negative left constant became a large positive number. Both are now read as signed.

modifiedJS compare against 0

type point = {x: int} let equal = (a: point, b: point) => compare(a, b) == 0let less = (a: array<int>, b: array<int>) => compare(a, b) < 0let nanEqual = (a: float, b: float) => compare(a, b) == 0let intLess = (a: int, b: int) => compare(a, b) < 0
js
Before
After
function equal(a, b) {function equal(a, b) { return a === b; return Primitive_object.compare(a, b) === 0;}} function less(a, b) {function less(a, b) { return a < b; return Primitive_object.compare(a, b) < 0;}} function nanEqual(a, b) {function nanEqual(a, b) { return a === b; return Primitive_float.compare(a, b) === 0;}} function intLess(a, b) {function intLess(a, b) { return a < b; return a < b;}}

modifiedJS compare of int constants

let a = compare(-1, -1) == 0let b = compare(-5, 3) > 0
js
Before
After
let a = false;let a = true; let b = true;let b = false;

Review

  • Which compares still fold? Those of ints, bools, strings and bigints, where the runtime function gives the same answer as the JS operator for well-typed values. Constant variants use the int compare, so they fold as before.
  • Where can the folded and the runtime result still differ? For values JS cannot order: @as(null) against @as(undefined) constructors, or a NaN typed as an int. The runtime compare returns 1 for those and the JS operators return false; this is unchanged.
  • Was the unsigned read of the left constant needed? Not on master: Ext_int.int32_unsigned_to_int had no other caller and is removed, and no checked-in output changes because of it.
  • Which checked-in outputs change? test_list.mjs, whose polymorphic mem, assoc, mem_assoc and remove_assoc now call Primitive_object.compare, and caml_compare_bigint_test.mjs, whose values are typed as floats.