Skip to content

Commit 32116b5

Browse files
authored
Evaluate optional @obj arguments in source order and read properties once (#9283)
Why: An `@obj` external builds its object as a literal and assigns an optional argument whose presence is not known after it, under `if (tmp !== undefined)`. So that argument was evaluated after the arguments that follow it: `make(~size=?size(), ~mode=mode(), ())` called `mode()` first, and a later argument with side effects could change what the optional argument read, such as a `@get` getter, a `@val` global, `Dict.get`, an array element, a mutable field or a ref. `hold_obj_args` now binds such an argument to a temporary after its statements, unless evaluating it after the literal gives the same values and effects. As with the temporaries of #9217, `sequence_arguments` then evaluates the arguments to the left of the temporary before it, with `evaluate_now`. That bound an optional argument known to be present as a whole, so that it lost its presence and was assigned after the literal too, and it bound variables and fields of records although defining a temporary as such a value cannot change them. `evaluate_now` now evaluates the value in an `Optional_block` and keeps the block, and `sequence_arguments` leaves an argument that runs no code, a variable, a constant or a field of a record, in place when the statements after it only define variables as such values. A JS property read may run a getter, so it does not count. An optional argument that is a JS property read, as from a `@get` external or a `@val` name with a dot, was read twice, to test it for `None` and to unwrap it, by a call, a JSX key and an `@obj` external alike. A getter ran twice, and one that returned a value and then `undefined` made the call throw a `TypeError`. Such an argument is now read once: a call and a JSX key give it to `Primitive_option.valFromOption`, which returns `undefined` for `None` since the previous commit, and an `@obj` external binds it. `Js_analyzer.is_okay_to_duplicate ~property_reads:false` tells these arguments apart. JS modified (optional argument with side effects): Example: @obj external make: (~size: int=?, ~mode: string, unit) => {..} = "" let o = (size, mode) => make(~size=?size(), ~mode=mode(), ()) Before (js): function o(size, mode) { let tmp = { mode: mode() }; let tmp$1 = size(); if (tmp$1 !== undefined) { tmp.size = tmp$1; } return tmp; } After (js): function o(size, mode) { let tmp = size(); let tmp$1 = { mode: mode() }; if (tmp !== undefined) { tmp$1.size = tmp; } return tmp$1; } JS modified (optional argument that a later argument changes): Example: type source @get external name: source => option<string> = "name" @obj external makeName: (~name: string=?, ~mode: string, unit) => {..} = "" let n = (s, rename) => makeName(~name=?name(s), ~mode=rename(s), ()) Before (js): function n(s, rename) { let tmp = { mode: rename(s) }; if (s.name !== undefined) { tmp.name = s.name; } return tmp; } After (js): function n(s, rename) { let tmp = s.name; let tmp$1 = { mode: rename(s) }; if (tmp !== undefined) { tmp$1.name = tmp; } return tmp$1; } JS modified (arguments before a bound optional argument): Example: type props = {color: string, width?: string} @obj external style: (~color: string=?, ~icon: string=?, ~width: string=?, ~height: string, unit) => {..} = "" let a = (props, height) => style(~color=props.color, ~width=?props.width, ~height=height(), ()) let b = (icon, width, height) => style(~icon=icon(), ~width=?width(), ~height=height(), ()) Before (js): function a(props, height) { let tmp = { color: props.color, height: height() }; if (props.width !== undefined) { tmp.width = props.width; } return tmp; } function b(icon, width, height) { let tmp = { icon: icon(), height: height() }; let tmp$1 = width(); if (tmp$1 !== undefined) { tmp.width = tmp$1; } return tmp; } After (js): function a(props, height) { let tmp = props.width; let tmp$1 = { color: props.color, height: height() }; if (tmp !== undefined) { tmp$1.width = tmp; } return tmp$1; } function b(icon, width, height) { let tmp = icon(); let tmp$1 = width(); let tmp$2 = { icon: tmp, height: height() }; if (tmp$1 !== undefined) { tmp$2.width = tmp$1; } return tmp$2; } JS modified (optional argument known to be present before a temporary): Example: type item = {id: int} @obj external mk: (~item: item=?, ~level: @int [#low | @as(10) #high], unit) => {..} = "" let k = async (f, p) => mk(~item=f(), ~level=await p, ()) Before (js): async function k(f, p) { let tmp = f(); let tmp$1 = await p; let tmp$2 = { level: (() => { switch (tmp$1) { … } })() }; if (tmp !== undefined) { tmp$2.item = Primitive_option.valFromOption(tmp); } return tmp$2; } After (js): async function k(f, p) { let tmp = f(); let tmp$1 = await p; return { item: tmp, level: (() => { switch (tmp$1) { … } })() }; } JS modified (optional property read): Example: type source @get external name: source => option<string> = "name" @Val external greet: (~name: string=?, unit) => string = "greet" @Val external userName: option<string> = "window.userName" @obj external makeName: (~name: string=?, ~mode: string, unit) => {..} = "" let g = s => greet(~name=?name(s), ()) let u = () => greet(~name=?userName, ()) let m = (o: {"name": option<string>}) => makeName(~name=?o["name"], ~mode="dark", ()) Before (js): function g(s) { return greet(s.name !== undefined ? Primitive_option.valFromOption(s.name) : undefined); } function u() { return greet(window.userName !== undefined ? Primitive_option.valFromOption(window.userName) : undefined); } function m(o) { let tmp = { mode: "dark" }; if (o.name !== undefined) { tmp.name = o.name; } return tmp; } After (js): function g(s) { return greet(Primitive_option.valFromOption(s.name)); } function u() { return greet(Primitive_option.valFromOption(window.userName)); } function m(o) { let tmp = { mode: "dark" }; let tmp$1 = o.name; if (tmp$1 !== undefined) { tmp.name = tmp$1; } return tmp; } JS modified (temporaries for optional arguments of an @obj external): Before (representation): Lam_compile_external_obj.hold_obj_args ~x=?f(), ~m=g() ↦ after the literal ~x=?p.x, ~m=g() ↦ after the literal ~x=?f(), ~m=p.m ↦ after the literal ~x=?f(), g() ↦ after the literal ~x=?p.x, ~m=p.m ↦ after the literal ~x=?f(), ~m="dark" ↦ after the literal ~x=?v, ~m=g() ↦ after the literal ~x=?f(), ~y=?g() ↦ after the literal note: p.x stands for a field, a global or a lookup, and v for an immutable variable After (representation): ~x=?f(), ~m=g() ↦ temporary ~x=?p.x, ~m=g() ↦ temporary ~x=?f(), ~m=p.m ↦ temporary ~x=?f(), g() ↦ temporary ~x=?p.x, ~m=p.m ↦ after the literal ~x=?f(), ~m="dark" ↦ after the literal ~x=?v, ~m=g() ↦ after the literal ~x=?f(), ~y=?g() ↦ after the literal note: p.x stands for a field, a global or a lookup, and v for an immutable variable JS modified (arguments before a statement): Before (representation): Lam_compile.sequence_arguments r.c, then let tmp = r.x ↦ temporary r.c, then let tmp = s.x ↦ temporary s.c, then let tmp = r.x ↦ temporary f(), then let tmp = r.x ↦ temporary r.c, then let tmp = g() ↦ temporary ~c=f(), then a statement ↦ temporary for the option note: r.c is a variable or a field of a record, s.x a JS property read, and ~c=f() an optional argument known to be present After (representation): r.c, then let tmp = r.x ↦ in place r.c, then let tmp = s.x ↦ temporary s.c, then let tmp = r.x ↦ temporary f(), then let tmp = r.x ↦ temporary r.c, then let tmp = g() ↦ temporary ~c=f(), then a statement ↦ temporary for f(), option in place note: r.c is a variable or a field of a record, s.x a JS property read, and ~c=f() an optional argument known to be present JS modified (optional arguments read twice): Before (representation): Js_analyzer.is_okay_to_duplicate x, M.x, globalName ↦ test, then unwrap r.field ↦ test, then unwrap s.prop, o["prop"], window.x ↦ test, then unwrap f(), a[i], c ? x : y ↦ unwrap once After (representation): Js_analyzer.is_okay_to_duplicate ~property_reads:false x, M.x, globalName ↦ test, then unwrap r.field ↦ test, then unwrap s.prop, o["prop"], window.x ↦ unwrap once f(), a[i], c ? x : y ↦ unwrap once note: r.field is a field of a record, s.prop a JS property read, such as a `@get` getter, and window.x a `@val` name with a dot Review: Which calls keep their output? An `@obj` call in which nothing that the literal evaluates after the optional argument can change it or be changed by it: constants, immutable variables and functions, reads without side effects when the optional argument has none either, as in `make(~x=?p.x, ~m=p.m, ())`, and other optional arguments whose presence is not known, which are assigned after it, in order. Variables and fields of records are still tested and unwrapped in place. No checked-in output changes besides the new tests. Review: Which arguments get a temporary they do not need? A later argument is taken to change an optional one unless it is `delay_safe` or neither has side effects, and the JS IR does not say whether a field is mutable or a call pure. So `make(~a=?props.a, ~b=Int.toString(n), ())` binds `props.a`, as `a` above binds `props.width`. A field of a JS object type, `o["x"]`, cannot be told from a getter, so an `@obj` external binds it even when no later argument can change it, as `m` above, while a call no longer tests it inline. Review: Why in `hold_obj_args` and not in `hold_arg`? Whether the argument has to be bound depends on the arguments after it, which `hold_arg` does not see, and only an object-creating external evaluates an argument after the ones that follow it. The binding does not depend on the type of the argument, so an optional polymorphic variant argument keeps its place whether or not `hold_arg` binds a later argument. Review: Why is `delay_safe` passed to `hold_obj_args`? It is `Lam_compile.delay_safe`, which needs the variables the function assigns, and `Lam_compile` depends on this module. Review: Why change `evaluate_now` and `sequence_arguments` here? Before this commit only the temporaries of #9217 for polymorphic variant arguments made `sequence_arguments` bind the arguments to their left, as in `k` above, where `item` lost its place in `Object.keys`. Binding optional arguments of any type would make that common: without the two changes, `b` above would assign `icon` after the literal as well, and `a` would bind `props.color`. Both functions are in `lam_compile.ml`, which #9231 does not change. Review: Why a flag on `is_okay_to_duplicate` and not another predicate? The two differ only in property reads, and its other callers, `min` and `max` of booleans and the object of a `Pjs_object_get`, keep the default. `Js_ast_util.named_expression` takes the same flag, which `assemble_obj_args` passes. Review: Is a `@val` global still read twice? Yes, a plain one is, like a value of a JS module: only a property read is taken to run a getter, as a `@get` external is there to do. A `@val` name with a dot and a global with `@scope` compile to a property read and are read once. Review: What still runs out of order? The side effects of a `unit` or `@ignore` argument are put before the literal or the call, so `mk(~a=f(), g())` calls `g()` first, as before. A getter is taken to have no side effects, so `make(~name=?name(s), ~count=count(s), ())` with two `@get` externals still reads `count` first. Signed-off-by: mununki <woonki.moon@gmail.com>
1 parent 0178eb0 commit 32116b5

11 files changed

Lines changed: 914 additions & 28 deletions
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
- Evaluate an optional `@obj` argument such as `~x=?f()` in source order.
2+
- Read an optional external argument that is a JS property, such as a `@get` getter, only once.

‎compiler/core/js_analyzer.ml‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -365,8 +365,13 @@ let rev_toplevel_flatten block =
365365
is_constant a && is_constant b
366366
| _ -> false *)
367367

