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.
modifiedJS 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
modifiedDiagnostic self tail call with a different argument count
let rec f = (a, b) => a == 0 ? b : (Obj.magic(f): int => int)(a - 1)diagnostic
Fatal error: exception Invalid_argument("List.fold_left2")js
function f(a, b) { if (a === 0) { return b; } else { return f(a - 1 | 0); }}
modifiedJS self tail call of a () function
let left = ref(3)@inline(never) let tick = () => left := left.contents - 1let rec drain = () => if left.contents > 0 { drain(tick()) } else { 0 }
js
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
reduceofHashMap,HashSetandMutableSetread 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, asforEachdoes. 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.