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/dict-has-evaluation-order.fix.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
- Fix `Dict.has` evaluating its key before its dict.
31 changes: 30 additions & 1 deletion compiler/backend/lam_compile.ml
Original file line number Diff line number Diff line change
Expand Up @@ -282,6 +282,16 @@ let rec delay_safe ~assignable (e : J.expression) =
entries
| _ -> false

(* Whether evaluating [a] and [b] in the other order can change a value or the
order of effects: neither is [delay_safe], and one has side effects. A read
of a property, such as [o.x] or [o[k]], counts as free of side effects, as
it does in [Js_analyzer], although a getter or a Proxy can see the order. *)
let order_matters ~assignable (a : J.expression) (b : J.expression) =
not
(delay_safe ~assignable a || delay_safe ~assignable b
|| Js_analyzer.no_side_effect_expression a
&& Js_analyzer.no_side_effect_expression b)

(* 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].
Expand Down Expand Up @@ -466,6 +476,20 @@ let copy_object (e : J.expression) =
| Object _ | Caml_block _ -> e
| _ -> E.obj_entries [Object_spread e]

(* The compiled arguments of a [Pdict_has], the dict and the key, prepared for
[k in d], which evaluates the key first. The dict is evaluated now, with
[evaluate_now], when the order matters. A key with statements makes
[sequence_arguments] evaluate the dict before them anyway. Index reads
count as pure in [order_matters], so [Dict.has(o["x"], o["y"])] keeps
[o["y"] in o["x"]], where a getter or a Proxy sees the key read first. *)
let hold_dict_has ~assignable (args : (J.block * J.expression) list) =
match args with
| [(block, dict); ((_, key) as compiled_key)]
when order_matters ~assignable dict key ->
let held, dict = evaluate_now ~assignable dict in
[(block @ held, dict); compiled_key]
| _ -> args

(* The copy of the argument at [index] of a [Pjsx] with a props spread. The
spread comes right after the tag; the later arguments, the props, children
and key, are no spreads and are not copied. *)
Expand Down Expand Up @@ -2075,7 +2099,8 @@ let compile output_prefix =
compile_arguments
~hold:
(Lam_compile_external_obj.hold_obj_args
~delay_safe:(delay_safe ~assignable:lambda_cxt.meta.assignable)
~order_matters:
(order_matters ~assignable:lambda_cxt.meta.assignable)
labels)
lambda_cxt args
in
Expand Down Expand Up @@ -2116,6 +2141,10 @@ let compile output_prefix =
in
Js_output.output_of_block_and_expression lambda_cxt.continuation
parts_code exp
| {primitive = Pdict_has as primitive; args; loc} ->
compile_primitive_default
~hold:(hold_dict_has ~assignable:lambda_cxt.meta.assignable)
primitive args loc
| {primitive = Pdict_spread as primitive; args; loc} ->
compile_primitive_default ~copy:(fun _ -> copy_object) primitive args loc
| {primitive = Pjsx {jsx_spread = true} as primitive; args; loc} ->
Expand Down
22 changes: 7 additions & 15 deletions compiler/backend/lam_compile_external_obj.ml
Original file line number Diff line number Diff line change
Expand Up @@ -66,38 +66,30 @@ let rec literal_args (labels : External_arg_spec.obj_params)
presence is not known after the object literal, so it evaluates the
argument after the arguments that follow it. Unless that gives the same
values and effects, the argument is bound to a temporary after its
statements, which keeps it in its place. It does when the argument is
[delay_safe], and when each argument that the literal evaluates after it
is [delay_safe] or neither of the two has side effects. *)
let rec hold_obj_args ~(delay_safe : J.expression -> bool)
statements, which keeps it in its place. That is when [order_matters]
holds for it and an argument that the literal evaluates before it. *)
let rec hold_obj_args ~(order_matters : J.expression -> J.expression -> bool)
(labels : External_arg_spec.obj_params)
(args : (J.block * J.expression) list) =
match (labels, args) with
| {obj_arg_label = Obj_label _; obj_arg_type = Arg_cst _} :: labels, args ->
hold_obj_args ~delay_safe labels args
hold_obj_args ~order_matters labels args
| ( {obj_arg_label = Obj_empty | Obj_label _; obj_arg_type} :: labels,
arg :: args ) ->
Lam_compile_external_call.hold_arg ~arg_type:obj_arg_type arg
:: hold_obj_args ~delay_safe labels args
:: hold_obj_args ~order_matters labels args
| {obj_arg_label = Obj_optional _; obj_arg_type} :: labels, arg :: args ->
let ((block, value) as held) =
Lam_compile_external_call.hold_arg ~arg_type:obj_arg_type arg
in
let order_matters (later : J.expression) =
not
(delay_safe later
|| Js_analyzer.no_side_effect_expression value
&& Js_analyzer.no_side_effect_expression later)
in
(if
presence_unknown value
&& (not (delay_safe value))
&& List.exists order_matters (literal_args labels args)
&& List.exists (order_matters value) (literal_args labels args)
then
let tmp = Ext_ident.create_tmp () in
(block @ [S.define_variable ~kind:Strict tmp value], E.var tmp)
else held)
:: hold_obj_args ~delay_safe labels args
:: hold_obj_args ~order_matters labels args
| [], [] -> []
| [], _ :: _ | _ :: _, [] -> assert false