368-
let rec is_okay_to_duplicate (e : J.expression) =
368+
let rec is_okay_to_duplicate ?(property_reads = true) (e : J.expression) =
369369
match e.expression_desc with
370+
| Var (Id id)
371+
when (not property_reads) && Ext_ident.is_js id
372+
&& String.contains id.name '.' ->
373+
false
370374
| Var _ | Bool _ | Str _ | Template_literal _ | Number _ -> true
371-
| Static_index (e, _s, _off) -> is_okay_to_duplicate e
375+
| Static_index (e, _s, off) ->
376+
(property_reads || off <> None) && is_okay_to_duplicate ~property_reads e
372377
| _ -> false

‎compiler/core/js_analyzer.mli‎

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -70,8 +70,9 @@ val rev_toplevel_flatten : J.block -> J.block
7070

7171
(* val is_constant : J.expression -> bool *)
7272

73-
(** Simple expression,
74-
no computation involved so that it is okay to be duplicated
75-
*)
76-
77-
val is_okay_to_duplicate : J.expression -> bool
73+
val is_okay_to_duplicate : ?property_reads:bool -> J.expression -> bool
74+
(** Simple expression, no computation involved so that it is okay to be
75+
duplicated. With [~property_reads:false], reading it twice also gives the
76+
same value twice: it reads no JS property, which may run a getter each
77+
time, as one from a [@get] external or a [@val] name with a dot does.
78+
Fields of records count. *)

