Fix Dict.has evaluating its key before its dict
Why
Dict.has(d, k) compiles to k in d, and JS evaluates the key first. ReScript evaluates arguments left to right, so the effects of the two arguments ran in the wrong order. Fixes #9222.
When the order can be seen, the dict is now evaluated first, into a temporary. The output stays k in d when either argument is a constant or a variable nothing assigns, or when neither has side effects.
modifiedJS Dict.has whose arguments must run in order
let eff: (string, 'a) => 'a = %raw(`function (s, v) { log.push(s); return v }`)let bothEffects = (d: dict<int>, k) => Dict.has(eff("dict", d), eff("key", k))let dicts = ref(dict{"a": 1})let dictReadsState = (other: dict<int>) => Dict.has( dicts.contents, { dicts := other eff("key", "a") }, )
js
Before
After
function bothEffects(d, k) {function bothEffects(d, k) { return eff("key", k) in eff("dict", d); let tmp = eff("dict", d); return eff("key", k) in tmp;}} function dictReadsState(other) {function dictReadsState(other) { return (dicts.contents = other, eff("key", "a")) in dicts.contents; let tmp = dicts.contents; return (dicts.contents = other, eff("key", "a")) in tmp;}}
modifiedJS Dict.has whose order cannot be seen
let constantKey = (d: dict<int>) => eff("dict", d)->Dict.has("a")let variableDict = (d: dict<int>) => d->Dict.has(eff("key", "a"))let variables = (d: dict<int>, k) => d->Dict.has(k)
js
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;}
Review
- Why in JS compilation and not in Lambda? Call arguments are already held there in order, with
delay_safeandevaluate_now.hold_dict_hasreuses them. It shares the neworder_matterswithhold_obj_args, which made the same check for the optional fields of an@objexternal. - Can a getter still see the key read first? Yes. Index reads count as pure, as for
@objfields, soDict.has(o["x"], o["y"])keepso["y"] in o["x"]and gets no temporary. This is deliberate. - What about the conditional key from the issue's comment? #9428 fixed it:
d->Dict.has(c ? "a" : "b")prints(c ? "a" : "b") in d, andprinter_operand_levels_testcovers it. - Does other output change? No. The runtime, Belt and every test's JavaScript compile as before.