diff --git a/changes/let-rec-record-after-effects.fix.md b/changes/let-rec-record-after-effects.fix.md new file mode 100644 index 0000000000..31839d3734 --- /dev/null +++ b/changes/let-rec-record-after-effects.fix.md @@ -0,0 +1 @@ +- Fix a `let rec` record that refers to itself and is built after other expressions, as in `let rec r = {...f(), next: r}` or `let rec r = {log(); {next: r}}`, reading itself before it is initialized, and a record of a `let rec` group being read by a record built before it, as `a` in `let rec b = {next: a, v: 1} and a = {f: () => b, w: 2}`, before it is declared (#9466). diff --git a/changes/rec-record-spread-source-check.breaking.md b/changes/rec-record-spread-source-check.breaking.md new file mode 100644 index 0000000000..6bf008dc90 --- /dev/null +++ b/changes/rec-record-spread-source-check.breaking.md @@ -0,0 +1 @@ +- The source of a record spread whose fields are all overridden is now checked in a `let rec` like any other expression, since it is evaluated. `let rec callback = {...wrap(callback), run: () => 1}`, which compiled with warning 23 and never called `wrap`, is now an error: remove the spread, or build the source without reading the binding. diff --git a/changes/record-spread-source-effect.fix.md b/changes/record-spread-source-effect.fix.md new file mode 100644 index 0000000000..b31a614e09 --- /dev/null +++ b/changes/record-spread-source-effect.fix.md @@ -0,0 +1 @@ +- Fix the source of a record spread (or JSX props spread) not being evaluated when every field is overridden, as in `{...f(), a: 1, b: 2}`. Warning 23 on such a spread now says that its source is still evaluated, instead of suggesting to remove the spread, unless the source is a variable. diff --git a/compiler/backend/lam_compile.ml b/compiler/backend/lam_compile.ml index 6fe20f7a1d..1398f49b69 100644 --- a/compiler/backend/lam_compile.ml +++ b/compiler/backend/lam_compile.ml @@ -84,6 +84,130 @@ let with_block_source_loc lam block = | stmt :: rest -> with_statement_source_loc (source_map_loc_of_lam lam) stmt :: rest +let rec const_block_tag (c : Lambda.structured_constant) = + match c with + | Const_block (tag_info, _) -> Some tag_info + | Const_some inner -> const_block_tag inner + | _ -> None + +let rec is_dups_alias dups (lam : Lambda.t) = + match lam with + | Lvar src -> Set_ident.mem src dups + | Lprim {primitive = Psome | Psome_not_nest; args = [inner]} -> + is_dups_alias dups inner + | _ -> false + +(* The tag of the block that [lam] builds at the end of a chain of sequences, + lets, recursive lets and [Psome] / [Psome_not_nest] option wrappers, with + the expressions evaluated to build it: those before it and its fields. + Such a chain is the one [Lam_pass_deep_flatten] leaves when it hoists the + bindings of a spread source out of a record. Both option wrappers preserve + the block's JS representation when their payload is a known block. The + block is built by [Pmakeblock], is a constant when its fields are all + constants (as [transl_record] makes [{...s, next: None}]), or is a shallow + copy built by [Pduprecord] followed by field assignments and ending in the + copy's variable (as [transl_record] makes for a partial spread of a record + with optional fields). *) +let tail_block (lam : Lambda.t) = + let rec find ~before ~dups (lam : Lambda.t) = + match lam with + | Lprim {primitive = Psome | Psome_not_nest; args = [body]} -> + find ~before ~dups body + | Llet (_, id, Lprim {primitive = Pduprecord; args}, body) -> + find ~before:(args @ before) ~dups:(Set_ident.add id dups) body + | Llet (_, id, rhs, body) when is_dups_alias dups rhs -> + find ~before ~dups:(Set_ident.add id dups) body + | Lsequence (Lprim {primitive = Psetfield _; args = [Lvar id; value]}, body) + when Set_ident.mem id dups -> + find ~before:(value :: before) ~dups body + | Lsequence (prefix, body) | Llet (_, _, prefix, body) -> + find ~before:(prefix :: before) ~dups body + | Lletrec (bindings, body) -> + find ~before:(List.map snd bindings @ before) ~dups body + | Lprim {primitive = Pmakeblock tag_info; args} -> + Some (tag_info, args @ before) + | Lconst c -> ( + match const_block_tag c with + | Some tag_info -> Some (tag_info, before) + | None -> None) + | Lvar id when Set_ident.mem id dups -> + Some (Lambda.blk_record [||] Immutable ~array:false, before) + | _ -> None + in + find ~before:[] ~dups:Set_ident.empty lam + +(* Whether evaluating the expressions [evaluated] may read a binding of + [group]. A function reads none of them when it is built, whatever it refers + to; any other expression reads one when it refers to it. *) +let reads_any group (evaluated : Lambda.t list) = + List.exists + (fun (arg : Lambda.t) -> + match arg with + | Lfunction _ -> false + | _ -> Lam_hit.hit_variables group arg) + evaluated + +(* The tag of the block that [lam] builds after evaluating other expressions, + when the block or the expressions before it may read one of the recursive + [all_bindings], as in [let rec r = {...f(), next: r}], whose spread source + [f()] is evaluated for its side effects first, or in + [let rec r = {...{let rec s = {next: r}; s}, next: base}], whose source + reads [r] while it is built. Such a binding is declared as a dummy before + those expressions run, and the block is copied into it. A bare block is + compiled into a dummy by the caller already. *) +let block_after_effects ~(all_bindings : (Ident.t * Lambda.t) list) + (lam : Lambda.t) = + match tail_block lam with + | Some (tag_info, evaluated) + when reads_any (Set_ident.of_list (List.map fst all_bindings)) evaluated -> + Some tag_info + | Some _ | None -> None + +(* The expressions evaluated to build [lam] that may read a variable while + they are evaluated: those evaluated to build its block or, for any other + value, [lam] itself. A function reads none when it is built, so a group of + functions, the common [let rec], has none to look at. *) +let evaluated_reads (lam : Lambda.t) = + let evaluated = + match tail_block lam with + | Some (_, evaluated) -> evaluated + | None -> [lam] + in + List.filter + (fun (arg : Lambda.t) -> + match arg with + | Lfunction _ -> false + | _ -> true) + evaluated + +(* The bindings of the recursive group [id_args], listed in the order they are + built, that a binding built before them reads, as [a] in + [let rec b = {next: Some(a), f: () => b} and a = {next: None, f: () => b}]. + Such a binding must be declared before that read, so it is built into a + dummy even when it could be declared directly where it is built. Only the + bindings built after a binding are looked for in what it reads, and only + when it evaluates something other than functions, so a group of functions + costs one walk over its bindings. *) +let read_before_built (id_args : (Ident.t * Lambda.t) list) = + let rec mark read_before (id_args : (Ident.t * Lambda.t) list) = + match id_args with + | [] -> read_before + | (_, arg) :: later -> ( + match evaluated_reads arg with + | [] -> mark read_before later + | evaluated -> + let read_before = + List.fold_left + (fun read_before (id, _) -> + if List.exists (Lam_hit.hit_variable id) evaluated then + Set_ident.add id read_before + else read_before) + read_before later + in + mark read_before later) + in + mark Set_ident.empty id_args + let args_either_function_or_const (args : Lambda.t list) = List.for_all (fun (x : Lambda.t) -> @@ -755,26 +879,13 @@ let compile output_prefix = | _ -> assert false))) ls), [] ) - | Lprim {primitive = Pmakeblock tag_info} -> ( + | Lprim {primitive = Pmakeblock tag_info} -> (* Lconst should not appear here if we do [scc] optimization, since it's faked recursive value, however it would affect scope issues, we have to declare it first *) - match compile_lambda {cxt with continuation = NeedValue Not_tail} arg with - | {block = b; value = Some v} -> - (* TODO: check recursive value .. - could be improved for simple cases - *) - ( Js_output.make - (List.append b - [ - S.exp - (E.runtime_call Primitive_modules.object_ "updateDummy" - [E.var id; v]); - ]), - [S.define_variable ~kind:Variable id (E.dummy_obj tag_info)] ) - | _ -> assert false) - | _ -> + compile_into_dummy cxt id tag_info arg + | _ -> ( (* pathological case: fail to capture taill call? {[ let rec a = @@ -796,15 +907,42 @@ let compile output_prefix = fun _-> print_endline "hey"; v () ]} *) - (compile_lambda {cxt with continuation = Declare (Alias, id)} arg, []) + match block_after_effects ~all_bindings arg with + | Some tag_info -> compile_into_dummy cxt id tag_info arg + | None -> + (compile_lambda {cxt with continuation = Declare (Alias, id)} arg, [])) + (* [id] is declared as a dummy object, which the block [arg] evaluates to is + copied into *) + and compile_into_dummy cxt id tag_info arg = + match compile_lambda {cxt with continuation = NeedValue Not_tail} arg with + | {block = b; value = Some v} -> + (* TODO: check recursive value .. + could be improved for simple cases + *) + ( Js_output.make + (List.append b + [ + S.exp + (E.runtime_call Primitive_modules.object_ "updateDummy" + [E.var id; v]); + ]), + [S.define_variable ~kind:Variable id (E.dummy_obj tag_info)] ) + | _ -> assert false and compile_recursive_lets_aux cxt (id_args : (Ident.t * Lambda.t) list) : Js_output.t = (* #1716 *) + let read_before = read_before_built id_args in let output_code, ids = List.fold_right (fun (ident, arg) (acc, ids) -> + (* A binding read before it is built that builds no block, such as + an array, cannot be a dummy and is declared where it is built *) let code, declare_ids = - compile_recursive_let ~all_bindings:id_args cxt ident arg + match tail_block arg with + | Some (tag_info, _) when Set_ident.mem ident read_before -> + compile_into_dummy cxt ident tag_info arg + | Some _ | None -> + compile_recursive_let ~all_bindings:id_args cxt ident arg in (Js_output.append_output code acc, List.append declare_ids ids)) id_args (Js_output.dummy, []) diff --git a/compiler/typing/rec_check.ml b/compiler/typing/rec_check.ml index 9744e66a23..bcd00759fb 100644 --- a/compiler/typing/rec_check.ml +++ b/compiler/typing/rec_check.ml @@ -298,7 +298,10 @@ let rec expression : Env.env -> Typedtree.expression -> Use.t = Use.guard in let field env (_, _, e) = expression env e in - Use.join (use (array field env es)) (option expression env eo) + let source = option expression env eo in + (* A source whose fields are all overridden is evaluated and dropped *) + let source = if writes_all_labels es then Use.discard source else source in + Use.join (use (array field env es)) source | Texp_ifthenelse (cond, ifso, ifnot) -> Use.( join @@ -498,7 +501,11 @@ let check_recursive_bindings valbinds = List.iter (fun {vb_expr} -> match vb_expr.exp_desc with - | Texp_record {fields = [|(lbl, _, {exp_desc = Texp_function _})|]} + | Texp_record + { + fields = [|(lbl, _, {exp_desc = Texp_function _})|]; + extended_expression = None; + } when Array.length lbl.lbl_all = 1 -> () | Texp_function _ -> () diff --git a/compiler/typing/translcore.ml b/compiler/typing/translcore.ml index b50eb03221..18bc98ed95 100644 --- a/compiler/typing/translcore.ml +++ b/compiler/typing/translcore.ml @@ -1032,16 +1032,6 @@ let jsx_children ~multi (lbl : label_description) (child : expression) = Some children | _ -> None -(* All labels of the record a [Texp_record] builds. Its [fields] hold only the - written ones. *) -let all_labels - (fields : (label_description * Longident.t loc * expression) array) = - match fields with - | [||] -> [||] - | _ -> - let lbl, _, _ = fields.(0) in - lbl.lbl_all - (* Each label of the record with the expression the literal writes for it, if any, in position order. A list rather than an array: [Array.map] over more than 256 labels (JSX props) forces a minor collection, which stops every @@ -1100,8 +1090,10 @@ let bind_strict defs body = (* How [transl_record] builds a record: by copying the fields of [init] one by one (or with no [init] at all), or by taking a shallow copy of [init] - and setting the other fields. JSX props follow the same rule. A shallow - copy is an object spread, so an array record always copies its fields. + and setting the other fields. With no field left to take from [init], it is + evaluated for its side effects and not copied. JSX props follow the same + rule. A shallow copy is an object spread, so an array record always copies + its fields. TODO: More strategies 3 + 2 * List.length lbl_expr_list >= size (density) *) let record_copies_fields @@ -1109,6 +1101,7 @@ let record_copies_fields ~(init : expression option) = match init with | None -> true + | Some _ when writes_all_labels fields -> true | Some _ -> ( let lbl_all = all_labels fields in match lbl_all.(0).lbl_repres with @@ -1117,6 +1110,14 @@ let record_copies_fields Array.length lbl_all < 20 && not (Array.exists (fun lbl -> lbl.lbl_optional) lbl_all)) +(* Whether [transl_record] leaves out the record's source: with no field to + take from it, a variable has nothing to evaluate. A binding for it would + count toward the size that decides whether a function is inlined. *) +let drops_record_source fields (init : Lambda.t) = + match init with + | Lvar _ -> writes_all_labels fields + | _ -> false + let jsx_props_of ~multi (props : expression) = match props.exp_desc with | Texp_record @@ -1769,6 +1770,7 @@ and transl_jsx_element loc (* An optional prop that is statically [undefined] can be left out, unless it overrides a prop of the spread *) let has_spread = Option.is_some init && not copy_fields in + let drops_source = drops_record_source fields in let field (lbl : label_description) value = (lbl.lbl_runtime_name, lbl.lbl_optional && not has_spread, value) in @@ -1799,7 +1801,9 @@ and transl_jsx_element loc let init, spread = match init with | None -> (None, None) - | Some init when copy_fields -> (Some (transl_exp init), None) + | Some init when copy_fields -> + let init = transl_exp init in + ((if drops_source init then None else Some init), None) | Some init -> (None, Some (transl_exp init)) in (init, spread, defs, fields, children) @@ -1970,7 +1974,9 @@ and transl_record loc env fields repres opt_init_expr = match opt_init_expr with | None -> lam | Some init_expr -> - let_ Strict init_id (transl_exp init_expr) (bind_strict defs lam) + let init = transl_exp init_expr in + if drops_record_source fields init then lam + else let_ Strict init_id init (bind_strict defs lam) else (* Take a shallow copy of the init record, then mutate the fields of the copy *) diff --git a/compiler/typing/typecore.ml b/compiler/typing/typecore.ml index 4fde5f8812..3b4a1e562c 100644 --- a/compiler/typing/typecore.ml +++ b/compiler/typing/typecore.ml @@ -2087,7 +2087,9 @@ let rec is_nonexpansive exp = | Texp_variant (_, arg) -> is_nonexpansive_opt arg | Texp_record {fields; extended_expression} -> ( Array.for_all (fun (_, _, exp) -> is_nonexpansive exp) fields - && is_nonexpansive_opt extended_expression + (* A source whose fields are all overridden is evaluated and dropped, like + the first expression of a sequence *) + && (writes_all_labels fields || is_nonexpansive_opt extended_expression) && (* The literal allocates every field of the record: written, copied from the spread, or left out *) @@ -3168,22 +3170,19 @@ and type_expect_ ?deprecated_context ~context ?(recarg = Rejected) Array.iter unify_kept lbl.lbl_all; Some {exp with exp_type = ty_exp} in - let num_fields = - match lbl_exp_list with - | [] -> assert false - | (_, lbl, _, _) :: _ -> Array.length lbl.lbl_all - in - let opt_exp = - if List.length lid_sexp_list = num_fields then ( - Loc_report.prerr_warning loc Warnings.Useless_record_with; - None) - else opt_exp - in let representation = let _, {lbl_repres}, _, _ = List.hd lbl_exp_list in lbl_repres in let fields = record_fields lbl_exp_list in + (if writes_all_labels fields then + let source_is_variable = + match exp.exp_desc with + | Texp_ident _ -> true + | _ -> false + in + Loc_report.prerr_warning loc + (Warnings.Useless_record_with {source_is_variable})); re { exp_desc = diff --git a/compiler/typing/typedtree.ml b/compiler/typing/typedtree.ml index 1a688c604c..398c379356 100644 --- a/compiler/typing/typedtree.ml +++ b/compiler/typing/typedtree.ml @@ -568,3 +568,15 @@ let rec alpha_pat env p = let mkloc = Location.mkloc let mknoloc = Location.mknoloc + +let all_labels + (fields : (label_description * Longident.t loc * expression) array) = + match fields with + | [||] -> [||] + | _ -> + let lbl, _, _ = fields.(0) in + lbl.lbl_all + +let writes_all_labels fields = + Array.length fields > 0 + && Array.length fields = Array.length (all_labels fields) diff --git a/compiler/typing/typedtree.mli b/compiler/typing/typedtree.mli index 558cc3821f..a4fad7b6f9 100644 --- a/compiler/typing/typedtree.mli +++ b/compiler/typing/typedtree.mli @@ -230,6 +230,9 @@ and expression_desc = one, and is otherwise an optional field set to [None]. The record's other labels are in [lbl_all] of any written label. + When the literal writes every field (see [writes_all_labels]), E0 + is evaluated only for its side effects. + If the type is { l1: t1; l2: t2 }, the expression { E0 with t2=P2 } is represented as Texp_record @@ -599,3 +602,13 @@ val exp_warning_attributes : expression -> attributes (** The attributes whose warning settings apply to an expression, in the order [Builtin_attributes.warning_scope] takes them: its own, then those of the type constraints around it, which [exp_extra] holds outermost first. *) + +val all_labels : + (Types.label_description * Longident.t loc * expression) array -> + Types.label_description array +(** All labels of the record a [Texp_record] builds. Its [fields] hold only the + written ones. *) + +val writes_all_labels : + (Types.label_description * Longident.t loc * expression) array -> bool +(** Whether the [fields] of a [Texp_record] hold every label of the record *) diff --git a/compiler/typing/warnings.ml b/compiler/typing/warnings.ml index 6d98ad2126..41e4b961e0 100644 --- a/compiler/typing/warnings.ml +++ b/compiler/typing/warnings.ml @@ -39,7 +39,7 @@ type t = | Unused_argument (* 20 *) | Nonreturning_statement (* 21 *) | Preprocessor of string (* 22 *) - | Useless_record_with (* 23 *) + | Useless_record_with of {source_is_variable: bool} (* 23 *) | All_clauses_guarded (* 8, used to be 25 *) | Unused_var of string (* 26 *) | Unused_var_strict of string (* 27 *) @@ -94,7 +94,7 @@ let number = function | Unused_argument -> 20 | Nonreturning_statement -> 21 | Preprocessor _ -> 22 - | Useless_record_with -> 23 + | Useless_record_with _ -> 23 | All_clauses_guarded -> 8 (* used to be 25 *) | Unused_var _ -> 26 | Unused_var_strict _ -> 27 @@ -307,9 +307,13 @@ let message = function | Nonreturning_statement -> "This statement does not continue execution; following code is unreachable." | Preprocessor s -> s - | Useless_record_with -> + | Useless_record_with {source_is_variable = true} -> "All the fields are already explicitly listed in this record. You can \ remove the `...` spread." + | Useless_record_with {source_is_variable = false} -> + "All the fields are already explicitly listed in this record, so the `...` \ + spread copies none of them. Its source is still evaluated: if you remove \ + the spread, keep any effect the source has." | All_clauses_guarded -> "this pattern-matching is not exhaustive.\n\ All clauses in this pattern-matching are guarded." diff --git a/compiler/typing/warnings.mli b/compiler/typing/warnings.mli index 71d9e4c865..fb9b85d0eb 100644 --- a/compiler/typing/warnings.mli +++ b/compiler/typing/warnings.mli @@ -32,7 +32,9 @@ type t = | Unused_argument (* 20 *) | Nonreturning_statement (* 21 *) | Preprocessor of string (* 22 *) - | Useless_record_with (* 23 *) + | Useless_record_with of {source_is_variable: bool} + (* 23: whether the source of the spread is a variable, which can be + removed without dropping an effect *) | All_clauses_guarded (* 8, used to be 25 *) | Unused_var of string (* 26 *) | Unused_var_strict of string (* 27 *) diff --git a/tests/compiler_tests/src/record_spread_pure_source.mjs b/tests/compiler_tests/src/record_spread_pure_source.mjs new file mode 100644 index 0000000000..1b1281a307 --- /dev/null +++ b/tests/compiler_tests/src/record_spread_pure_source.mjs @@ -0,0 +1,60 @@ +// Generated by ReScript, PLEASE EDIT WITH CARE + +import * as JsxRuntime from "react/jsx-runtime"; + +let overridden = { + x: 3, + y: 4 +}; + +function override(source, x) { + return { + x: x, + y: 2 + }; +} + +function callOverride(x) { + return x; +} + +function Record_spread_pure_source$Component(props) { + return props.a + props.b | 0; +} + +let Component = { + make: Record_spread_pure_source$Component +}; + +function overrideJsx(props) { + return JsxRuntime.jsx(Record_spread_pure_source$Component, { + a: 1, + b: 2 + }); +} + +function callOverrideJsx(props) { + return JsxRuntime.jsx(Record_spread_pure_source$Component, { + a: 1, + b: 2 + }); +} + +let base = { + x: 1, + y: 2 +}; + +let Component$make = Record_spread_pure_source$Component; + +export { + base, + overridden, + override, + callOverride, + Component, + overrideJsx, + callOverrideJsx, + Component$make, +} +/* react/jsx-runtime Not a pure module */ diff --git a/tests/compiler_tests/src/record_spread_pure_source.res b/tests/compiler_tests/src/record_spread_pure_source.res new file mode 100644 index 0000000000..ec100f94cc --- /dev/null +++ b/tests/compiler_tests/src/record_spread_pure_source.res @@ -0,0 +1,28 @@ +// A variable as the source of a record spread whose fields are all overridden +// leaves no trace in the output: `override` and `overrideJsx` are still small +// enough to be inlined, and `overridden` is emitted before `base`, as a record +// without the spread would be. +// Warning 23 reports these spreads; it stays on, but not as an error. +@@config({flags: ["-bs-jsx", "4", "-warn-error", "-23"]}) + +type point = {x: int, y: int} + +let base = {x: 1, y: 2} +let overridden = {...base, x: 3, y: 4} + +let _ = overridden + +let override = (source, x) => {...source, x, y: 2} + +let callOverride = x => override({x: 0, y: 0}, x).x + +module Component = { + type props = {a: int, b: int} + + @react.componentWithProps + let make = props => React.int(props.a + props.b) +} + +let overrideJsx = props => + +let callOverrideJsx = props => overrideJsx(props) diff --git a/tests/compiler_tests/src/record_spread_source_effect_dep.mjs b/tests/compiler_tests/src/record_spread_source_effect_dep.mjs new file mode 100644 index 0000000000..2199da6424 --- /dev/null +++ b/tests/compiler_tests/src/record_spread_source_effect_dep.mjs @@ -0,0 +1,17 @@ +// Generated by ReScript, PLEASE EDIT WITH CARE + + +let loads = [1]; + +loads.push(2); + +let base = { + x: 0, + y: 0 +}; + +export { + loads, + base, +} +/* Not a pure module */ diff --git a/tests/compiler_tests/src/record_spread_source_effect_dep.res b/tests/compiler_tests/src/record_spread_source_effect_dep.res new file mode 100644 index 0000000000..dfd92724d1 --- /dev/null +++ b/tests/compiler_tests/src/record_spread_source_effect_dep.res @@ -0,0 +1,7 @@ +type point = {x: int, y: int} + +let loads = [1] + +loads->Array.push(2) + +let base = {x: 0, y: 0} diff --git a/tests/compiler_tests/src/record_spread_source_effect_test.mjs b/tests/compiler_tests/src/record_spread_source_effect_test.mjs new file mode 100644 index 0000000000..24de8126a1 --- /dev/null +++ b/tests/compiler_tests/src/record_spread_source_effect_test.mjs @@ -0,0 +1,758 @@ +// Generated by ReScript, PLEASE EDIT WITH CARE + +import * as Mocha from "mocha"; +import * as Test_utils from "./test_utils.mjs"; +import * as Stdlib_JsError from "@rescript/runtime/lib/es6/Stdlib_JsError.mjs"; +import * as Primitive_object from "@rescript/runtime/lib/es6/Primitive_object.mjs"; +import * as Primitive_option from "@rescript/runtime/lib/es6/Primitive_option.mjs"; +import * as JsxRuntime from "react/jsx-runtime"; +import * as Primitive_exceptions from "@rescript/runtime/lib/es6/Primitive_exceptions.mjs"; +import * as Record_spread_source_effect_dep from "./record_spread_source_effect_dep.mjs"; + +function Record_spread_source_effect_test$Component(props) { + let __b = props.b; + let __b_value = __b !== undefined ? __b : 2; + return props.a + __b_value | 0; +} + +let Component = { + make: Record_spread_source_effect_test$Component +}; + +function id(x) { + return x; +} + +let calls = []; + +function logged(name, value) { + calls.push(name); + return value; +} + +function takeCalls() { + let taken = calls.slice(); + calls.splice(0, calls.length); + return taken; +} + +logged("polymorphic", id({ + compare: undefined, + first: 1 +})); + +let polymorphic = { + compare: undefined, + first: undefined +}; + +function base_self() { + return base; +} + +let base = { + self: base_self, + value: 0 +}; + +logged("recursive", id(base)); + +function recursive_self() { + return recursive; +} + +let recursive = { + self: recursive_self, + value: 2 +}; + +function selfSpread_self() { + return selfSpread; +} + +let selfSpread = { + self: selfSpread_self, + value: 3 +}; + +let singleCallback = { + run: () => 4 +}; + +function makeNode(value) { + let node = {}; + node.next = node; + node.value = value; + return node; +} + +let cycle = {}; + +Primitive_object.updateDummy(cycle, (logged("cycle", makeNode(0)), { + next: cycle, + value: 7 +})); + +let letCycle = {}; + +let value = logged("letCycle", id(8)); + +Primitive_object.updateDummy(letCycle, (logged("letCycleSource", makeNode(0)), { + next: letCycle, + value: value +})); + +let sequenceCycle = {}; + +Primitive_object.updateDummy(sequenceCycle, (logged("sequenceCycle", undefined), { + next: sequenceCycle, + value: 9 +})); + +let letRecCycle = {}; + +function retry(_attempts) { + while (true) { + let attempts = _attempts; + if (attempts <= 0) { + return logged("letRecCycle", makeNode(0)); + } + _attempts = attempts - 1 | 0; + continue; + }; +} + +Primitive_object.updateDummy(letRecCycle, (retry(id(2)), { + next: letRecCycle, + value: 12 +})); + +function localLetRecCycle(value) { + let node = {}; + let retry = _attempts => { + while (true) { + let attempts = _attempts; + if (attempts <= 0) { + return makeNode(0); + } + _attempts = attempts - 1 | 0; + continue; + }; + }; + Primitive_object.updateDummy(node, (retry(id(2)), { + next: node, + value: value + })); + return node; +} + +let leaf = {}; + +leaf.left = leaf; + +leaf.right = leaf; + +leaf.value = 0; + +let prefixRead = {}; + +let source = {}; + +Primitive_object.updateDummy(source, { + left: source, + right: prefixRead, + value: logged("prefixRead", id(14)) +}); + +Primitive_object.updateDummy(prefixRead, { + left: leaf, + right: leaf, + value: 14 +}); + +function localPrefixRead(value) { + let tree = {}; + let source = {}; + source.left = source; + source.right = tree; + source.value = value; + Primitive_object.updateDummy(tree, { + left: leaf, + right: leaf, + value: value + }); + return tree; +} + +let constantPrefixRead = {}; + +let source$1 = {}; + +Primitive_object.updateDummy(source$1, { + lower: source$1, + upper: constantPrefixRead, + weight: logged("constantPrefixRead", id(16)) +}); + +Primitive_object.updateDummy(constantPrefixRead, { + lower: undefined, + upper: undefined, + weight: 16 +}); + +function localConstantPrefixRead(value) { + let branch = {}; + let source = {}; + Primitive_object.updateDummy(source, { + lower: source, + upper: branch, + weight: value + }); + Primitive_object.updateDummy(branch, { + lower: undefined, + upper: undefined, + weight: 17 + }); + return branch; +} + +let sourceReadsLater = {}; + +let later = {}; + +let source$2 = {}; + +Primitive_object.updateDummy(source$2, { + next: later, + back: () => source$2, + weight: logged("sourceReadsLater", id(19)) +}); + +Primitive_object.updateDummy(sourceReadsLater, { + next: undefined, + back: () => sourceReadsLater, + weight: 19 +}); + +Primitive_object.updateDummy(later, { + next: undefined, + back: () => sourceReadsLater, + weight: 20 +}); + +function localSourceReadsLater(weight) { + let link = {}; + let later = {}; + let source = {}; + Primitive_object.updateDummy(source, { + next: later, + back: () => source, + weight: weight + }); + Primitive_object.updateDummy(link, { + next: undefined, + back: () => link, + weight: weight + }); + Primitive_object.updateDummy(later, { + next: undefined, + back: () => link, + weight: weight + 1 | 0 + }); + return link; +} + +function baseOptLink_optBack() { + return baseOptLink; +} + +let baseOptLink_optWeight = 25; + +let baseOptLink = { + optNext: undefined, + optBack: baseOptLink_optBack, + optWeight: baseOptLink_optWeight +}; + +let sourceReadsLaterCopy = {}; + +let laterCopy = {}; + +let source$3 = {}; + +Primitive_object.updateDummy(source$3, { + optNext: laterCopy, + optBack: () => source$3, + optWeight: logged("sourceReadsLaterCopy", id(26)) +}); + +Primitive_object.updateDummy(sourceReadsLaterCopy, { + optNext: undefined, + optBack: () => sourceReadsLaterCopy, + optWeight: 26 +}); + +Primitive_object.updateDummy(laterCopy, { + ...baseOptLink, + optBack: () => sourceReadsLaterCopy +}); + +function localSourceReadsLaterCopy(weight) { + let link = {}; + let later = {}; + let source = {}; + Primitive_object.updateDummy(source, { + optNext: later, + optBack: () => source, + optWeight: weight + }); + Primitive_object.updateDummy(link, { + optNext: undefined, + optBack: () => link, + optWeight: weight + }); + Primitive_object.updateDummy(later, { + ...baseOptLink, + optBack: () => link + }); + return [ + link, + later + ]; +} + +let optionalPrefixRead = {}; + +let source$4 = {}; + +Primitive_object.updateDummy(source$4, { + lower: source$4, + upper: optionalPrefixRead, + weight: logged("optionalPrefixRead", id(27)) +}); + +Primitive_object.updateDummy(optionalPrefixRead, { + lower: undefined, + upper: undefined, + weight: 27 +}); + +function localOptionalPrefixRead(weight) { + let node = {}; + let source = {}; + Primitive_object.updateDummy(source, { + lower: source, + upper: node, + weight: weight + }); + Primitive_object.updateDummy(node, { + lower: undefined, + upper: undefined, + weight: weight + 1 | 0 + }); + return node; +} + +let nestedOptionalPrefixRead = {}; + +let source$5 = {}; + +Primitive_object.updateDummy(source$5, { + nestedLeft: source$5, + nestedRight: nestedOptionalPrefixRead, + nestedWeight: logged("nestedOptionalPrefixRead", id(31)) +}); + +Primitive_object.updateDummy(nestedOptionalPrefixRead, Primitive_option.some({ + nestedLeft: undefined, + nestedRight: undefined, + nestedWeight: 31 +})); + +function localNestedOptionalPrefixRead(weight) { + let node = {}; + let source = {}; + Primitive_object.updateDummy(source, { + nestedLeft: source, + nestedRight: node, + nestedWeight: weight + }); + Primitive_object.updateDummy(node, Primitive_option.some({ + nestedLeft: undefined, + nestedRight: undefined, + nestedWeight: weight + 1 | 0 + })); + return node; +} + +function baseNestedOptLink_nestedOptBack() { + return baseNestedOptLink; +} + +let baseNestedOptLink_nestedOptWeight = 32; + +let baseNestedOptLink = { + nestedOptNext: undefined, + nestedOptBack: baseNestedOptLink_nestedOptBack, + nestedOptWeight: baseNestedOptLink_nestedOptWeight +}; + +let nestedSourceReadsLaterCopy = {}; + +let nestedLaterCopy = {}; + +let source$6 = {}; + +Primitive_object.updateDummy(source$6, { + nestedOptNext: nestedLaterCopy, + nestedOptBack: () => source$6, + nestedOptWeight: logged("nestedSourceReadsLaterCopy", id(33)) +}); + +Primitive_object.updateDummy(nestedSourceReadsLaterCopy, { + nestedOptNext: undefined, + nestedOptBack: () => nestedSourceReadsLaterCopy, + nestedOptWeight: 33 +}); + +Primitive_object.updateDummy(nestedLaterCopy, Primitive_option.some({ + ...baseNestedOptLink, + nestedOptBack: () => nestedSourceReadsLaterCopy +})); + +function makeLink(weight) { + let link = {}; + Primitive_object.updateDummy(link, { + next: undefined, + back: () => link, + weight: weight + }); + return link; +} + +let mutualFirst = {}; + +let mutualSecond = {}; + +Primitive_object.updateDummy(mutualFirst, (logged("mutualFirst", makeLink(0)), { + next: mutualSecond, + back: () => mutualSecond, + weight: 22 +})); + +Primitive_object.updateDummy(mutualSecond, (logged("mutualSecond", makeLink(0)), { + next: mutualFirst, + back: () => mutualFirst, + weight: 23 +})); + +let wrapped = {}; + +Primitive_object.updateDummy(wrapped, { + TAG: "Shape", + _0: (logged("wrapped", id({ + around: "NoShape", + size: 0 + })), { + around: wrapped, + size: 24 + }) +}); + +function isWrapped(shape) { + if (typeof shape !== "object") { + return false; + } else { + return shape._0.around === shape; + } +} + +function nextCount() { + return counter.start + 1 | 0; +} + +logged("counter", undefined); + +let counter_start = logged("counterStart", id(10)); + +function counter_step() { + return counter.start + 1 | 0; +} + +let counter = { + start: counter_start, + step: counter_step +}; + +let moduleCalls = takeCalls(); + +let fromOtherModule = { + x: 5, + y: 6 +}; + +function overridePure(source) { + return { + x: 1, + y: logged("y", 2) + }; +} + +function overrideJsxPure(props) { + return JsxRuntime.jsx(Record_spread_source_effect_test$Component, { + a: 1, + b: 2 + }); +} + +Mocha.describe("Record_spread_source_effect_test", () => { + Mocha.test("a source whose fields are all overridden runs first", () => { + logged("source", { + x: 0, + y: 0 + }); + let point_x = logged("x", id(1)); + let point_y = logged("y", id(2)); + let point = { + x: point_x, + y: point_y + }; + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 388, characters 7-14", takeCalls(), [ + "source", + "x", + "y" + ]); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 389, characters 7-14", point, { + x: 1, + y: 2 + }); + }); + Mocha.test("a source of a record with optional fields runs", () => { + logged("source", { + height: 0 + }); + let options = { + width: 1, + height: 2 + }; + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 394, characters 7-14", takeCalls(), ["source"]); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 395, characters 7-14", options, { + width: 1, + height: 2 + }); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 397, characters 7-14", JSON.stringify(options), `{"width":1,"height":2}`); + }); + Mocha.test("a source that raises stops the record from being built", () => { + let result; + try { + logged("source", Stdlib_JsError.throwWithMessage("source")); + result = 1; + } catch (raw_exn) { + let exn = Primitive_exceptions.internalToException(raw_exn); + if (exn.RE_EXN_ID === "JsExn") { + result = -1; + } else { + throw exn; + } + } + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 407, characters 7-14", result, -1); + }); + Mocha.test("the source of a JSX element's props runs", () => { + logged("props", { + a: 0 + }); + JsxRuntime.jsx(Record_spread_source_effect_test$Component, { + a: 1, + b: 2 + }); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 412, characters 7-14", takeCalls(), ["props"]); + }); + Mocha.test("sources of module-level and recursive records run", () => { + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 418, characters 6-13", moduleCalls, [ + "polymorphic", + "recursive", + "cycle", + "letCycle", + "letCycleSource", + "sequenceCycle", + "letRecCycle", + "prefixRead", + "constantPrefixRead", + "sourceReadsLater", + "sourceReadsLaterCopy", + "optionalPrefixRead", + "nestedOptionalPrefixRead", + "nestedSourceReadsLaterCopy", + "mutualFirst", + "mutualSecond", + "wrapped", + "counter", + "counterStart" + ]); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 442, characters 7-14", undefined, undefined); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 443, characters 7-14", undefined, undefined); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 444, characters 7-14", recursive_self().value, 2); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 445, characters 7-14", selfSpread_self().value, 3); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 446, characters 7-14", singleCallback.run(), 4); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 447, characters 7-14", cycle.next === cycle, true); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 448, characters 7-14", cycle.next.value, 7); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 449, characters 7-14", letCycle.next === letCycle, true); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 450, characters 7-14", letCycle.next.value, 8); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 451, characters 7-14", sequenceCycle.next === sequenceCycle, true); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 452, characters 7-14", sequenceCycle.next.value, 9); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 453, characters 7-14", letRecCycle.next === letRecCycle, true); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 454, characters 7-14", letRecCycle.next.value, 12); + let local = localLetRecCycle(13); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 456, characters 7-14", local.next === local, true); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 457, characters 7-14", local.next.value, 13); + let localPrefix = localPrefixRead(15); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 459, characters 7-14", prefixRead.left === leaf, true); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 460, characters 7-14", prefixRead.value, 14); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 461, characters 7-14", localPrefix.value, 15); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 462, characters 7-14", constantPrefixRead, { + lower: undefined, + upper: undefined, + weight: 16 + }); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 463, characters 7-14", localConstantPrefixRead(18), { + lower: undefined, + upper: undefined, + weight: 17 + }); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 464, characters 7-14", sourceReadsLater.weight, 19); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 465, characters 7-14", later.back() === sourceReadsLater, true); + let localLink = localSourceReadsLater(21); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 467, characters 7-14", localLink.weight, 21); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 468, characters 7-14", localLink.back() === localLink, true); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 469, characters 7-14", sourceReadsLaterCopy.optWeight, 26); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 470, characters 7-14", laterCopy.optBack() === sourceReadsLaterCopy, true); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 471, characters 7-14", laterCopy.optWeight, 25); + let match = localSourceReadsLaterCopy(28); + let localLaterCopy = match[1]; + let localCopyLink = match[0]; + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 473, characters 7-14", localCopyLink.optWeight, 28); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 474, characters 7-14", localLaterCopy.optBack() === localCopyLink, true); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 475, characters 7-14", localLaterCopy.optWeight, 25); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 476, characters 7-14", optionalPrefixRead, { + lower: undefined, + upper: undefined, + weight: 27 + }); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 477, characters 7-14", localOptionalPrefixRead(29), { + lower: undefined, + upper: undefined, + weight: 30 + }); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 479, characters 6-13", nestedOptionalPrefixRead, { + nestedLeft: undefined, + nestedRight: undefined, + nestedWeight: 31 + }); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 484, characters 6-13", localNestedOptionalPrefixRead(34), { + nestedLeft: undefined, + nestedRight: undefined, + nestedWeight: 35 + }); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 488, characters 7-14", nestedSourceReadsLaterCopy.nestedOptWeight, 33); + let copy = Primitive_option.valFromOption(nestedLaterCopy); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 490, characters 6-13", copy !== undefined ? [ + copy.nestedOptBack() === nestedSourceReadsLaterCopy, + copy.nestedOptWeight + ] : [ + false, + undefined + ], [ + true, + 32 + ]); + let opt = mutualFirst.next; + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 500, characters 7-14", opt !== undefined ? Primitive_option.some(Primitive_option.valFromOption(opt) === mutualSecond) : undefined, true); + let opt$1 = mutualSecond.next; + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 501, characters 7-14", opt$1 !== undefined ? Primitive_option.some(Primitive_option.valFromOption(opt$1) === mutualFirst) : undefined, true); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 502, characters 7-14", mutualFirst.back() === mutualSecond, true); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 503, characters 7-14", mutualSecond.weight, 23); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 504, characters 7-14", isWrapped(wrapped), true); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 505, characters 7-14", counter_start, 10); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 506, characters 7-14", counter_step(), 11); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 507, characters 7-14", fromOtherModule, { + x: 5, + y: 6 + }); + }); + Mocha.test("a pure source is left out", () => { + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 511, characters 7-14", overridePure(id({ + x: 0, + y: 0 + })), { + x: 1, + y: 2 + }); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 512, characters 7-14", takeCalls(), ["y"]); + id({ + a: 0 + }); + JsxRuntime.jsx(Record_spread_source_effect_test$Component, { + a: 1, + b: 2 + }); + }); +}); + +let strings = polymorphic; + +let ints = polymorphic; + +let Component$make = Record_spread_source_effect_test$Component; + +export { + Component, + id, + calls, + logged, + takeCalls, + polymorphic, + strings, + ints, + base, + recursive, + selfSpread, + singleCallback, + makeNode, + cycle, + letCycle, + sequenceCycle, + letRecCycle, + localLetRecCycle, + leaf, + prefixRead, + localPrefixRead, + constantPrefixRead, + localConstantPrefixRead, + sourceReadsLater, + later, + localSourceReadsLater, + baseOptLink, + sourceReadsLaterCopy, + laterCopy, + localSourceReadsLaterCopy, + optionalPrefixRead, + localOptionalPrefixRead, + nestedOptionalPrefixRead, + localNestedOptionalPrefixRead, + baseNestedOptLink, + nestedSourceReadsLaterCopy, + nestedLaterCopy, + makeLink, + mutualFirst, + mutualSecond, + wrapped, + isWrapped, + nextCount, + counter, + moduleCalls, + fromOtherModule, + overridePure, + overrideJsxPure, + Component$make, +} +/* Not a pure module */ diff --git a/tests/compiler_tests/src/record_spread_source_effect_test.res b/tests/compiler_tests/src/record_spread_source_effect_test.res new file mode 100644 index 0000000000..04a68b389d --- /dev/null +++ b/tests/compiler_tests/src/record_spread_source_effect_test.res @@ -0,0 +1,515 @@ +// Every spread here has all its fields overridden, which warning 23 reports. +// The warning stays on, but not as an error, since that spread is under test. +@@config({flags: ["-bs-jsx", "4", "-warn-error", "-23"]}) + +open Mocha +open Test_utils + +type point = {x: int, y: int} +type options = {width?: int, height: int} +type polymorphic<'a> = {compare: option<('a, 'a) => int>, first: option<'a>} +type rec recursive = {self: unit => recursive, value: int} +type callback = {run: unit => int} +type rec node = {next: node, value: int} +type rec tree = {left: tree, right: tree, value: int} +type counter = {start: int, step: unit => int} +type rec branch = {lower: option, upper: option, weight: int} +type rec link = {next: option, back: unit => link, weight: int} + +type rec shape = Shape(shapeRecord) | NoShape +and shapeRecord = {around: shape, size: int} + +module Component = { + @react.component + let make = (~a: int, ~b: int=2) => React.int(a + b) +} + +@inline(never) +let id = x => x + +let calls = [] + +@inline(never) +let logged = (name, value) => { + calls->Array.push(name) + value +} + +let takeCalls = () => { + let taken = calls->Array.copy + calls->Array.splice(~start=0, ~remove=calls->Array.length, ~insert=[]) + taken +} + +// The source doesn't stop the record from being polymorphic +let polymorphic = { + ...logged("polymorphic", id({compare: None, first: Some(1)})), + compare: None, + first: None, +} + +let strings: polymorphic = polymorphic +let ints: polymorphic = polymorphic + +let rec base = {self: () => base, value: 0} + +let rec recursive = { + ...logged("recursive", id(base)), + self: () => recursive, + value: 2, +} + +let rec selfSpread = {...selfSpread, self: () => selfSpread, value: 3} + +let rec singleCallback = {...singleCallback, run: () => 4} + +let makeNode = value => { + let rec node = {next: node, value} + node +} + +// The record still refers to itself once its source has been evaluated +let rec cycle = {...logged("cycle", makeNode(0)), next: cycle, value: 7} + +let rec letCycle = { + let value = logged("letCycle", id(8)) + {...logged("letCycleSource", makeNode(0)), next: letCycle, value} +} + +// The same holds for a record built at the end of a sequence +let rec sequenceCycle = { + ignore(logged("sequenceCycle", ())) + {next: sequenceCycle, value: 9} +} + +// A recursive helper of the source is hoisted out of it, which leaves the +// record after a recursive let +let rec letRecCycle = { + ...{ + let rec retry = attempts => + attempts > 0 ? retry(attempts - 1) : logged("letRecCycle", makeNode(0)) + retry(id(2)) + }, + next: letRecCycle, + value: 12, +} + +// The same holds for a record local to a function +let localLetRecCycle = value => { + let rec node = { + ...{ + let rec retry = attempts => attempts > 0 ? retry(attempts - 1) : makeNode(0) + retry(id(2)) + }, + next: node, + value, + } + node +} + +// A source that reads the record while it is built sees the record, even +// though none of the record's own fields reads it +let rec leaf = {left: leaf, right: leaf, value: 0} + +let rec prefixRead = { + ...{ + let rec source = {left: source, right: prefixRead, value: logged("prefixRead", id(14))} + source + }, + left: leaf, + right: leaf, + value: 14, +} + +// The same holds for a record local to a function +let localPrefixRead = value => { + let rec tree = { + ...{ + let rec source = {left: source, right: tree, value} + source + }, + left: leaf, + right: leaf, + value, + } + tree +} + +// The same holds when the record's fields are all constants, so that the +// record is a constant +let rec constantPrefixRead = { + ...{ + let rec source = { + lower: Some(source), + upper: Some(constantPrefixRead), + weight: logged("constantPrefixRead", id(16)), + } + source + }, + lower: None, + upper: None, + weight: 16, +} + +// The same holds for a record local to a function +let localConstantPrefixRead = value => { + let rec branch = { + ...{ + let rec source = {lower: Some(source), upper: Some(branch), weight: value} + source + }, + lower: None, + upper: None, + weight: 17, + } + branch +} + +// A binding of the group that a source reads while it is built is declared +// before that read, even one that could be declared where it is built +let rec sourceReadsLater = { + ...{ + let rec source = { + next: Some(later), + back: () => source, + weight: logged("sourceReadsLater", id(19)), + } + source + }, + next: None, + back: () => sourceReadsLater, + weight: 19, +} +and later = {next: None, back: () => sourceReadsLater, weight: 20} + +// The same holds for a record local to a function +let localSourceReadsLater = weight => { + let rec link = { + ...{ + let rec source = {next: Some(later), back: () => source, weight} + source + }, + next: None, + back: () => link, + weight, + } + and later = {next: None, back: () => link, weight: weight + 1} + link +} + +// A later binding built by a shallow-copy partial spread (record with an +// optional field) is also declared as a dummy before an earlier source reads it +type rec optLink = { + optNext: option, + optBack: unit => optLink, + optWeight?: int, +} + +let rec baseOptLink = {optNext: None, optBack: () => baseOptLink, optWeight: 25} + +let rec sourceReadsLaterCopy = { + ...{ + let rec source = { + optNext: Some(laterCopy), + optBack: () => source, + optWeight: logged("sourceReadsLaterCopy", id(26)), + } + source + }, + optNext: None, + optBack: () => sourceReadsLaterCopy, + optWeight: 26, +} +and laterCopy = {...baseOptLink, optBack: () => sourceReadsLaterCopy} + +let localSourceReadsLaterCopy = weight => { + let rec link = { + ...{ + let rec source = {optNext: Some(later), optBack: () => source, optWeight: weight} + source + }, + optNext: None, + optBack: () => link, + optWeight: weight, + } + and later = {...baseOptLink, optBack: () => link} + (link, later) +} + +// A non-nesting Some wrapper around a recursive record with a prefix read +let rec optionalPrefixRead = Some({ + ...{ + let rec source = { + lower: Some(source), + upper: optionalPrefixRead, + weight: logged("optionalPrefixRead", id(27)), + } + source + }, + lower: None, + upper: None, + weight: 27, +}) + +let localOptionalPrefixRead = weight => { + let rec node = Some({ + ...{ + let rec source = {lower: Some(source), upper: node, weight} + source + }, + lower: None, + upper: None, + weight: weight + 1, + }) + node +} + +// A nesting-capable Some(Some(...)) wrapper around a recursive record with a +// prefix read (both constant and non-constant final blocks, and a Pduprecord copy) +type rec nestedOpt = { + nestedLeft: option, + nestedRight: option>, + nestedWeight: int, +} + +let rec nestedOptionalPrefixRead = Some( + Some({ + ...{ + let rec source = { + nestedLeft: Some(source), + nestedRight: nestedOptionalPrefixRead, + nestedWeight: logged("nestedOptionalPrefixRead", id(31)), + } + source + }, + nestedLeft: None, + nestedRight: None, + nestedWeight: 31, + }), +) + +let localNestedOptionalPrefixRead = weight => { + let rec node = Some( + Some({ + ...{ + let rec source = {nestedLeft: Some(source), nestedRight: node, nestedWeight: weight} + source + }, + nestedLeft: None, + nestedRight: None, + nestedWeight: weight + 1, + }), + ) + node +} + +type rec nestedOptLink = { + nestedOptNext: option>, + nestedOptBack: unit => nestedOptLink, + nestedOptWeight?: int, +} + +let rec baseNestedOptLink = { + nestedOptNext: None, + nestedOptBack: () => baseNestedOptLink, + nestedOptWeight: 32, +} + +let rec nestedSourceReadsLaterCopy = { + ...{ + let rec source = { + nestedOptNext: nestedLaterCopy, + nestedOptBack: () => source, + nestedOptWeight: logged("nestedSourceReadsLaterCopy", id(33)), + } + source + }, + nestedOptNext: None, + nestedOptBack: () => nestedSourceReadsLaterCopy, + nestedOptWeight: 33, +} +and nestedLaterCopy = Some( + Some({...baseNestedOptLink, nestedOptBack: () => nestedSourceReadsLaterCopy}), +) + +// Each record of a mutually recursive group evaluates its own source +let makeLink = weight => { + let rec link = {next: None, back: () => link, weight} + link +} + +let rec mutualFirst = { + ...logged("mutualFirst", makeLink(0)), + next: Some(mutualSecond), + back: () => mutualSecond, + weight: 22, +} +and mutualSecond = { + ...logged("mutualSecond", makeLink(0)), + next: Some(mutualFirst), + back: () => mutualFirst, + weight: 23, +} + +// The same holds for a record inside a variant +let rec wrapped = Shape({ + ...logged("wrapped", id({around: NoShape, size: 0})), + around: wrapped, + size: 24, +}) + +let isWrapped = shape => + switch shape { + | Shape({around}) => around === shape + | NoShape => false + } + +// A record of a recursive group whose fields read none of the group's bindings +// when it is built is declared directly, after the expressions before it +let rec nextCount = () => counter.start + 1 +and counter = { + ignore(logged("counter", ())) + {start: logged("counterStart", id(10)), step: () => nextCount()} +} + +let moduleCalls = takeCalls() + +// The source is evaluated, so the module it comes from stays imported when it +// has side effects, even though its value is not needed +let fromOtherModule = {...Record_spread_source_effect_dep.base, x: 5, y: 6} + +let overridePure = (source: point) => {...source, x: 1, y: logged("y", 2)} + +let overrideJsxPure = props => + +describe(__MODULE__, () => { + test("a source whose fields are all overridden runs first", () => { + let point = {...logged("source", {x: 0, y: 0}), x: logged("x", id(1)), y: logged("y", id(2))} + eq(__LOC__, takeCalls(), ["source", "x", "y"]) + eq(__LOC__, point, {x: 1, y: 2}) + }) + + test("a source of a record with optional fields runs", () => { + let options = {...logged("source", {height: 0}), width: 1, height: 2} + eq(__LOC__, takeCalls(), ["source"]) + eq(__LOC__, options, {width: 1, height: 2}) + // A copy of the source would have `height` first + eq(__LOC__, JSON.stringifyAny(options), Some(`{"width":1,"height":2}`)) + }) + + test("a source that raises stops the record from being built", () => { + let result = try { + let point = {...logged("source", JsError.throwWithMessage("source")), x: 1, y: 2} + point.x + } catch { + | JsExn(_) => -1 + } + eq(__LOC__, result, -1) + }) + + test("the source of a JSX element's props runs", () => { + let element = + eq(__LOC__, takeCalls(), ["props"]) + ignore(element) + }) + + test("sources of module-level and recursive records run", () => { + eq( + __LOC__, + moduleCalls, + [ + "polymorphic", + "recursive", + "cycle", + "letCycle", + "letCycleSource", + "sequenceCycle", + "letRecCycle", + "prefixRead", + "constantPrefixRead", + "sourceReadsLater", + "sourceReadsLaterCopy", + "optionalPrefixRead", + "nestedOptionalPrefixRead", + "nestedSourceReadsLaterCopy", + "mutualFirst", + "mutualSecond", + "wrapped", + "counter", + "counterStart", + ], + ) + eq(__LOC__, strings.first, None) + eq(__LOC__, ints.first, None) + eq(__LOC__, recursive.self().value, 2) + eq(__LOC__, selfSpread.self().value, 3) + eq(__LOC__, singleCallback.run(), 4) + eq(__LOC__, cycle.next === cycle, true) + eq(__LOC__, cycle.next.value, 7) + eq(__LOC__, letCycle.next === letCycle, true) + eq(__LOC__, letCycle.next.value, 8) + eq(__LOC__, sequenceCycle.next === sequenceCycle, true) + eq(__LOC__, sequenceCycle.next.value, 9) + eq(__LOC__, letRecCycle.next === letRecCycle, true) + eq(__LOC__, letRecCycle.next.value, 12) + let local = localLetRecCycle(13) + eq(__LOC__, local.next === local, true) + eq(__LOC__, local.next.value, 13) + let localPrefix = localPrefixRead(15) + eq(__LOC__, prefixRead.left === leaf, true) + eq(__LOC__, prefixRead.value, 14) + eq(__LOC__, localPrefix.value, 15) + eq(__LOC__, constantPrefixRead, {lower: None, upper: None, weight: 16}) + eq(__LOC__, localConstantPrefixRead(18), {lower: None, upper: None, weight: 17}) + eq(__LOC__, sourceReadsLater.weight, 19) + eq(__LOC__, later.back() === sourceReadsLater, true) + let localLink = localSourceReadsLater(21) + eq(__LOC__, localLink.weight, 21) + eq(__LOC__, localLink.back() === localLink, true) + eq(__LOC__, sourceReadsLaterCopy.optWeight, Some(26)) + eq(__LOC__, laterCopy.optBack() === sourceReadsLaterCopy, true) + eq(__LOC__, laterCopy.optWeight, Some(25)) + let (localCopyLink, localLaterCopy) = localSourceReadsLaterCopy(28) + eq(__LOC__, localCopyLink.optWeight, Some(28)) + eq(__LOC__, localLaterCopy.optBack() === localCopyLink, true) + eq(__LOC__, localLaterCopy.optWeight, Some(25)) + eq(__LOC__, optionalPrefixRead, Some({lower: None, upper: None, weight: 27})) + eq(__LOC__, localOptionalPrefixRead(29), Some({lower: None, upper: None, weight: 30})) + eq( + __LOC__, + nestedOptionalPrefixRead, + Some(Some({nestedLeft: None, nestedRight: None, nestedWeight: 31})), + ) + eq( + __LOC__, + localNestedOptionalPrefixRead(34), + Some(Some({nestedLeft: None, nestedRight: None, nestedWeight: 35})), + ) + eq(__LOC__, nestedSourceReadsLaterCopy.nestedOptWeight, Some(33)) + eq( + __LOC__, + switch nestedLaterCopy { + | Some(Some(copy)) => ( + copy.nestedOptBack() === nestedSourceReadsLaterCopy, + copy.nestedOptWeight, + ) + | _ => (false, None) + }, + (true, Some(32)), + ) + eq(__LOC__, mutualFirst.next->Option.map(next => next === mutualSecond), Some(true)) + eq(__LOC__, mutualSecond.next->Option.map(next => next === mutualFirst), Some(true)) + eq(__LOC__, mutualFirst.back() === mutualSecond, true) + eq(__LOC__, mutualSecond.weight, 23) + eq(__LOC__, isWrapped(wrapped), true) + eq(__LOC__, counter.start, 10) + eq(__LOC__, counter.step(), 11) + eq(__LOC__, fromOtherModule, {x: 5, y: 6}) + }) + + test("a pure source is left out", () => { + eq(__LOC__, overridePure(id({x: 0, y: 0})), {x: 1, y: 2}) + eq(__LOC__, takeCalls(), ["y"]) + ignore(overrideJsxPure(id({Component.a: 0}))) + }) +}) diff --git a/tests/compiler_tests/src/recursive_records_test.mjs b/tests/compiler_tests/src/recursive_records_test.mjs index 758ab04f20..389a4e3743 100644 --- a/tests/compiler_tests/src/recursive_records_test.mjs +++ b/tests/compiler_tests/src/recursive_records_test.mjs @@ -69,6 +69,57 @@ rec_cell3.hd = 3; rec_cell3.tl = rec_cell3; +let first = {}; + +let second = {}; + +Primitive_object.updateDummy(first, { + other: second, + back: () => first +}); + +Primitive_object.updateDummy(second, { + other: undefined, + back: () => first +}); + +function localPair() { + let first = {}; + let second = {}; + Primitive_object.updateDummy(first, { + other: second, + back: () => first + }); + Primitive_object.updateDummy(second, { + other: undefined, + back: () => first + }); + return first; +} + +let holder = {}; + +let held = {}; + +Primitive_object.updateDummy(holder, { + held: held, + size: 1 +}); + +Primitive_object.updateDummy(held, { + holder: () => holder, + weight: 2 +}); + +function pointsBack(pair) { + let other = pair.other; + if (other !== undefined) { + return other.back() === pair; + } else { + return false; + } +} + function f3(x) { let rec_cell3 = {}; Primitive_object.updateDummy(rec_cell3, {hd: (x * x | 0) - 6 | 0, tl: rec_cell3}); @@ -77,18 +128,25 @@ function f3(x) { Mocha.describe("Recursive_records_test", () => { Mocha.test("recursive record operations", () => { - Test_utils.eq("File \"recursive_records_test.res\", line 57, characters 7-14", a0(rec_cell), 9); - Test_utils.eq("File \"recursive_records_test.res\", line 58, characters 7-14", a0(f0(3)), 9); + Test_utils.eq("File \"recursive_records_test.res\", line 85, characters 7-14", a0(rec_cell), 9); + Test_utils.eq("File \"recursive_records_test.res\", line 86, characters 7-14", a0(f0(3)), 9); }); Mocha.test("recursive inline record operations", () => { - Test_utils.eq("File \"recursive_records_test.res\", line 62, characters 7-14", (hd(rec_cell2) + hd(tl_exn(rec_cell2)) | 0) + hd(tl_exn(tl_exn(rec_cell2))) | 0, 9); + Test_utils.eq("File \"recursive_records_test.res\", line 90, characters 7-14", (hd(rec_cell2) + hd(tl_exn(rec_cell2)) | 0) + hd(tl_exn(tl_exn(rec_cell2))) | 0, 9); let rec_cell2$1 = f2(3); - Test_utils.eq("File \"recursive_records_test.res\", line 64, characters 7-14", (hd(rec_cell2$1) + hd(tl_exn(rec_cell2$1)) | 0) + hd(tl_exn(tl_exn(rec_cell2$1))) | 0, 9); + Test_utils.eq("File \"recursive_records_test.res\", line 92, characters 7-14", (hd(rec_cell2$1) + hd(tl_exn(rec_cell2$1)) | 0) + hd(tl_exn(tl_exn(rec_cell2$1))) | 0, 9); + }); + Mocha.test("recursive records reading a record built after them", () => { + Test_utils.eq("File \"recursive_records_test.res\", line 96, characters 7-14", pointsBack(first), true); + Test_utils.eq("File \"recursive_records_test.res\", line 97, characters 7-14", second.back() === first, true); + Test_utils.eq("File \"recursive_records_test.res\", line 98, characters 7-14", pointsBack(localPair()), true); + Test_utils.eq("File \"recursive_records_test.res\", line 99, characters 7-14", held.holder().held === held, true); + Test_utils.eq("File \"recursive_records_test.res\", line 100, characters 7-14", held.holder() === holder, true); }); Mocha.test("recursive variant list operations", () => { - Test_utils.eq("File \"recursive_records_test.res\", line 70, characters 7-14", (Stdlib_List.headOrThrow(rec_cell3) + Stdlib_List.headOrThrow(Stdlib_List.tailOrThrow(rec_cell3)) | 0) + Stdlib_List.headOrThrow(Stdlib_List.tailOrThrow(Stdlib_List.tailOrThrow(rec_cell3))) | 0, 9); + Test_utils.eq("File \"recursive_records_test.res\", line 106, characters 7-14", (Stdlib_List.headOrThrow(rec_cell3) + Stdlib_List.headOrThrow(Stdlib_List.tailOrThrow(rec_cell3)) | 0) + Stdlib_List.headOrThrow(Stdlib_List.tailOrThrow(Stdlib_List.tailOrThrow(rec_cell3))) | 0, 9); let rec_cell3$1 = f3(3); - Test_utils.eq("File \"recursive_records_test.res\", line 72, characters 7-14", (Stdlib_List.headOrThrow(rec_cell3$1) + Stdlib_List.headOrThrow(Stdlib_List.tailOrThrow(rec_cell3$1)) | 0) + Stdlib_List.headOrThrow(Stdlib_List.tailOrThrow(Stdlib_List.tailOrThrow(rec_cell3$1))) | 0, 9); + Test_utils.eq("File \"recursive_records_test.res\", line 108, characters 7-14", (Stdlib_List.headOrThrow(rec_cell3$1) + Stdlib_List.headOrThrow(Stdlib_List.tailOrThrow(rec_cell3$1)) | 0) + Stdlib_List.headOrThrow(Stdlib_List.tailOrThrow(Stdlib_List.tailOrThrow(rec_cell3$1))) | 0, 9); }); }); @@ -101,6 +159,12 @@ export { hd, tl_exn, rec_cell3, + first, + second, + localPair, + holder, + held, + pointsBack, f3, } /* Not a pure module */ diff --git a/tests/compiler_tests/src/recursive_records_test.res b/tests/compiler_tests/src/recursive_records_test.res index 0a3b8cea24..5a62bfc7ed 100644 --- a/tests/compiler_tests/src/recursive_records_test.res +++ b/tests/compiler_tests/src/recursive_records_test.res @@ -47,6 +47,34 @@ let tl_exn = x => let rec rec_cell3 = list{3, ...rec_cell3} /* over variant */ +type rec pair = {other: option, back: unit => pair} + +// A record built into a dummy reads a record of its group built after it, +// which is declared before that read +let rec first = {other: Some(second), back: () => first} +and second = {other: None, back: () => first} + +let localPair = () => { + let rec first = {other: Some(second), back: () => first} + and second = {other: None, back: () => first} + first +} + +type rec holder = {held: held, size: int} +and held = {holder: unit => holder, weight: int} + +// The same holds when the record built after it reads nothing of the group +// while it is built, as its only reference to the group is in a function +// (#9466) +let rec holder = {held, size: 1} +and held = {holder: () => holder, weight: 2} + +let pointsBack = pair => + switch pair.other { + | Some(other) => other.back() === pair + | None => false + } + let f3 = x => { let rec rec_cell3 = list{x * x - 6, ...rec_cell3} /* over variant */ rec_cell3 @@ -64,6 +92,14 @@ describe(__MODULE__, () => { eq(__LOC__, hd(rec_cell2) + hd(tl_exn(rec_cell2)) + hd(tl_exn(tl_exn(rec_cell2))), 9) }) + test("recursive records reading a record built after them", () => { + eq(__LOC__, pointsBack(first), true) + eq(__LOC__, second.back() === first, true) + eq(__LOC__, pointsBack(localPair()), true) + eq(__LOC__, held.holder().held === held, true) + eq(__LOC__, held.holder() === holder, true) + }) + test("recursive variant list operations", () => { let hd = List.headOrThrow let tl = List.tailOrThrow diff --git a/tests/error_tests/single/expected/rec_record_spread_partial_source.res.expected b/tests/error_tests/single/expected/rec_record_spread_partial_source.res.expected new file mode 100644 index 0000000000..fa3b9b9c7f --- /dev/null +++ b/tests/error_tests/single/expected/rec_record_spread_partial_source.res.expected @@ -0,0 +1,10 @@ + + We've found a bug for you! + /.../fixtures/rec_record_spread_partial_source.res:3:17-32 + + 1 │ type point = {x: int, y: int} + 2 │ + 3 │ let rec point = {...point, x: 1} + 4 │ + + This kind of expression is not allowed as right-hand side of `let rec` \ No newline at end of file diff --git a/tests/error_tests/single/expected/rec_record_spread_source.res.expected b/tests/error_tests/single/expected/rec_record_spread_source.res.expected new file mode 100644 index 0000000000..3e237ea8f4 --- /dev/null +++ b/tests/error_tests/single/expected/rec_record_spread_source.res.expected @@ -0,0 +1,21 @@ + + Warning number 23 + /.../fixtures/rec_record_spread_source.res:5:20-52 + + 3 │ @val external wrap: callback => callback = "wrap" + 4 │ + 5 │ let rec callback = {...wrap(callback), run: () => 1} + 6 │ + + All the fields are already explicitly listed in this record, so the `...` spread copies none of them. Its source is still evaluated: if you remove the spread, keep any effect the source has. + + + We've found a bug for you! + /.../fixtures/rec_record_spread_source.res:5:20-52 + + 3 │ @val external wrap: callback => callback = "wrap" + 4 │ + 5 │ let rec callback = {...wrap(callback), run: () => 1} + 6 │ + + This kind of expression is not allowed as right-hand side of `let rec` \ No newline at end of file diff --git a/tests/error_tests/single/expected/warning_23_useless_record_with_call.res.expected b/tests/error_tests/single/expected/warning_23_useless_record_with_call.res.expected new file mode 100644 index 0000000000..15ae479884 --- /dev/null +++ b/tests/error_tests/single/expected/warning_23_useless_record_with_call.res.expected @@ -0,0 +1,11 @@ + + Warning number 23 + /.../fixtures/warning_23_useless_record_with_call.res:4:10-32 + + 2 │ + 3 │ let make = () => {a: 1, b: 2} + 4 │ let r2 = {...make(), a: 3, b: 4} + 5 │ + 6 │ let _ = r2 + + All the fields are already explicitly listed in this record, so the `...` spread copies none of them. Its source is still evaluated: if you remove the spread, keep any effect the source has. \ No newline at end of file diff --git a/tests/error_tests/single/fixtures/rec_record_spread_partial_source.res b/tests/error_tests/single/fixtures/rec_record_spread_partial_source.res new file mode 100644 index 0000000000..abb4addc9c --- /dev/null +++ b/tests/error_tests/single/fixtures/rec_record_spread_partial_source.res @@ -0,0 +1,3 @@ +type point = {x: int, y: int} + +let rec point = {...point, x: 1} diff --git a/tests/error_tests/single/fixtures/rec_record_spread_source.res b/tests/error_tests/single/fixtures/rec_record_spread_source.res new file mode 100644 index 0000000000..720f6795c4 --- /dev/null +++ b/tests/error_tests/single/fixtures/rec_record_spread_source.res @@ -0,0 +1,5 @@ +type callback = {run: unit => int} + +@val external wrap: callback => callback = "wrap" + +let rec callback = {...wrap(callback), run: () => 1} diff --git a/tests/error_tests/single/fixtures/warning_23_useless_record_with_call.res b/tests/error_tests/single/fixtures/warning_23_useless_record_with_call.res new file mode 100644 index 0000000000..7518280396 --- /dev/null +++ b/tests/error_tests/single/fixtures/warning_23_useless_record_with_call.res @@ -0,0 +1,6 @@ +type t = {a: int, b: int} + +let make = () => {a: 1, b: 2} +let r2 = {...make(), a: 3, b: 4} + +let _ = r2