‎compiler/core/js_ast_util.ml‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -26,8 +26,9 @@
2626

2727
module S = Js_stmt_make
2828

29-
let named_expression (e : J.expression) : (J.statement * Ident.t) option =
30-
if Js_analyzer.is_okay_to_duplicate e then None
29+
let named_expression ?property_reads (e : J.expression) :
30+
(J.statement * Ident.t) option =
31+
if Js_analyzer.is_okay_to_duplicate ?property_reads e then None
3132
else
3233
let obj = Ext_ident.create_tmp () in
3334
let obj_code = S.define_variable ~kind:Strict obj e in

‎compiler/core/js_ast_util.mli‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,4 +22,7 @@
2222
* along with this program; if not, write to the Free Software
2323
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *)
2424

25-
val named_expression : J.expression -> (J.statement * Ident.t) option
25+
val named_expression :
26+
?property_reads:bool -> J.expression -> (J.statement * Ident.t) option
27+
(** A temporary bound to the expression, unless
28+
{!Js_analyzer.is_okay_to_duplicate} holds for it *)

‎compiler/core/js_of_lam_option.ml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,7 @@ let get_default_undefined_from_optional (arg : J.expression) : J.expression =
7474
match desc with
7575
| Optional_block (x, _) -> x (* invariant: option encoding *)
7676
| _ ->
77-
if Js_analyzer.is_okay_to_duplicate arg then
77+
if Js_analyzer.is_okay_to_duplicate ~property_reads:false arg then
7878
(* FIXME: no need do such inlining*)
7979
E.econd (is_not_none arg) (val_from_option arg) E.undefined
8080
else