Expand Down
6 changes: 3 additions & 3 deletions compiler/backend/lam_compile_external_obj.mli
Original file line number Diff line number Diff line change
Expand Up @@ -26,16 +26,16 @@
object literal. *)

val hold_obj_args :
delay_safe:(J.expression -> bool) ->
order_matters:(J.expression -> J.expression -> bool) ->
External_arg_spec.obj_params ->
(J.block * J.expression) list ->
(J.block * J.expression) list
(** {!Lam_compile_external_call.hold_arg} for the compiled arguments of an
object-creating external. An optional argument whose presence is not
known is also bound to a temporary when evaluating it after the object
literal, as {!assemble_obj_args} does, could change a value or the order
of effects. [delay_safe] tells whether evaluating an argument after other
code gives the same value and effects. *)
of effects. [order_matters a b] tells whether evaluating [a] and [b] in
the other order can change a value or the order of effects. *)

val assemble_obj_args :
External_arg_spec.obj_params -> J.expression list -> J.block * J.expression
Expand Down
2 changes: 2 additions & 0 deletions compiler/backend/lam_compile_primitive.ml
Original file line number Diff line number Diff line change
Expand Up @@ -600,6 +600,8 @@ let translate output_prefix loc (cxt : Lam_compile_context.t)
args)
| Pdict_has -> (
match args with
(* [Lam_compile.hold_dict_has] has bound the dict to a temporary when it
must be evaluated before the key *)
| [obj; prop] -> E.in_ prop obj
| _ ->
Loc_report.raise_errorf ~loc
Expand Down
206 changes: 206 additions & 0 deletions tests/compiler_tests/src/dict_has_order_test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,206 @@
// Generated by ReScript, PLEASE EDIT WITH CARE

import * as Mocha from "mocha";
import * as Test_utils from "./test_utils.mjs";

let log = [];

let eff = (function (s, v) { log.push(s); return v });

function takeLog() {
let entries = log.slice();
log.splice(0, log.length);
return entries;
}

function bothEffects(d, k) {
let tmp = eff("dict", d);
return eff("key", k) in tmp;
}

let current = {
contents: "a"
};

function keyReadsState(d) {
current.contents = "b";
let tmp = eff("dict", d);
return current.contents in tmp;
}

let dicts = {
contents: {
a: 1
}
};

function dictReadsState(other) {
let tmp = dicts.contents;
return (dicts.contents = other, eff("key", "a")) in tmp;
}

function localKey(d) {
let k = "x";
let results = [];
for (let i = 0; i <= 1; ++i) {
let set = () => {
k = i === 0 ? "a" : "x";
return d;
};
let tmp = set();
results.push(k in tmp);
}
return results;
}

function localDict(d, other) {
let current = d;
let results = [];
for (let i = 0; i <= 1; ++i) {
let set = () => {
current = other;
if (i === 0) {
return "a";
} else {
return "b";
}
};
let tmp = current;
results.push(set() in tmp);
}
return results;
}

function keyStatements(d) {
let tmp = eff("dict", d);
let tmp$1;
try {
tmp$1 = eff("key", "a");
} catch (exn) {
tmp$1 = "b";
}
return tmp$1 in tmp;
}

function nested(d) {
let tmp = eff("dict", d);
let tmp$1 = eff("inner dict", d);
return (
eff("inner key", "a") in tmp$1 ? eff("key", "a") : "b"
) in tmp;
}

function constantKey(d) {
return "a" in eff("dict", d);
}

function variableDict(d) {
return eff("key", "a") in d;
}

function variables(d, k) {
return k in d;
}

function constant(d) {
return "a" in d;
}

Mocha.describe("Dict_has_order_test", () => {
Mocha.test("the dict is evaluated before the key", () => {
Test_utils.eq("File \"dict_has_order_test.res\", line 95, characters 7-14", bothEffects({
a: 1
}, "a"), true);
Test_utils.eq("File \"dict_has_order_test.res\", line 96, characters 7-14", takeLog(), [
"dict",
"key"
]);
Test_utils.eq("File \"dict_has_order_test.res\", line 97, characters 7-14", bothEffects({
a: 1
}, "b"), false);
Test_utils.eq("File \"dict_has_order_test.res\", line 98, characters 7-14", takeLog(), [
"dict",
"key"
]);
});
Mocha.test("the key is read after the dict's effects", () => {
current.contents = "a";
Test_utils.eq("File \"dict_has_order_test.res\", line 102, characters 7-14", keyReadsState({
b: 1
}), true);
Test_utils.eq("File \"dict_has_order_test.res\", line 103, characters 7-14", takeLog(), ["dict"]);
});
Mocha.test("the dict is read before the key's effects", () => {
dicts.contents = {
a: 1
};
Test_utils.eq("File \"dict_has_order_test.res\", line 107, characters 7-14", dictReadsState({}), true);
Test_utils.eq("File \"dict_has_order_test.res\", line 108, characters 7-14", takeLog(), ["key"]);
});
Mocha.test("a local key assigned by the dict", () => Test_utils.eq("File \"dict_has_order_test.res\", line 111, characters 7-14", localKey({
a: 1
}), [
true,
false
]));
Mocha.test("a local dict assigned by the key", () => Test_utils.eq("File \"dict_has_order_test.res\", line 114, characters 7-14", localDict({
a: 1
}, {}), [
true,
false
]));
Mocha.test("a key with statements", () => {
Test_utils.eq("File \"dict_has_order_test.res\", line 117, characters 7-14", keyStatements({
a: 1
}), true);
Test_utils.eq("File \"dict_has_order_test.res\", line 118, characters 7-14", takeLog(), [
"dict",
"key"
]);
});
Mocha.test("a Dict.has in the key", () => {
Test_utils.eq("File \"dict_has_order_test.res\", line 121, characters 7-14", nested({
a: 1
}), true);
Test_utils.eq("File \"dict_has_order_test.res\", line 122, characters 7-14", takeLog(), [
"dict",
"inner dict",
"inner key",
"key"
]);
});
Mocha.test("shapes without an observable order", () => {
Test_utils.eq("File \"dict_has_order_test.res\", line 125, characters 7-14", constantKey({
a: 1
}), true);
Test_utils.eq("File \"dict_has_order_test.res\", line 126, characters 7-14", variableDict({}), false);
Test_utils.eq("File \"dict_has_order_test.res\", line 127, characters 7-14", takeLog(), [
"dict",
"key"
]);
Test_utils.eq("File \"dict_has_order_test.res\", line 128, characters 7-14", "a" in ({
a: 1
}), true);
Test_utils.eq("File \"dict_has_order_test.res\", line 129, characters 7-14", "a" in ({}), false);
});
});

export {
log,
eff,
takeLog,
bothEffects,
current,
keyReadsState,
dicts,
dictReadsState,
localKey,
localDict,
keyStatements,
nested,
constantKey,
variableDict,
variables,
constant,
}
/* Not a pure module */
Loading
Loading