diff --git a/changes/argument-evaluation-order.fix.md b/changes/argument-evaluation-order.fix.md new file mode 100644 index 0000000000..2a78c4c1e6 --- /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 bbd250c361..90c4fa1760 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 163760de04..1105a01aed 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 1ba8512867..bb1c77916d 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 a05ab0b292..a7f53fe32f 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 560501d435..027eb9dd88 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 3e5d0267f3..9c342c2daa 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 9d92dd0e4c..0bd723dc88 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 0000000000..6c16fa348e --- /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 0000000000..41b3e02622 --- /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) + }) +})