‎compiler/core/lam_compile.ml‎

Lines changed: 29 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -282,7 +282,8 @@ let rec delay_safe ~assignable (e : J.expression) =
282282
Building an array, block or object literal is pure, so a literal stays in
283283
place and its elements are evaluated now instead. That also keeps the
284284
literal visible to translations that look into their arguments, such as
285-
the rows of a dict literal or a [@variadic] array. *)
285+
the rows of a dict literal or a [@variadic] array. So does an
286+
[Optional_block], which keeps an optional argument known to be present. *)
286287
let rec evaluate_now ~assignable (e : J.expression) : J.block * J.expression =
287288
match e.expression_desc with
288289
| _ when delay_safe ~assignable e -> ([], e)
@@ -291,6 +292,9 @@ let rec evaluate_now ~assignable (e : J.expression) : J.block * J.expression =
291292
if Js_analyzer.no_side_effect_expression a then (rest, b)
292293
else
293294
({J.statement_desc = Exp a; comment = None; source_loc = None} :: rest, b)
295+
| Optional_block (a, identity) ->
296+
let held, a = evaluate_now ~assignable a in
297+
(held, {e with expression_desc = Optional_block (a, identity)})
294298
| Array xs ->
295299
let held, xs = evaluate_all_now ~assignable xs in
296300
(held, {e with expression_desc = Array xs})
@@ -327,12 +331,29 @@ and evaluate_all_now ~assignable (xs : J.expression list) :
327331
let blocks, xs = Ext_list.split_map xs (evaluate_now ~assignable) in
328332
(List.concat blocks, xs)
329333

