From d52e88ff02f04ce91c6234391bdf99fcce222526 Mon Sep 17 00:00:00 2001 From: Christoph Knittel Date: Sun, 1 Nov 2026 06:23:15 +0000 Subject: [PATCH] Evaluate arguments left to right when a later one compiles to statements Why: The statements of an argument were emitted before the whole call or literal, so they ran before the arguments to their left, which could read values the statements had already changed (#9154). JS modified (argument order): Example: let count = ref(0) let pair = (count.contents, { count := count.contents + 1 let id = count.contents `item-${Int.toString(id)}` }) Before (js): pair is [1, "item-1"] count.contents = count.contents + 1 | 0; let id = count.contents; let pair_0 = count.contents; let pair_1 = `item-${id.toString()}`; After (js): pair is [0, "item-1"] let tmp = count.contents; count.contents = count.contents + 1 | 0; let id = count.contents; let pair_1 = `item-${id.toString()}`; JS modified (called fields): Example: let r = o.f({ o.f = x => x + 100 let y = Int.fromString("1")->Option.getOrThrow y * 2 }) Before (js): the new function was called o.f = x => x + 100 | 0; let y = Stdlib_Option.getOrThrow(Stdlib_Int.fromString("1"), undefined); let r = o.f((y << 1)); After (js): the function is read before the arguments let tmp = o.f; o.f = x => x + 100 | 0; let y = Stdlib_Option.getOrThrow(Stdlib_Int.fromString("1"), undefined); let r = tmp((y << 1)); Review: Which arguments get a temporary? Only those to the left of an argument with statements, and only when delaying them could change their value. Constants, functions, immutable variables and literals of such values stay in place. Reads of fields, JS globals and assignable variables are held: the statements, or a closure they call, may change them. A literal keeps its shape and only its elements are held, so translations that read their arguments, such as dict rows and @variadic arrays, still see it. Review: How are assignable variables known? They are the targets of `Lassign` in the final Lambda (`Lambda_traverse.assigned_variables`), collected once per module into `Lam_stats.assignable`, and for a body inlined from another module while generating JS. Review: What about method calls? The callee is held like any argument, except a JS method read (`Pjs_object_get`): there the object is held and the property read stays in the call, so the object is still `this`. Review: Which other constructs change? JS object writes (`obj["k"] = v`) go through the same path, so the target is evaluated before the value's statements. The start of a `for` loop was moved after the statements of its end whenever it had no side effects, which included field reads; it now uses the same check. Review: Does the output change elsewhere? Only where the order was wrong: in the test corpus, one call in bs_array_test.mjs, whose first argument `Belt_Array.reverse(x)` now runs before the copy in the second. A field read such as `init.x` in `{...init, y: {block}}` still gets a temporary, since fields are never delayed. Fixes: #9154 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Kbf3gJs1wimqEvBr89ZYbb Signed-off-by: Christoph Knittel --- changes/argument-evaluation-order.fix.md | 1 + compiler/core/lam_compile.ml | 236 ++++++++++---- compiler/core/lam_compile_main.ml | 11 + compiler/core/lam_stats.ml | 4 + compiler/core/lam_stats.mli | 3 + compiler/ml/lambda_traverse.ml | 11 + compiler/ml/lambda_traverse.mli | 3 + tests/belt_tests/src/bs_array_test.mjs | 3 +- .../src/argument_evaluation_order_test.mjs | 307 ++++++++++++++++++ .../src/argument_evaluation_order_test.res | 275 ++++++++++++++++ 10 files changed, 790 insertions(+), 64 deletions(-) create mode 100644 changes/argument-evaluation-order.fix.md create mode 100644 tests/tests/src/argument_evaluation_order_test.mjs create mode 100644 tests/tests/src/argument_evaluation_order_test.res diff --git a/changes/argument-evaluation-order.fix.md b/changes/argument-evaluation-order.fix.md new file mode 100644 index 00000000000..2a78c4c1e6b --- /dev/null +++ b/changes/argument-evaluation-order.fix.md @@ -0,0 +1 @@ +- Evaluate arguments and literal elements left to right when a later one is a block that compiles to statements, which could produce wrong values. diff --git a/compiler/core/lam_compile.ml b/compiler/core/lam_compile.ml index bbd250c361f..90c4fa17607 100644 --- a/compiler/core/lam_compile.ml +++ b/compiler/core/lam_compile.ml @@ -238,6 +238,135 @@ let functions_before_values (group : (Ident.t * Lambda.t) list) = | _, _ -> 0) group +(* Whether evaluating [e] later, after other code, gives the same value and + the same effects as evaluating it now: constants, functions, immutable + local variables and pure operations on them. [assignable] are the local + variables some [Lassign] assigns; the other code, or a closure it calls, + may assign them. JS globals ([@val]) and reads of the heap (fields, array + elements, lengths) may change as well. *) +let rec delay_safe ~assignable (e : J.expression) = + match e.expression_desc with + | Undefined _ | Null | Bool _ | Number _ | Str _ | Template_literal _ + | Json_literal _ | Fun _ + | Var (Qualified _) -> + true + | Var (Id id) -> + (not (Ext_ident.is_js id)) && not (Set_ident.mem id assignable) + | Bin (Eq, _, _) -> false + | Bin (_, a, b) -> + Js_analyzer.no_side_effect_expression e + && delay_safe ~assignable a && delay_safe ~assignable b + | String_append (a, b) -> delay_safe ~assignable a && delay_safe ~assignable b + | Js_not a + | Js_bnot a + | Typeof a + | Is_null_or_undefined a + | Optional_block (a, _) -> + delay_safe ~assignable a + | Cond (a, b, c) -> + delay_safe ~assignable a && delay_safe ~assignable b + && delay_safe ~assignable c + | Interpolated_template {values} -> + Ext_list.for_all values (delay_safe ~assignable) + | Array xs | Caml_block (xs, _, _) -> + Ext_list.for_all xs (delay_safe ~assignable) + | Object entries -> + Ext_list.for_all entries (function + | J.Object_property (_, v) -> delay_safe ~assignable v + | Record_spread _ | Object_spread _ -> false) + | _ -> false + +(* Statements that evaluate [e] now, and the expression that stands for its + value afterwards. A sequence's leading expressions become statements of + their own, and the last one gets a temporary unless it is [delay_safe]. + Building an array, block or object literal is pure, so a literal stays in + place and its elements are evaluated now instead. That also keeps the + literal visible to translations that look into their arguments, such as + the rows of a dict literal or a [@variadic] array. *) +let rec evaluate_now ~assignable (e : J.expression) : J.block * J.expression = + match e.expression_desc with + | _ when delay_safe ~assignable e -> ([], e) + | Seq (a, b) -> + let rest, b = evaluate_now ~assignable b in + if Js_analyzer.no_side_effect_expression a then (rest, b) + else + ({J.statement_desc = Exp a; comment = None; source_loc = None} :: rest, b) + | Array xs -> + let held, xs = evaluate_all_now ~assignable xs in + (held, {e with expression_desc = Array xs}) + | Caml_block (xs, mutable_flag, tag) -> + let held, xs = evaluate_all_now ~assignable xs in + (held, {e with expression_desc = Caml_block (xs, mutable_flag, tag)}) + | Object entries + when Ext_list.for_all entries (function + | J.Object_property _ -> true + | Record_spread _ | Object_spread _ -> false) -> + let held, values = + evaluate_all_now ~assignable + (Ext_list.filter_map entries (function + | J.Object_property (_, v) -> Some v + | Record_spread _ | Object_spread _ -> None)) + in + let entries = + List.map2 + (fun entry v -> + match entry with + | J.Object_property (k, _) -> J.Object_property (k, v) + | Record_spread _ | Object_spread _ -> assert false) + entries values + in + (held, {e with expression_desc = Object entries}) + | _ -> + let tmp = Ext_ident.create_tmp () in + ([S.define_variable ~kind:Strict tmp e], E.var tmp) + +(* [evaluate_now] on each of [xs], left to right. The elements left in place + are [delay_safe], so no other element's statements can change them. *) +and evaluate_all_now ~assignable (xs : J.expression list) : + J.block * J.expression list = + let blocks, xs = Ext_list.split_map xs (evaluate_now ~assignable) in + (List.concat blocks, xs) + +(* Assembles compiled arguments for a call or a literal that evaluates them + left to right. Each argument comes with the statements that have to run + before its value is read. Putting all statements first and then the + values would move the statements of an argument in front of the values of + the arguments to its left, so when an argument has statements, every + argument to its left is evaluated before them with [evaluate_now]. + + With [~method_callee:true], the first argument is a JS method read + [obj.m] being called: the object is held and the property read stays in + the call, so the call still passes the object as [this]. *) +let sequence_arguments ?(method_callee = false) ~assignable + (args : (J.block * J.expression) list) : J.block * J.expression list = + let later_statements = + match args with + | [] -> false + | _ :: rest -> Ext_list.exists_fst rest (fun block -> block <> []) + in + if not later_statements then (List.concat_map fst args, Ext_list.map args snd) + else + let last = List.length args - 1 in + let _, code, values = + Ext_list.fold_right args (last, [], []) + (fun (block, value) (i, code, values) -> + let held, value = + if code = [] then ([], value) + else + match value.expression_desc with + | Static_index (obj, name, pos) when method_callee && i = 0 -> + let held, obj = evaluate_now ~assignable obj in + ( held, + {value with expression_desc = Static_index (obj, name, pos)} + ) + | _ -> evaluate_now ~assignable value + in + ( i - 1, + Ext_list.append block (Ext_list.append held code), + value :: values )) + in + (code, values) + let compile output_prefix = (* When compiling a read from another module, a nested source path like Other.A.B.make reaches this point as nested module-field reads: @@ -320,21 +449,23 @@ let compile output_prefix = let _, param_map = Lam_closure.is_closed_with_map Set_ident.empty params body in - compile_lambda lambda_cxt - (Lam_beta_reduce.propagate_beta_reduce_with_map lambda_cxt.meta - param_map params body ap_args) - | _ -> - let args_code, args = - let dummy = ([], []) in - if ap_args = [] then dummy - else - let arg_cxt = {lambda_cxt with continuation = NeedValue Not_tail} in - Ext_list.fold_right ap_args dummy (fun arg_lambda (args_code, args) -> - match compile_lambda arg_cxt arg_lambda with - | {block; value = Some b} -> - (Ext_list.append block args_code, b :: args) - | _ -> assert false) + let inlined = + Lam_beta_reduce.propagate_beta_reduce_with_map lambda_cxt.meta param_map + params body ap_args in + (* The inlined body comes from another module, so the variables it + assigns are not in [meta.assignable] yet. *) + let meta = + { + lambda_cxt.meta with + assignable = + Set_ident.union lambda_cxt.meta.assignable + (Lambda_traverse.assigned_variables inlined); + } + in + compile_lambda {lambda_cxt with meta} inlined + | _ -> + let args_code, args = compile_arguments lambda_cxt ap_args in let fn = E.ml_var_dot module_id ident_info.name in let expression = @@ -1256,7 +1387,7 @@ let compile output_prefix = match (b1, b2) with | _, [] -> Ext_list.append_one b1 (make_for (Some e1)) | _, _ - when Js_analyzer.no_side_effect_expression e1 + when delay_safe ~assignable:lambda_cxt.meta.assignable e1 (* e1 > b2 > e2 re-order @@ -1563,15 +1694,15 @@ let compile output_prefix = 2. no need create names *) let ap_func = appinfo.ap_func in - let new_cxt = {lambda_cxt with continuation = NeedValue Not_tail} in let args_code, fn_code, args = match - Ext_list.fold_right (ap_func :: appinfo.ap_args) ([], []) - (fun x (args_code, fn_code) -> - match compile_lambda new_cxt x with - | {block; value = Some b} -> - (Ext_list.append block args_code, b :: fn_code) - | {value = None} -> assert false) + compile_arguments + ~method_callee: + (match ap_func with + | Lprim {primitive = Pjs_object_get _} -> true + | _ -> false) + lambda_cxt + (ap_func :: appinfo.ap_args) with | args_code, fn_code :: args -> (args_code, fn_code, args) | _, [] -> assert false @@ -1631,19 +1762,22 @@ let compile output_prefix = (E.call ~info:(call_info_of_apply lambda_cxt.meta appinfo) fn_code args))) + (* Compiles the arguments of a call or a literal, which are evaluated left to + right; see [sequence_arguments]. *) + and compile_arguments ?method_callee (lambda_cxt : Lam_compile_context.t) + (args : Lambda.t list) : J.block * J.expression list = + if args = [] then ([], []) + else + let arg_cxt = {lambda_cxt with continuation = NeedValue Not_tail} in + sequence_arguments ?method_callee ~assignable:lambda_cxt.meta.assignable + (Ext_list.map args (fun arg -> + match compile_lambda arg_cxt arg with + | {block; value = Some value} -> (block, value) + | {value = None} -> assert false)) and compile_prim (prim_info : Lambda.prim_info) (lambda_cxt : Lam_compile_context.t) = let compile_primitive_default primitive args loc = - let args_block, args_expr = - if args = [] then ([], []) - else - let new_cxt = {lambda_cxt with continuation = NeedValue Not_tail} in - Ext_list.split_map args (fun x -> - match compile_lambda new_cxt x with - | {block; value = Some b} -> (block, b) - | {value = None} -> assert false) - in - let args_code : J.block = List.concat args_block in + let args_code, args_expr = compile_arguments lambda_cxt args in let exp = (* TODO: all can be done in [Lam_compile_primitive.translate] *) Lam_compile_primitive.translate output_prefix loc lambda_cxt primitive @@ -1717,28 +1851,12 @@ let compile output_prefix = ret) | {primitive = Pjs_object_set property; args = [obj; setter_val]} -> ( (* property write: obj["height"] = v *) - let need_value_no_return_cxt = - {lambda_cxt with continuation = NeedValue Not_tail} - in - let obj_output = compile_lambda need_value_no_return_cxt obj in - let arg_output = compile_lambda need_value_no_return_cxt setter_val in - let cont obj_block arg_block obj_code = + match compile_arguments lambda_cxt [obj; setter_val] with + | args_code, [obj; value] -> Js_output.output_of_block_and_expression lambda_cxt.continuation - (match obj_code with - | None -> Ext_list.append obj_block arg_block - | Some obj_code -> Ext_list.append obj_block (obj_code :: arg_block)) - in - match (obj_output, arg_output) with - | {value = None}, _ | _, {value = None} -> assert false - | ( {block = obj_block; value = Some obj}, - {block = arg_block; value = Some value} ) -> ( - match Js_ast_util.named_expression obj with - | None -> - cont obj_block arg_block None - (E.seq (E.assign (E.dot obj property) value) E.unit) - | Some (obj_code, obj) -> - cont obj_block arg_block (Some obj_code) - (E.seq (E.assign (E.dot (E.var obj) property) value) E.unit))) + args_code + (E.seq (E.assign (E.dot obj property) value) E.unit) + | _ -> assert false) | {primitive = Pjs_object_get _ | Pjs_object_set _} -> assert false | {primitive = Pjs_fn_method; args = args_lambda} -> ( match args_lambda with @@ -1763,20 +1881,12 @@ let compile output_prefix = body)))) | _ -> assert false) | {primitive = Pjs_object_create labels; args} -> - let args_block, args_expr = - if args = [] then ([], []) - else - let new_cxt = {lambda_cxt with continuation = NeedValue Not_tail} in - Ext_list.split_map args (fun x -> - match compile_lambda new_cxt x with - | {block; value = Some b} -> (block, b) - | {value = None} -> assert false) - in + let args_code, args_expr = compile_arguments lambda_cxt args in let block, exp = Lam_compile_external_obj.assemble_obj_args labels args_expr in Js_output.output_of_block_and_expression lambda_cxt.continuation - (Ext_list.concat_append args_block block) + (Ext_list.append args_code block) exp | {primitive; args; loc} -> compile_primitive_default primitive args loc and collect_dup_overrides (copy_id : Ident.t) (lam : Lambda.t) diff --git a/compiler/core/lam_compile_main.ml b/compiler/core/lam_compile_main.ml index 163760de040..1105a01aede 100644 --- a/compiler/core/lam_compile_main.ml +++ b/compiler/core/lam_compile_main.ml @@ -215,6 +215,14 @@ let is_awaited_unit (lam : Lambda.t) = true | _ -> false +(* See [Lam_stats.assignable]. *) +let assigned_variables (group : Lam_group.t) = + match group with + | Single (_, _, lam) | Nop lam -> Lambda_traverse.assigned_variables lam + | Recursive bindings -> + Ext_list.fold_left bindings Set_ident.empty (fun acc (_, lam) -> + Set_ident.union acc (Lambda_traverse.assigned_variables lam)) + (* See [Lam_stats.awaited_units]. *) let awaited_units (groups : Lam_group.t list) = let units = ref Set_ident.empty in @@ -360,6 +368,9 @@ let compile ?on_optimized_lambda (output_prefix : string) { meta with awaited_units = awaited_units groups; + assignable = + Ext_list.fold_left groups Set_ident.empty (fun acc group -> + Set_ident.union acc (assigned_variables group)); exports = meta.exports @ flat_exports; export_idents = Ext_list.fold_left flat_exports meta.export_idents (fun acc id -> diff --git a/compiler/core/lam_stats.ml b/compiler/core/lam_stats.ml index 1ba85128671..bb1c77916db 100644 --- a/compiler/core/lam_stats.ml +++ b/compiler/core/lam_stats.ml @@ -47,6 +47,9 @@ type t = { for sure it's not a function, there is no need to count them *) awaited_units: Set_ident.t; + assignable: Set_ident.t; + (** The variables some [Lassign] assigns. [Lam_compile] never delays + reading one of them past other code. *) } let pp = Format.fprintf @@ -68,4 +71,5 @@ let make ~export_idents ~export_ident_sets : t = exports = export_idents; export_idents = export_ident_sets; awaited_units = Set_ident.empty; + assignable = Set_ident.empty; } diff --git a/compiler/core/lam_stats.mli b/compiler/core/lam_stats.mli index a05ab0b292c..a7f53fe32f4 100644 --- a/compiler/core/lam_stats.mli +++ b/compiler/core/lam_stats.mli @@ -40,6 +40,9 @@ type t = { (** Locals bound to an awaited compilation unit, [let d = await import(Unit)]: reads of nested [make] values through them use the flat exports too. *) + assignable: Set_ident.t; + (** The variables some [Lassign] assigns. [Lam_compile] never delays + reading one of them past other code. *) } val print : Format.formatter -> t -> unit diff --git a/compiler/ml/lambda_traverse.ml b/compiler/ml/lambda_traverse.ml index 560501d4359..027eb9dd88a 100644 --- a/compiler/ml/lambda_traverse.ml +++ b/compiler/ml/lambda_traverse.ml @@ -243,6 +243,17 @@ let free_variables l = | _ -> []) l +let assigned_variables l = + let assigned = ref Set_ident.empty in + let rec walk l = + (match l with + | Lassign (id, _) -> assigned := Set_ident.add id !assigned + | _ -> ()); + iter walk l + in + walk l; + !assigned + (* Substitution rebuilds through [shallow_map_sharing], so the result is normalized and an untouched subterm is returned physically unchanged. *) let subst_lambda s lam = diff --git a/compiler/ml/lambda_traverse.mli b/compiler/ml/lambda_traverse.mli index 3e5d0267f34..9c342c2daad 100644 --- a/compiler/ml/lambda_traverse.mli +++ b/compiler/ml/lambda_traverse.mli @@ -28,6 +28,9 @@ val iter : (Lambda.t -> unit) -> Lambda.t -> unit val free_variables : Lambda.t -> Set_ident.t +val assigned_variables : Lambda.t -> Set_ident.t +(** The variables some [Lassign] in the term assigns. *) + val subst_lambda : Lambda.t Ident.tbl -> Lambda.t -> Lambda.t (** Substitute for the free variables in the domain of the substitution. Assumes the substitution's image is out of reach of the term's bound diff --git a/tests/belt_tests/src/bs_array_test.mjs b/tests/belt_tests/src/bs_array_test.mjs index 9d92dd0e4c1..0bd723dc884 100644 --- a/tests/belt_tests/src/bs_array_test.mjs +++ b/tests/belt_tests/src/bs_array_test.mjs @@ -847,8 +847,9 @@ Mocha.describe("Bs_array_test", () => { }), c === 6)); }); let id = (loc, x) => { + let tmp = Belt_Array.reverse(x); let u = x.slice(0); - Test_utils.eq("File \"bs_array_test.res\", line 298, characters 6-13", Belt_Array.reverse(x), (Belt_Array.reverseInPlace(u), u)); + Test_utils.eq("File \"bs_array_test.res\", line 298, characters 6-13", tmp, (Belt_Array.reverseInPlace(u), u)); }; Mocha.test("bs_array_test_id_functions", () => { id("File \"bs_array_test.res\", line 308, characters 7-14", []); diff --git a/tests/tests/src/argument_evaluation_order_test.mjs b/tests/tests/src/argument_evaluation_order_test.mjs new file mode 100644 index 00000000000..6c16fa348ee --- /dev/null +++ b/tests/tests/src/argument_evaluation_order_test.mjs @@ -0,0 +1,307 @@ +// Generated by ReScript, PLEASE EDIT WITH CARE + +import * as Mocha from "mocha"; +import * as Stdlib_Int from "@rescript/runtime/lib/es6/Stdlib_Int.mjs"; +import * as Test_utils from "./test_utils.mjs"; +import * as Stdlib_Option from "@rescript/runtime/lib/es6/Stdlib_Option.mjs"; + +globalThis.orderCounter = 0 +globalThis.bumpOrderCounter = () => { globalThis.orderCounter++ } +globalThis.makeCounter = () => ({ v: 7, get(x) { return this.v + x } }) +; + +let resetOrderCounter = (() => { globalThis.orderCounter = 0 }); + +let makeBox = (x => ({x})); + +let makeOps = (() => ({f: x => x + 1})); + +let count = { + contents: 0 +}; + +let tmp = count.contents; + +count.contents = count.contents + 1 | 0; + +let c = count.contents; + +let topLevel_1 = c * 10 | 0; + +let topLevel = [ + tmp, + topLevel_1 +]; + +Mocha.describe("Argument_evaluation_order_test", () => { + Mocha.test("a read before a block that writes it, at the top level", () => Test_utils.eq("File \"argument_evaluation_order_test.res\", line 47, characters 7-14", [ + 0, + 10 + ], topLevel)); + Mocha.test("a local ref that becomes a JS variable", () => { + let n = 0; + let tmp = n; + n = n + 1 | 0; + let m = n; + let pair_1 = m * 10 | 0; + let pair = [ + tmp, + pair_1 + ]; + Test_utils.eq("File \"argument_evaluation_order_test.res\", line 60, characters 7-14", [ + 0, + 10 + ], pair); + }); + Mocha.test("a local ref that a closure called in the block assigns", () => { + let n = 0; + let bump = () => { + n = n + 1 | 0; + }; + let tmp = n; + bump(); + let m = n; + let pair_1 = m * 10 | 0; + let pair = [ + tmp, + pair_1 + ]; + Test_utils.eq("File \"argument_evaluation_order_test.res\", line 74, characters 7-14", [ + 0, + 10 + ], pair); + }); + Mocha.test("effects in arrays, tuples, records, dicts and objects", () => { + let log = []; + let mark = (s, v) => { + log.push(s); + return v; + }; + let tmp = mark("first", 1); + let v = mark("second", 2); + let arr = [ + tmp, + v * v | 0 + ]; + let tmp$1 = mark("first", 1); + let v$1 = mark("second", 3); + let tup_1 = v$1 * v$1 | 0; + let tup = [ + tmp$1, + tup_1 + ]; + let tmp$2 = mark("first", 1); + let v$2 = mark("second", 4); + let rec__b = v$2 * v$2 | 0; + let rec_ = { + a: tmp$2, + b: rec__b + }; + let tmp$3 = mark("first", 1); + let v$3 = mark("second", 5); + let d = { + a: tmp$3, + b: v$3 * v$3 | 0 + }; + let tmp$4 = mark("first", 1); + let v$4 = mark("second", 6); + let o = { + a: tmp$4, + b: v$4 * v$4 | 0 + }; + Test_utils.eq("File \"argument_evaluation_order_test.res\", line 119, characters 6-13", [ + "first", + "second", + "first", + "second", + "first", + "second", + "first", + "second", + "first", + "second" + ], log); + Test_utils.eq("File \"argument_evaluation_order_test.res\", line 134, characters 7-14", [ + 1, + 4 + ], arr); + Test_utils.eq("File \"argument_evaluation_order_test.res\", line 135, characters 7-14", [ + 1, + 9 + ], tup); + Test_utils.eq("File \"argument_evaluation_order_test.res\", line 136, characters 7-14", { + a: 1, + b: 16 + }, rec_); + Test_utils.eq("File \"argument_evaluation_order_test.res\", line 137, characters 7-14", { + a: 1, + b: 25 + }, d); + Test_utils.eq("File \"argument_evaluation_order_test.res\", line 138, characters 7-14", [ + 1, + 36 + ], [ + o.a, + o.b + ]); + }); + Mocha.test("calls of externals and of ReScript functions", () => { + let log = []; + let mark = (s, v) => { + log.push(s); + return v; + }; + let tmp = mark("x", 1); + let v = mark("y", 2); + let viaExternal = Array.of(tmp, v * v | 0); + let tmp$1 = mark("x", 1); + let v$1 = mark("y", 2); + let viaFunction = tmp$1 + (v$1 * v$1 | 0) | 0; + Test_utils.eq("File \"argument_evaluation_order_test.res\", line 162, characters 7-14", [ + "x", + "y", + "x", + "y" + ], log); + Test_utils.eq("File \"argument_evaluation_order_test.res\", line 163, characters 7-14", [ + 1, + 4 + ], viaExternal); + Test_utils.eq("File \"argument_evaluation_order_test.res\", line 164, characters 7-14", 5, viaFunction); + }); + Mocha.test("a switch and a try as arguments", () => { + let log = []; + let mark = (s, v) => { + log.push(s); + return v; + }; + let tmp = mark("before", 0); + let match = mark("scrutinee", 1); + let viaSwitch = [ + tmp, + match !== 0 ? ( + match !== 1 ? mark("other", 12) : mark("one", 11) + ) : mark("zero", 10) + ]; + let tmp$1 = mark("before", 0); + let tmp$2; + try { + tmp$2 = mark("body", 1); + } catch (exn) { + tmp$2 = 2; + } + let viaTry = [ + tmp$1, + tmp$2 + ]; + Test_utils.eq("File \"argument_evaluation_order_test.res\", line 187, characters 7-14", [ + "before", + "scrutinee", + "one", + "before", + "body" + ], log); + Test_utils.eq("File \"argument_evaluation_order_test.res\", line 188, characters 7-14", [ + 0, + 11 + ], viaSwitch); + Test_utils.eq("File \"argument_evaluation_order_test.res\", line 189, characters 7-14", [ + 0, + 1 + ], viaTry); + }); + Mocha.test("the start of a for loop before a block in its end", () => { + let r = 0; + let visited = []; + let i = r; + r = 2; + let e = r; + for (let i_finish = (e - 1 | 0); i <= i_finish; ++i) { + visited.push(i); + } + Test_utils.eq("File \"argument_evaluation_order_test.res\", line 202, characters 7-14", [ + 0, + 1 + ], visited); + }); + Mocha.test("a JS global read before a block that changes it", () => { + resetOrderCounter(); + let tmp = orderCounter; + bumpOrderCounter(); + let m = orderCounter; + let pair_1 = m * 10 | 0; + let pair = [ + tmp, + pair_1 + ]; + Test_utils.eq("File \"argument_evaluation_order_test.res\", line 215, characters 7-14", [ + 0, + 10 + ], pair); + }); + Mocha.test("the target of a JS object write before a block in the value", () => { + let log = []; + let mark = (s, v) => { + log.push(s); + return v; + }; + let o = makeBox(0); + let first = o; + let tmp = o; + o = makeBox(100); + let v = mark("v", 5); + tmp.x = v * v | 0; + Test_utils.eq("File \"argument_evaluation_order_test.res\", line 232, characters 7-14", [ + 25, + 100 + ], [ + first.x, + o.x + ]); + }); + Mocha.test("a function read from a record field before the arguments", () => { + let o = makeOps(); + let tmp = o.f; + o.f = x => x + 100 | 0; + let y = Stdlib_Option.getOrThrow(Stdlib_Int.fromString("1"), undefined); + let r = tmp((y << 1)); + Test_utils.eq("File \"argument_evaluation_order_test.res\", line 242, characters 7-14", 3, r); + }); + Mocha.test("a function read from a ref before the arguments", () => { + let fr = x => x + 1 | 0; + let tmp = fr; + fr = x => x + 100 | 0; + let y = Stdlib_Option.getOrThrow(Stdlib_Int.fromString("1"), undefined); + let r = tmp((y << 1)); + Test_utils.eq("File \"argument_evaluation_order_test.res\", line 252, characters 7-14", 3, r); + }); + Mocha.test("a held receiver is still passed as this", () => { + let log = []; + let tmp = makeCounter(); + log.push("arg"); + let y = log.length; + let r = tmp.get((y << 1)); + Test_utils.eq("File \"argument_evaluation_order_test.res\", line 262, characters 7-14", 9, r); + }); + Mocha.test("a method keeps a receiver that stays in place", () => { + let arr = [1]; + arr.push(2); + let l = arr.length; + let length = arr.push(l * 100 | 0); + Test_utils.eq("File \"argument_evaluation_order_test.res\", line 272, characters 7-14", 3, length); + Test_utils.eq("File \"argument_evaluation_order_test.res\", line 273, characters 7-14", [ + 1, + 2, + 200 + ], arr); + }); +}); + +export { + resetOrderCounter, + makeBox, + makeOps, + count, + topLevel, +} +/* Not a pure module */ diff --git a/tests/tests/src/argument_evaluation_order_test.res b/tests/tests/src/argument_evaluation_order_test.res new file mode 100644 index 00000000000..41b3e02622b --- /dev/null +++ b/tests/tests/src/argument_evaluation_order_test.res @@ -0,0 +1,275 @@ +open Mocha +open Test_utils + +// Arguments and literal elements are evaluated left to right, also when a later +// one is a block that compiles to statements. + +type pair = {a: int, b: int} +type ops = {mutable f: int => int} + +@val external makeObject: (int, int) => array = "Array.of" +@obj external makeJsObject: (~a: int, ~b: int) => {"a": int, "b": int} = "" +@send external pushTo: (array, int) => int = "push" + +%%raw(` +globalThis.orderCounter = 0 +globalThis.bumpOrderCounter = () => { globalThis.orderCounter++ } +globalThis.makeCounter = () => ({ v: 7, get(x) { return this.v + x } }) +`) + +@val external orderCounter: int = "orderCounter" +@val external bumpOrderCounter: unit => unit = "bumpOrderCounter" +let resetOrderCounter: unit => unit = %raw(`() => { globalThis.orderCounter = 0 }`) + +type counter +@val external makeCounter: unit => counter = "makeCounter" +@send external counterGet: (counter, int) => int = "get" + +type box = {@set "x": int} +let makeBox: int => box = %raw(`x => ({x})`) + +// Opaque, so that the record stays a record instead of becoming a variable. +let makeOps: unit => ops = %raw(`() => ({f: x => x + 1})`) + +let count = ref(0) + +let topLevel = ( + count.contents, + { + count := count.contents + 1 + let c = count.contents + c * 10 + }, +) + +describe(__MODULE__, () => { + test("a read before a block that writes it, at the top level", () => { + eq(__LOC__, (0, 10), topLevel) + }) + + test("a local ref that becomes a JS variable", () => { + let n = ref(0) + let pair = ( + n.contents, + { + n := n.contents + 1 + let m = n.contents + m * 10 + }, + ) + eq(__LOC__, (0, 10), pair) + }) + + test("a local ref that a closure called in the block assigns", () => { + let n = ref(0) + let bump = () => n := n.contents + 1 + let pair = ( + n.contents, + { + bump() + let m = n.contents + m * 10 + }, + ) + eq(__LOC__, (0, 10), pair) + }) + + test("effects in arrays, tuples, records, dicts and objects", () => { + let log = [] + let mark = (s, v) => { + log->Array.push(s) + v + } + let arr = [ + mark("first", 1), + { + let v = mark("second", 2) + v * v + }, + ] + let tup = ( + mark("first", 1), + { + let v = mark("second", 3) + v * v + }, + ) + let rec_ = { + a: mark("first", 1), + b: { + let v = mark("second", 4) + v * v + }, + } + let d = dict{ + "a": mark("first", 1), + "b": { + let v = mark("second", 5) + v * v + }, + } + let o = makeJsObject( + ~a=mark("first", 1), + ~b={ + let v = mark("second", 6) + v * v + }, + ) + eq( + __LOC__, + [ + "first", + "second", + "first", + "second", + "first", + "second", + "first", + "second", + "first", + "second", + ], + log, + ) + eq(__LOC__, [1, 4], arr) + eq(__LOC__, (1, 9), tup) + eq(__LOC__, {a: 1, b: 16}, rec_) + eq(__LOC__, dict{"a": 1, "b": 25}, d) + eq(__LOC__, (1, 36), (o["a"], o["b"])) + }) + + test("calls of externals and of ReScript functions", () => { + let log = [] + let mark = (s, v) => { + log->Array.push(s) + v + } + let add = (x, y) => x + y + let viaExternal = makeObject( + mark("x", 1), + { + let v = mark("y", 2) + v * v + }, + ) + let viaFunction = add( + mark("x", 1), + { + let v = mark("y", 2) + v * v + }, + ) + eq(__LOC__, ["x", "y", "x", "y"], log) + eq(__LOC__, [1, 4], viaExternal) + eq(__LOC__, 5, viaFunction) + }) + + test("a switch and a try as arguments", () => { + let log = [] + let mark = (s, v) => { + log->Array.push(s) + v + } + let viaSwitch = [ + mark("before", 0), + switch mark("scrutinee", 1) { + | 0 => mark("zero", 10) + | 1 => mark("one", 11) + | _ => mark("other", 12) + }, + ] + let viaTry = [ + mark("before", 0), + try mark("body", 1) catch { + | _ => 2 + }, + ] + eq(__LOC__, ["before", "scrutinee", "one", "before", "body"], log) + eq(__LOC__, [0, 11], viaSwitch) + eq(__LOC__, [0, 1], viaTry) + }) + + test("the start of a for loop before a block in its end", () => { + let r = ref(0) + let visited = [] + for i in r.contents to { + r := 2 + let e = r.contents + e - 1 + } { + visited->Array.push(i) + } + eq(__LOC__, [0, 1], visited) + }) + + test("a JS global read before a block that changes it", () => { + resetOrderCounter() + let pair = ( + orderCounter, + { + bumpOrderCounter() + let m = orderCounter + m * 10 + }, + ) + eq(__LOC__, (0, 10), pair) + }) + + test("the target of a JS object write before a block in the value", () => { + let log = [] + let mark = (s, v) => { + log->Array.push(s) + v + } + let o = ref(makeBox(0)) + let first = o.contents + o.contents["x"] = { + o := makeBox(100) + let v = mark("v", 5) + v * v + } + + eq(__LOC__, (25, 100), (first["x"], o.contents["x"])) + }) + + test("a function read from a record field before the arguments", () => { + let o = makeOps() + let r = o.f({ + o.f = x => x + 100 + let y = Int.fromString("1")->Option.getOrThrow + y * 2 + }) + eq(__LOC__, 3, r) + }) + + test("a function read from a ref before the arguments", () => { + let fr = ref(x => x + 1) + let r = fr.contents({ + fr := x => x + 100 + let y = Int.fromString("1")->Option.getOrThrow + y * 2 + }) + eq(__LOC__, 3, r) + }) + + test("a held receiver is still passed as this", () => { + let log = [] + let r = makeCounter()->counterGet({ + log->Array.push("arg") + let y = log->Array.length + y * 2 + }) + eq(__LOC__, 9, r) + }) + + test("a method keeps a receiver that stays in place", () => { + let arr = [1] + let length = arr->pushTo({ + arr->Array.push(2) + let l = arr->Array.length + l * 100 + }) + eq(__LOC__, 3, length) + eq(__LOC__, [1, 2, 200], arr) + }) +})