Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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/argument-evaluation-order.fix.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
- Evaluate arguments and literal elements left to right when a later one is a block that compiles to statements, which could produce wrong values.
236 changes: 173 additions & 63 deletions compiler/core/lam_compile.ml
Original file line number Diff line number Diff line change
Expand Up @@ -238,6 +238,135 @@ let functions_before_values (group : (Ident.t * Lambda.t) list) =
| _, _ -> 0)
group

(* Whether evaluating [e] later, after other code, gives the same value and
the same effects as evaluating it now: constants, functions, immutable
local variables and pure operations on them. [assignable] are the local
variables some [Lassign] assigns; the other code, or a closure it calls,
may assign them. JS globals ([@val]) and reads of the heap (fields, array
elements, lengths) may change as well. *)
let rec delay_safe ~assignable (e : J.expression) =
match e.expression_desc with
| Undefined _ | Null | Bool _ | Number _ | Str _ | Template_literal _
| Json_literal _ | Fun _
| Var (Qualified _) ->
true
| Var (Id id) ->
(not (Ext_ident.is_js id)) && not (Set_ident.mem id assignable)
| Bin (Eq, _, _) -> false
| Bin (_, a, b) ->
Js_analyzer.no_side_effect_expression e
&& delay_safe ~assignable a && delay_safe ~assignable b
| String_append (a, b) -> delay_safe ~assignable a && delay_safe ~assignable b
| Js_not a
| Js_bnot a
| Typeof a
| Is_null_or_undefined a
| Optional_block (a, _) ->
delay_safe ~assignable a
| Cond (a, b, c) ->
delay_safe ~assignable a && delay_safe ~assignable b
&& delay_safe ~assignable c
| Interpolated_template {values} ->
Ext_list.for_all values (delay_safe ~assignable)
| Array xs | Caml_block (xs, _, _) ->
Ext_list.for_all xs (delay_safe ~assignable)
| Object entries ->
Ext_list.for_all entries (function
| J.Object_property (_, v) -> delay_safe ~assignable v
| Record_spread _ | Object_spread _ -> false)
| _ -> false

(* Statements that evaluate [e] now, and the expression that stands for its
value afterwards. A sequence's leading expressions become statements of
their own, and the last one gets a temporary unless it is [delay_safe].
Building an array, block or object literal is pure, so a literal stays in
place and its elements are evaluated now instead. That also keeps the
literal visible to translations that look into their arguments, such as
the rows of a dict literal or a [@variadic] array. *)
let rec evaluate_now ~assignable (e : J.expression) : J.block * J.expression =
match e.expression_desc with
| _ when delay_safe ~assignable e -> ([], e)
| Seq (a, b) ->
let rest, b = evaluate_now ~assignable b in
if Js_analyzer.no_side_effect_expression a then (rest, b)
else
({J.statement_desc = Exp a; comment = None; source_loc = None} :: rest, b)
| Array xs ->
let held, xs = evaluate_all_now ~assignable xs in
(held, {e with expression_desc = Array xs})
| Caml_block (xs, mutable_flag, tag) ->
let held, xs = evaluate_all_now ~assignable xs in
(held, {e with expression_desc = Caml_block (xs, mutable_flag, tag)})
| Object entries
when Ext_list.for_all entries (function
| J.Object_property _ -> true
| Record_spread _ | Object_spread _ -> false) ->
let held, values =
evaluate_all_now ~assignable
(Ext_list.filter_map entries (function
| J.Object_property (_, v) -> Some v
| Record_spread _ | Object_spread _ -> None))
in
let entries =
List.map2
(fun entry v ->
match entry with
| J.Object_property (k, _) -> J.Object_property (k, v)
| Record_spread _ | Object_spread _ -> assert false)
entries values
in
(held, {e with expression_desc = Object entries})
| _ ->
let tmp = Ext_ident.create_tmp () in
([S.define_variable ~kind:Strict tmp e], E.var tmp)