334+
(* Whether evaluating [e] runs no code: it has no side effects and reads no JS
335+
property, which may run a getter. A record field counts. *)
336+
let runs_no_code (e : J.expression) =
337+
Js_analyzer.is_okay_to_duplicate ~property_reads:false e
338+
339+
(* Whether [block] only defines variables as values that run no code, as a
340+
temporary bound to a record field does *)
341+
let defines_pure_values (block : J.block) =
342+
Ext_list.for_all block (fun (s : J.statement) ->
343+
match s.statement_desc with
344+
| Variable {value = None} -> true
345+
| Variable {value = Some e} -> runs_no_code e
346+
| _ -> false)
347+
330348
(* Assembles compiled arguments for a call or a literal that evaluates them
331349
left to right. Each argument comes with the statements that have to run
332350
before its value is read. Putting all statements first and then the
333351
values would move the statements of an argument in front of the values of
334352
the arguments to its left, so when an argument has statements, every
335-
argument to its left is evaluated before them with [evaluate_now].
353+
argument to its left is evaluated before them with [evaluate_now]. An
354+
argument that runs no code stays in place when the statements after it
355+
only define values that run none either, since then neither can change
356+
the other.
336357
337358
With [~method_callee:true], the first argument is a JS method read
338359
[obj.m] being called: the object is held and the property read stays in
@@ -351,7 +372,8 @@ let sequence_arguments ?(method_callee = false) ~assignable
351372
Ext_list.fold_right args (last, [], [])
352373
(fun (block, value) (i, code, values) ->
353374
let held, value =
354-
if code = [] then ([], value)
375+
if code = [] || (runs_no_code value && defines_pure_values code)
376+
then ([], value)
355377
else
356378
match value.expression_desc with
357379
| Static_index (obj, name, pos) when method_callee && i = 0 ->
@@ -1908,7 +1930,10 @@ let compile output_prefix =
19081930
| {primitive = Pjs_object_create labels; args} ->
19091931
let args_code, args_expr =
19101932
compile_arguments
1911-
~hold:(Lam_compile_external_obj.hold_obj_args labels)
1933+
~hold:
1934+
(Lam_compile_external_obj.hold_obj_args
1935+
~delay_safe:(delay_safe ~assignable:lambda_cxt.meta.assignable)
1936+
labels)
19121937
lambda_cxt args
19131938
in
19141939
let block, exp =

‎compiler/core/lam_compile_external_obj.ml‎

Lines changed: 60 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -36,24 +36,72 @@ module S = Js_stmt_make
3636
But the default to be undefined seems reasonable
3737
*)
3838

39+
(* Whether [assemble_obj_args] assigns the optional argument [arg] after the
40+
object literal, since its presence is not known *)
41+
let presence_unknown (arg : J.expression) =
42+
Js_of_lam_option.destruct_optional arg ~for_sure_none:false
43+
~for_sure_some:(fun _ -> false)
44+
~not_sure:(fun () -> true)
45+
46+
(* The arguments that [assemble_obj_args] evaluates in the object literal or
47+
before it, which are all but the optional ones whose presence is not
48+
known *)
49+
let rec literal_args (labels : External_arg_spec.obj_params)
50+
(args : (J.block * J.expression) list) =
51+
match (labels, args) with
52+
| {obj_arg_label = Obj_label _; obj_arg_type = Arg_cst _} :: labels, args ->
53+
literal_args labels args
54+
| {obj_arg_label = Obj_optional _} :: labels, (_, arg) :: args
55+
when presence_unknown arg ->
56+
literal_args labels args
57+
| ( {obj_arg_label = Obj_empty | Obj_label _ | Obj_optional _} :: labels,
58+
(_, arg) :: args ) ->
59+
arg :: literal_args labels args
60+
| [], [] -> []
61+
| [], _ :: _ | _ :: _, [] -> assert false
62+
3963
(* [Lam_compile_external_call.hold_arg] for the compiled arguments of an
4064
object-creating external, which pair with the labels as in
41-
[assemble_obj_args] *)
42-
let rec hold_obj_args (labels : External_arg_spec.obj_params)
65+
[assemble_obj_args]. That function assigns an optional argument whose
66+
presence is not known after the object literal, so it evaluates the
67+
argument after the arguments that follow it. Unless that gives the same
68+
values and effects, the argument is bound to a temporary after its
69+
statements, which keeps it in its place. It does when the argument is
70+
[delay_safe], and when each argument that the literal evaluates after it
71+
is [delay_safe] or neither of the two has side effects. *)
72+
let rec hold_obj_args ~(delay_safe : J.expression -> bool)
73+
(labels : External_arg_spec.obj_params)
4374
(args : (J.block * J.expression) list) =
4475
match (labels, args) with
4576
| {obj_arg_label = Obj_label _; obj_arg_type = Arg_cst _} :: labels, args ->
46-
hold_obj_args labels args
77+
hold_obj_args ~delay_safe labels args
4778
| {obj_arg_label = Obj_empty} :: labels, arg :: args ->
48-
arg :: hold_obj_args labels args
79+
arg :: hold_obj_args ~delay_safe labels args
4980
| {obj_arg_label = Obj_label _; obj_arg_type} :: labels, arg :: args ->
5081
Lam_compile_external_call.hold_arg ~arg_label:Arg_label
5182
~arg_type:obj_arg_type arg
52-
:: hold_obj_args labels args
83+
:: hold_obj_args ~delay_safe labels args
5384
| {obj_arg_label = Obj_optional _; obj_arg_type} :: labels, arg :: args ->
54-
Lam_compile_external_call.hold_arg ~arg_label:Arg_optional
55-
~arg_type:obj_arg_type arg
56-
:: hold_obj_args labels args
85+
let ((block, value) as held) =
86+
Lam_compile_external_call.hold_arg ~arg_label:Arg_optional
87+
~arg_type:obj_arg_type arg
88+
in
89+
let order_matters (later : J.expression) =
90+
not
91+
(delay_safe later
92+
|| Js_analyzer.no_side_effect_expression value
93+
&& Js_analyzer.no_side_effect_expression later)
94+
in
95+
(if
96+
presence_unknown value
97+
&& (not (delay_safe value))
98+
&& List.exists order_matters (literal_args labels args)
99+
then
100+
let tmp = Ext_ident.create_tmp () in
101+
( Ext_list.append_one block (S.define_variable ~kind:Strict tmp value),
102+
E.var tmp )
103+
else held)
104+
:: hold_obj_args ~delay_safe labels args
57105
| [], [] -> []
58106
| [], _ :: _ | _ :: _, [] -> assert false
59107

