Repository navigation
Description
After #9317 and #9385 I had Claude read through the optimizer passes (Lambda and JS IR, pattern-match compilation, constant folding) looking for more cases where the optimized output disagrees with the unoptimized meaning of the program. Claude did the audit, wrote the reproductions and drafted this issue; I reviewed the results. This is the list of what could be reproduced, ranked by how likely an ordinary program is to hit each one and how silently it fails. I'd like to discuss which of these you consider bugs and in what order they are worth fixing; I'm happy to split out individual issues and send fixes.
Reproductions
Every entry has a failing test on a branch of my fork, one commit per bug:
https://github.com/illusionalsagacity/rescript-compiler/commits/optimizer-failing-tests
- Based on master at 643e9c0. Each commit adds
tests/tests/src/<name>_test.resand its generated.mjs; the commit message names the cause. - Most tests compare a constant expression the compiler can fold with the same expression passed through an
@inline(never)identity function. - Each failing assertion has a
// Actual: X, expected: Ycomment above it. - Together the 31 files give 47 failing assertions.
Each entry says whether the same test also fails on maintenance/12.x. "Not testable" means the test uses syntax or a type that 12.x doesn't have.
Updates
23 November
- Item 1 has fixes up for review: Fold compare against 0 only where JS operators agree #9400 (master) and [12.x] Fold compare against 0 only where JS operators agree #9401 (12.x).
- Item 6 is wider than first reported; see its entry.
- Reviewing the fixes turned up four more bugs, all reproduced on master:
compareof int constants folds to the wrong result when the left one is negative:compare(-1, -1) == 0compiles tofalse. Fixed in Fold compare against 0 only where JS operators agree #9400 and [12.x] Fold compare against 0 only where JS operators agree #9401.- A subtraction from zero whose right operand prints with a leading minus is printed as
--:Float.fromInt(0) -. (Float.fromInt(0) -. a) +. bcompiles to--a + b, which decrementsa, andFloat.fromInt(0) -. -5.0compiles to--5.0, a syntax error. - A self tail call through a cast that changes the argument count crashes the compiler:
let rec f = (a, b) => if a == 0 { b } else { (Obj.magic(f): int => int)(a - 1) }fails withInvalid_argument("List.fold_left2"). - An unused
@getread is removed, so a getter with side effects never runs:let f = el => { let _ = el->offsetHeight }compiles to an empty function. This may be intended, since Merge null and undefined checks only of operands without side effects #9376 treats field reads as free of side effects.
Already tracked
I checked this list against the existing issues (all issue titles, keyword searches of issue and PR text, and the open PRs). Three items are already known:
- Item 7 (
forloop bound) is a duplicate of Aforloop reads its upper bound from a local ref on every iteration #9356, which is open. - Item 19 (unit argument of an external) has a fix in progress in Evaluate @int, @as, unit and @ignore arguments of externals in their place #9231.
- Item 14 (
Float.toIntof a constant) is a duplicate of %intoffloat inconsistency #6739, which was closed as stale without a fix.
I found no existing report for the other 28. Where an older issue is related, the entry links it under "Existing reports".
Tier 1: ordinary code, wrong result or crash
1. compare(a, b) == 0 (also < 0, > 0) is folded to a === b for every type, not only ints
- How you'd hit it: Comparing records, tuples, arrays or options with
compare - Effect: Equal values compare unequal; ordering is wrong. Silent.
- 12.x: also fails
- Test:
compare_fold_test.res - Cause:
js_exp_make.ml:1539(int_comp)
2. A local binding shadows the root of a dotted @val external
- How you'd hit it: A local named
document,location,history,windoworconsolein a file that also uses an external such as"document.title" - Effect:
TypeError, or a call on the wrong object - 12.x: also fails
- Test:
external_shadow_dotted_test.res - Cause:
js_pass_external_shadow.ml:113 - Existing reports: none for locals. Shadowing of js constructors in generated output #3214 and Shadowing of
Imageconstructor #3268 were the same collision between a module name and a global, both closed.
3. A tagged template call whose result is unused is dropped
- How you'd hit it:
tag`...`->ignore,ignore(tag`...`)orlet _ = tag`...` - Effect: The call never happens. Silent.
- 12.x: not testable
- Test:
tagged_template_effect_test.res - Cause:
js_analyzer.ml:150
4. Record rest rewrites later uses of the source record to the destructured locals
- How you'd hit it: Calling a method on, or writing to, a record after
let {a: _, ...rest} = r - Effect: The method loses
this; the write goes to a local copy - 12.x: not applicable (new feature on master)
- Test:
record_rest_source_test.res - Cause:
js_pass_record_rest.ml:32
Tier 2: ordinary code in a narrower shape, silent
5. Int * and ** lose low bits at runtime above 2^53, while the constant fold is exact
- How you'd hit it: Hash functions, random number generators
- Effect: Wrong low bits; folded and runtime results disagree
- 12.x: also fails
- Test:
int_multiplication_fold_test.res - Cause:
js_exp_make.ml:1683,:1703 - Existing reports: none open. The runtime form was introduced by Change
%mulintprimitive behavior #7358.
6. A function or functor body that is copied more than once runs the branch of another copy
- How you'd hit it: An
@inlinefunction with an or-patternswitchor an| exceptioncase, called twice; or a functor whose body has such aswitch, applied twice (no@inlineneeded) - Effect: Wrong branch taken
- 12.x: passes for the shapes I tried (regression on master)
- Update: wider than first reported, which said it needs
@inline. The functor form makes this tier 1. - Test:
inline_static_exit_test.res - Cause:
lam_bounded_vars.ml:96,lam_pass_exits.ml
7. The upper bound of a for loop is read again on every iteration
- How you'd hit it: The body assigns the
refused as the bound - Effect: Extra iterations, possibly endless
- 12.x: also fails
- Test:
for_loop_bound_test.res - Cause:
lam_compile.ml:1417(compile_for) - Existing reports: duplicate of A
forloop reads its upper bound from a local ref on every iteration #9356 (open), which reports the same behaviour for a local ref.
8. Float addition and subtraction of int literals wrap at int32
- How you'd hit it:
Float.fromIntof literals whose sum leaves the int range - Effect: Result off by 2^32
- 12.x: also fails
- Test:
float_add_fold_test.res - Cause:
js_exp_make.ml:1610
9. Record spread copies the base after evaluating the overrides
- How you'd hit it: Spread of a record with an optional field, where an override is a statement-level
try/switchthat touches the base - Effect: A mutation leaks into the copy; evaluation order reversed
- 12.x: passes (master only)
- Test:
record_spread_order_test.res - Cause:
lam_compile.ml:1974 - Existing reports: none for record spread; same evaluation-order family as A block in an argument runs before the arguments to its left, which can produce wrong values #9154.
10. Closures created in a for loop share the loop variable
- How you'd hit it: The loop bound is a statement-level
try/switch - Effect: Every closure sees the final value
- 12.x: also fails
- Test:
for_loop_closure_test.res - Cause:
lam_compile.ml:1457
11. A dense int switch loses its default arm
- How you'd hit it: A match with an unreachable case (already a warning)
- Effect:
undefinedor the wrong arm - 12.x: not testable
- Test:
dense_switch_default_test.res - Cause:
matching.ml:1893(fail_rec)
12. A self tail call evaluates its arguments right to left
- How you'd hit it: Arguments with order-dependent side effects
- Effect: Effects run in reverse
- 12.x: also fails
- Test:
tail_call_argument_order_test.res - Cause:
lam_compile.ml:1787 - Existing reports: none for self tail calls. A block in an argument runs before the arguments to its left, which can produce wrong values #9154, Inlining evaluates arguments in the order the function body uses them, not left to right #9175 and Labelled arguments passed out of order are evaluated in the declared order #9340 treat left-to-right evaluation as the specified order, so this looks in scope.
Tier 3: edge values or unusual code
All of these also fail on 12.x.
13. Float.fromInt(-1) == Float.fromInt(-1) folds to false
- Test:
float_of_negative_int_equality_test.res - Cause:
js_exp_make.ml:1535 - Existing reports: none. Float constants never compare equal in the JS simplifier:
x == 2.5 && x == 2.5compiles tofalse#9099 and Float comparison optimization bug #6674 were other wrong folds of float comparisons, both closed.
14. Float.toInt of an out-of-range constant saturates instead of wrapping, and depends on the build machine
- Test:
float_to_int_fold_test.res - Cause:
lambda.ml:1055 - Existing reports: duplicate of %intoffloat inconsistency #6739, which was closed as stale without a fix; the wider
Float.toIntdiscussion is in Castinginfinityto integer makes value0#6737 and %intoffloat converts Infinity and NaN to 0 #6038.
15. A shift by 32 or more, or by a negative amount, folds to 0; the runtime result differs
- Test:
shift_fold_test.res - Cause:
lambda.ml:1104
16. >>> by a constant 32 or more gives a result outside the int range
- Test:
unsigned_shift_int_test.res - Cause:
js_exp_make.ml:1494 - Existing reports: related to lsr(-123, 0) not equiv. to -123 >>> 0 #7222 (
lsr(-123, 0)folded to-123), closed as stale. Same operator, different constant.
17. @as(3000000000) is wrapped to a negative number, so no case matches
- Test:
as_int_out_of_range_test.res - Cause:
lam_compile_const.ml:49
18. Int remainder can give -0
- Test:
int_remainder_zero_test.res - Cause:
js_exp_make.ml:1654 - Existing reports: none for remainder. ReScript force normalizing
-0to0#6736 (the literal-0printed as0) was merged into Castinginfinityto integer makes value0#6737.
19. A unit argument of an external is evaluated before the arguments to its left
- Test:
external_ignored_argument_order_test.res - Cause:
lam_compile_external_call.ml:203,:228 - Existing reports: fix in progress in Evaluate @int, @as, unit and @ignore arguments of externals in their place #9231 (open PR, follow-up to A polymorphic variant argument of an external is evaluated twice, or inside a generated function #9215 and Evaluate a polymorphic variant argument of an external once, in place #9217), which evaluates
unitand@ignorearguments of externals in place. I have not run this test against that PR.
20. In target().a = { ...; v } the block runs before target()
- Test:
assignment_order_test.res - Cause:
js_pass_flatten.ml:65 - Existing reports: none for assignments; same evaluation-order family as A block in an argument runs before the arguments to its left, which can produce wrong values #9154.
21. isNullable / typeof of an array literal drops the side effects of its elements
- Test:
null_typeof_effect_test.res - Cause:
js_exp_make.ml:1801,:295
22. A mutable field read is stale after a guard mutates it (arguably unspecified, but two shapes of the same match disagree)
- Test:
mutable_field_guard_test.res - Cause:
matching.ml:1612,:2706
23. An unused structural comparison of functions is removed, so the exception is never thrown
- Test:
structural_compare_effect_test.res - Cause:
lam_analysis.ml:64
24. for i in a to x - 1 runs zero times when x - 1 wraps
- Test:
for_loop_wrapped_bound_test.res - Cause:
lam_compile.ml:2143
25. typeof of a bigint literal folds to "number"
- Test:
typeof_bigint_fold_test.res - Cause:
js_exp_make.ml:293
26. -0n == 0n folds to false
- Test:
bigint_zero_equality_test.res - Cause:
js_exp_make.ml:1748
Tier 4: needs an unsafe cast, or only visible from JavaScript
All of these also fail on 12.x.
27. A switch on a constant string ignores merged arms
- Why it ranks low: Only reached through a
%identitystring-to-variant cast; without the cast the constant folds earlier - Test:
constant_string_switch_test.res - Cause:
js_stmt_make.ml:132
28. Truthiness of "", 0.0, 0n and Some(None) is folded as true
- Why it ranks low: Needs a
%identitycast tobool - Test:
truthiness_fold_test.res - Cause:
lambda.ml:1230,js_exp_make.ml:1351
29. if a && b { true } else { false } is reduced to a && b
- Why it ranks low: Same cast
- Test:
boolean_condition_test.res - Cause:
lambda.ml:1218
30. let rec values of a variant type lack TAG
- Why it ranks low: Matching in ReScript still works; only JS interop sees it
- Test:
recursive_value_representation_test.res - Cause:
lam_compile.ml:599
31. Variants with constructors named None/Some ignore @as
- Why it ranks low: Consistent inside ReScript; only wrong for values coming from JS
- Test:
option_shaped_variant_test.res - Cause:
datarepr.ml:194,translcore.ml:1362 - Existing reports: none for
@as. Codegen issue when type isNone | Some('a)#5169 fixed the representation ofNone | Some('a)variants in 9.1; this is what remains of the option special case.
Found but without a test
- An unused dynamic
import()is dropped. Importing a module only to preload it is a real pattern, so I'd put this in tier 2. while true {}is deleted as pure. Tier 3.- The compiler hits an
assert falseon aswitchover a constant string that matches no case. It needs the same cast as item 27, so tier 4.
Open questions
- Item 5 (int multiplication): the runtime form seems to come from Change
%mulintprimitive behavior #7358. If the imprecision above 2^53 is intended, the constant fold should probably match it; otherwise the runtime should useMath.imul. Which is the intended behavior? - Item 11 (dense switch): the only reproduction found has an unreachable case. If one exists without a warning it belongs in tier 1.
- Item 22 (mutable field after a guard): is the read order specified?
- Tier 4: are results behind
%identitycasts in scope at all?
I'd suggest starting with items 1 and 2, since they affect released 12.x and need no unusual code, then item 6 as a recent regression on master that needs no annotation in its functor form.
Activity