(* [evaluate_now] on each of [xs], left to right. The elements left in place
are [delay_safe], so no other element's statements can change them. *)
and evaluate_all_now ~assignable (xs : J.expression list) :
J.block * J.expression list =
let blocks, xs = Ext_list.split_map xs (evaluate_now ~assignable) in
(List.concat blocks, xs)

(* Assembles compiled arguments for a call or a literal that evaluates them
left to right. Each argument comes with the statements that have to run
before its value is read. Putting all statements first and then the
values would move the statements of an argument in front of the values of
the arguments to its left, so when an argument has statements, every
argument to its left is evaluated before them with [evaluate_now].

With [~method_callee:true], the first argument is a JS method read
[obj.m] being called: the object is held and the property read stays in
the call, so the call still passes the object as [this]. *)
let sequence_arguments ?(method_callee = false) ~assignable
(args : (J.block * J.expression) list) : J.block * J.expression list =
let later_statements =
match args with
| [] -> false
| _ :: rest -> Ext_list.exists_fst rest (fun block -> block <> [])
in
if not later_statements then (List.concat_map fst args, Ext_list.map args snd)
else
let last = List.length args - 1 in
let _, code, values =
Ext_list.fold_right args (last, [], [])
(fun (block, value) (i, code, values) ->
let held, value =
if code = [] then ([], value)
else
match value.expression_desc with
| Static_index (obj, name, pos) when method_callee && i = 0 ->
let held, obj = evaluate_now ~assignable obj in
( held,
{value with expression_desc = Static_index (obj, name, pos)}
)
| _ -> evaluate_now ~assignable value
in
( i - 1,
Ext_list.append block (Ext_list.append held code),
value :: values ))
in
(code, values)

let compile output_prefix =
(* When compiling a read from another module, a nested source path like
Other.A.B.make reaches this point as nested module-field reads:
Expand Down Expand Up @@ -320,21 +449,23 @@ let compile output_prefix =
let _, param_map =
Lam_closure.is_closed_with_map Set_ident.empty params body
in
compile_lambda lambda_cxt
(Lam_beta_reduce.propagate_beta_reduce_with_map lambda_cxt.meta
param_map params body ap_args)
| _ ->
let args_code, args =
let dummy = ([], []) in
if ap_args = [] then dummy
else
let arg_cxt = {lambda_cxt with continuation = NeedValue Not_tail} in
Ext_list.fold_right ap_args dummy (fun arg_lambda (args_code, args) ->
match compile_lambda arg_cxt arg_lambda with
| {block; value = Some b} ->
(Ext_list.append block args_code, b :: args)
| _ -> assert false)
let inlined =
Lam_beta_reduce.propagate_beta_reduce_with_map lambda_cxt.meta param_map
params body ap_args
in
(* The inlined body comes from another module, so the variables it
assigns are not in [meta.assignable] yet. *)
let meta =
{
lambda_cxt.meta with
assignable =
Set_ident.union lambda_cxt.meta.assignable
(Lambda_traverse.assigned_variables inlined);
}
in
compile_lambda {lambda_cxt with meta} inlined
| _ ->
let args_code, args = compile_arguments lambda_cxt ap_args in

let fn = E.ml_var_dot module_id ident_info.name in
let expression =
Expand Down Expand Up @@ -1256,7 +1387,7 @@ let compile output_prefix =
match (b1, b2) with
| _, [] -> Ext_list.append_one b1 (make_for (Some e1))
| _, _
when Js_analyzer.no_side_effect_expression e1
when delay_safe ~assignable:lambda_cxt.meta.assignable e1
(*
e1 > b2 > e2
re-order
Expand Down Expand Up @@ -1563,15 +1694,15 @@ let compile output_prefix =
2. no need create names
*)
let ap_func = appinfo.ap_func in
let new_cxt = {lambda_cxt with continuation = NeedValue Not_tail} in
let args_code, fn_code, args =
match
Ext_list.fold_right (ap_func :: appinfo.ap_args) ([], [])
(fun x (args_code, fn_code) ->
match compile_lambda new_cxt x with
| {block; value = Some b} ->
(Ext_list.append block args_code, b :: fn_code)
| {value = None} -> assert false)
compile_arguments
~method_callee:
(match ap_func with
| Lprim {primitive = Pjs_object_get _} -> true
| _ -> false)
lambda_cxt
(ap_func :: appinfo.ap_args)
with
| args_code, fn_code :: args -> (args_code, fn_code, args)
| _, [] -> assert false
Expand Down Expand Up @@ -1631,19 +1762,22 @@ let compile output_prefix =
(E.call
~info:(call_info_of_apply lambda_cxt.meta appinfo)
fn_code args)))
(* Compiles the arguments of a call or a literal, which are evaluated left to
right; see [sequence_arguments]. *)
and compile_arguments ?method_callee (lambda_cxt : Lam_compile_context.t)
(args : Lambda.t list) : J.block * J.expression list =
if args = [] then ([], [])
else
let arg_cxt = {lambda_cxt with continuation = NeedValue Not_tail} in
sequence_arguments ?method_callee ~assignable:lambda_cxt.meta.assignable
(Ext_list.map args (fun arg ->
match compile_lambda arg_cxt arg with
| {block; value = Some value} -> (block, value)
| {value = None} -> assert false))
and compile_prim (prim_info : Lambda.prim_info)
(lambda_cxt : Lam_compile_context.t) =
let compile_primitive_default primitive args loc =
let args_block, args_expr =
if args = [] then ([], [])
else
let new_cxt = {lambda_cxt with continuation = NeedValue Not_tail} in
Ext_list.split_map args (fun x ->
match compile_lambda new_cxt x with
| {block; value = Some b} -> (block, b)
| {value = None} -> assert false)
in
let args_code : J.block = List.concat args_block in
let args_code, args_expr = compile_arguments lambda_cxt args in
let exp =
(* TODO: all can be done in [Lam_compile_primitive.translate] *)
Lam_compile_primitive.translate output_prefix loc lambda_cxt primitive
Expand Down Expand Up @@ -1717,28 +1851,12 @@ let compile output_prefix =
ret)
| {primitive = Pjs_object_set property; args = [obj; setter_val]} -> (
(* property write: obj["height"] = v *)
let need_value_no_return_cxt =
{lambda_cxt with continuation = NeedValue Not_tail}
in
let obj_output = compile_lambda need_value_no_return_cxt obj in
let arg_output = compile_lambda need_value_no_return_cxt setter_val in
let cont obj_block arg_block obj_code =
match compile_arguments lambda_cxt [obj; setter_val] with
| args_code, [obj; value] ->
Js_output.output_of_block_and_expression lambda_cxt.continuation
(match obj_code with
| None -> Ext_list.append obj_block arg_block
| Some obj_code -> Ext_list.append obj_block (obj_code :: arg_block))
in
match (obj_output, arg_output) with
| {value = None}, _ | _, {value = None} -> assert false
| ( {block = obj_block; value = Some obj},
{block = arg_block; value = Some value} ) -> (
match Js_ast_util.named_expression obj with
| None ->
cont obj_block arg_block None
(E.seq (E.assign (E.dot obj property) value) E.unit)
| Some (obj_code, obj) ->
cont obj_block arg_block (Some obj_code)
(E.seq (E.assign (E.dot (E.var obj) property) value) E.unit)))
args_code
(E.seq (E.assign (E.dot obj property) value) E.unit)
| _ -> assert false)
| {primitive = Pjs_object_get _ | Pjs_object_set _} -> assert false
| {primitive = Pjs_fn_method; args = args_lambda} -> (
match args_lambda with
Expand All @@ -1763,20 +1881,12 @@ let compile output_prefix =
body))))
| _ -> assert false)
| {primitive = Pjs_object_create labels; args} ->
let args_block, args_expr =
if args = [] then ([], [])
else
let new_cxt = {lambda_cxt with continuation = NeedValue Not_tail} in
Ext_list.split_map args (fun x ->
match compile_lambda new_cxt x with
| {block; value = Some b} -> (block, b)
| {value = None} -> assert false)
in
let args_code, args_expr = compile_arguments lambda_cxt args in
let block, exp =
Lam_compile_external_obj.assemble_obj_args labels args_expr
in
Js_output.output_of_block_and_expression lambda_cxt.continuation
(Ext_list.concat_append args_block block)
(Ext_list.append args_code block)
exp
| {primitive; args; loc} -> compile_primitive_default primitive args loc
and collect_dup_overrides (copy_id : Ident.t) (lam : Lambda.t)
Expand Down
11 changes: 11 additions & 0 deletions compiler/core/lam_compile_main.ml
Original file line number Diff line number Diff line change
Expand Up @@ -215,6 +215,14 @@ let is_awaited_unit (lam : Lambda.t) =
true
| _ -> false