@@ -130,10 +178,10 @@ let assemble_obj_args (labels : External_arg_spec.obj_params)
130178
obj_arg_label =
131179
Obj_optional {name = label; for_sure_no_nested_option};
132180
} -> (
133-
(* Need make sure whether assignment is effectful or not
134-
to avoid code duplication
135-
*)
136-
match Js_ast_util.named_expression arg with
181+
(* [arg] is read for its presence and for its value, so it is
182+
bound to a temporary unless reading it twice gives the
183+
same value twice *)
184+
match Js_ast_util.named_expression ~property_reads:false arg with
137185
| None -> (
138186
let acc, new_eff =
139187
Lam_compile_external_call.ocaml_to_js_eff

‎compiler/core/lam_compile_external_obj.mli‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,11 +26,16 @@
2626
object literal. *)
2727

2828
val hold_obj_args :
29+
delay_safe:(J.expression -> bool) ->
2930
External_arg_spec.obj_params ->
3031
(J.block * J.expression) list ->
3132
(J.block * J.expression) list
3233
(** {!Lam_compile_external_call.hold_arg} for the compiled arguments of an
33-
object-creating external *)
34+
object-creating external. An optional argument whose presence is not
35+
known is also bound to a temporary when evaluating it after the object
36+
literal, as {!assemble_obj_args} does, could change a value or the order
37+
of effects. [delay_safe] tells whether evaluating an argument after other
38+
code gives the same value and effects. *)
3439

3540
val assemble_obj_args :
3641
External_arg_spec.obj_params -> J.expression list -> J.block * J.expression

0 commit comments

Comments
 (0)