Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
14 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changes/let-rec-record-after-effects.fix.md
Original file line number Diff line number Diff line change
@@ -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).
1 change: 1 addition & 0 deletions changes/rec-record-spread-source-check.breaking.md
Original file line number Diff line number Diff line change
@@ -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.
1 change: 1 addition & 0 deletions changes/record-spread-source-effect.fix.md
Original file line number Diff line number Diff line change
@@ -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.
174 changes: 156 additions & 18 deletions compiler/backend/lam_compile.ml
Original file line number Diff line number Diff line change
Expand Up @@ -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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Look through non-nesting options when locating record tails

For type rec node = {left: option<node>, right: option<node>, value: int} and an effectful tick, the accepted initializer let rec n = Some({...{let rec tmp = {left: Some(tmp), right: n, value: tick()}; tmp}, left: None, right: None, value: 1}) has an outer Psome_not_nest. This fallback therefore hides both the terminal record and its eager prefix read from tail_block; compile_recursive_let declares n normally, and constructing tmp reads it before initialization, throwing ReferenceError. Previously the fully overridden spread source was dropped, leaving a constant initializer without that read. Traverse the allocation-free option wrapper when locating the block, and cover this with and without optimization.

AGENTS.md reference: compiler/AGENTS.md:L160-L160

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Real. Wrapping the recursive record in a non-nesting Some(...) produced an outer Psome_not_nest, so tail_block returned None and declared n after tmp read it, throwing ReferenceError: Cannot access 'n' before initialization.

Fixed in 5d51c88: tail_block now traverses Psome_not_nest wrappers when locating the terminal block and its prefix reads, so n is declared as a dummy before tmp is constructed and filled via updateDummy. Regression tests: optionalPrefixRead (module level) and localOptionalPrefixRead (local to a function) in record_spread_source_effect_test.res.

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) ->
Expand Down Expand Up @@ -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 =
Expand All @@ -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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve own proto fields when backpatching spread records

For type rec node = {next: option<node>, self: unit => node, @as("__proto__") proto: int}, consider a fully overridden source {let rec s = {next: Some(n), self: () => s, proto: tick()}; s} with final overrides next: None, self: () => n, proto: 1. The source's eager read now sends n through this dummy path, whereas previously its function/constant-only final block was declared directly. compile_into_dummy uses Primitive_object.updateDummy, implemented with Object.assign, which invokes the inherited __proto__ setter instead of creating an own property. The resulting record therefore loses the numeric field, and reading n.proto no longer returns 1; the previous direct object literal preserved it. Use own-property-safe backpatching and add optimized and unoptimized regression coverage.

AGENTS.md reference: compiler/AGENTS.md:L160-L160

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This case is no longer reachable on master: #9513 (fe8c75b189) made __proto__ a compile-time error as the JavaScript name of a record/object field or @tag, and removed Js_exp_make.define_own_property.

| 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
Comment on lines +944 to +945

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Allocate a dummy for forward-read record copies

When a later recursive binding partially spreads a record with optional fields, transl_record emits a Pduprecord binding ending in Lvar copy_id, not a terminal block. For example, in the new sourceReadsLater scenario, make link.weight optional and use later = {...base, back: () => sourceReadsLater} with an existing base: link. read_before_built correctly marks later, but tail_block returns None, so this fallback still declares it after the earlier source has read it, causing a module-load ReferenceError. Previously the fully overridden source was discarded, so that read did not happen. Support dummy allocation for copied-record results too, and cover this with and without Lambda optimization.

AGENTS.md reference: compiler/AGENTS.md:L160-L160

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Real. When a later binding in a let rec group partially spreads a record with optional fields (later = {...base, back: () => sourceReadsLater}), transl_record emits Llet (copy_id, Pduprecord, ...) ending in Lvar copy_id. tail_block returned None, so later was still declared after sourceReadsLater's spread source read it, throwing ReferenceError: Cannot access 'later' before initialization.

Fixed in 5d51c88 (after rebasing onto master): tail_block now tracks Pduprecord bindings (and aliases of them) through their Psetfield sequences to the terminal Lvar, treating the copy as an object block so compile_recursive_lets_aux allocates let later = {}; up front and fills it with Primitive_object.updateDummy(later, {...base, ...}). Regression tests: sourceReadsLaterCopy (module level) and localSourceReadsLaterCopy (local to a function) in record_spread_source_effect_test.res.

in
(Js_output.append_output code acc, List.append declare_ids ids))
id_args (Js_output.dummy, [])
Expand Down
11 changes: 9 additions & 2 deletions compiler/typing/rec_check.ml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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 _ -> ()
Expand Down
34 changes: 20 additions & 14 deletions compiler/typing/translcore.ml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -1100,15 +1090,18 @@ 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
(fields : (label_description * Longident.t loc * expression) array)
~(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
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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 *)
Expand Down
23 changes: 11 additions & 12 deletions compiler/typing/typecore.ml
Original file line number Diff line number Diff line change
Expand Up @@ -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 *)
Expand Down Expand Up @@ -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 =
Expand Down
12 changes: 12 additions & 0 deletions compiler/typing/typedtree.ml
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Loading
Loading