(* See [Lam_stats.assignable]. *)
let assigned_variables (group : Lam_group.t) =
match group with
| Single (_, _, lam) | Nop lam -> Lambda_traverse.assigned_variables lam
| Recursive bindings ->
Ext_list.fold_left bindings Set_ident.empty (fun acc (_, lam) ->
Set_ident.union acc (Lambda_traverse.assigned_variables lam))

(* See [Lam_stats.awaited_units]. *)
let awaited_units (groups : Lam_group.t list) =
let units = ref Set_ident.empty in
Expand Down Expand Up @@ -360,6 +368,9 @@ let compile ?on_optimized_lambda (output_prefix : string)
{
meta with
awaited_units = awaited_units groups;
assignable =
Ext_list.fold_left groups Set_ident.empty (fun acc group ->
Set_ident.union acc (assigned_variables group));
exports = meta.exports @ flat_exports;
export_idents =
Ext_list.fold_left flat_exports meta.export_idents (fun acc id ->
Expand Down
4 changes: 4 additions & 0 deletions compiler/core/lam_stats.ml
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,9 @@ type t = {
for sure it's not a function, there is no need to count them
*)
awaited_units: Set_ident.t;
assignable: Set_ident.t;
(** The variables some [Lassign] assigns. [Lam_compile] never delays
reading one of them past other code. *)
}

let pp = Format.fprintf
Expand All @@ -68,4 +71,5 @@ let make ~export_idents ~export_ident_sets : t =
exports = export_idents;
export_idents = export_ident_sets;
awaited_units = Set_ident.empty;
assignable = Set_ident.empty;
}
3 changes: 3 additions & 0 deletions compiler/core/lam_stats.mli
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,9 @@ type t = {
(** Locals bound to an awaited compilation unit,
[let d = await import(Unit)]: reads of nested [make] values through
them use the flat exports too. *)
assignable: Set_ident.t;
(** The variables some [Lassign] assigns. [Lam_compile] never delays
reading one of them past other code. *)
}

val print : Format.formatter -> t -> unit
Expand Down
11 changes: 11 additions & 0 deletions compiler/ml/lambda_traverse.ml
Original file line number Diff line number Diff line change
Expand Up @@ -243,6 +243,17 @@ let free_variables l =
| _ -> [])
l

let assigned_variables l =
let assigned = ref Set_ident.empty in
let rec walk l =
(match l with
| Lassign (id, _) -> assigned := Set_ident.add id !assigned
| _ -> ());
iter walk l
in
walk l;
!assigned

(* Substitution rebuilds through [shallow_map_sharing], so the result is
normalized and an untouched subterm is returned physically unchanged. *)
let subst_lambda s lam =
Expand Down
3 changes: 3 additions & 0 deletions compiler/ml/lambda_traverse.mli
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,9 @@ val iter : (Lambda.t -> unit) -> Lambda.t -> unit

val free_variables : Lambda.t -> Set_ident.t

val assigned_variables : Lambda.t -> Set_ident.t
(** The variables some [Lassign] in the term assigns. *)

val subst_lambda : Lambda.t Ident.tbl -> Lambda.t -> Lambda.t
(** Substitute for the free variables in the domain of the substitution.
Assumes the substitution's image is out of reach of the term's bound
Expand Down
3 changes: 2 additions & 1 deletion tests/belt_tests/src/bs_array_test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -847,8 +847,9 @@ Mocha.describe("Bs_array_test", () => {
}), c === 6));
});
let id = (loc, x) => {
let tmp = Belt_Array.reverse(x);
let u = x.slice(0);
Test_utils.eq("File \"bs_array_test.res\", line 298, characters 6-13", Belt_Array.reverse(x), (Belt_Array.reverseInPlace(u), u));
Test_utils.eq("File \"bs_array_test.res\", line 298, characters 6-13", tmp, (Belt_Array.reverseInPlace(u), u));
};
Mocha.test("bs_array_test_id_functions", () => {
id("File \"bs_array_test.res\", line 308, characters 7-14", []);
Expand Down
Loading
Loading