Skip to content

Improve output of Dict.has to use inlined JS' in operator #7342

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 7 commits into from
Apr 2, 2025
Merged
Show file tree
Hide file tree
Changes from 5 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 CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
- Fix Pervasive.max using boolean comparison for floats. https://github.com/rescript-lang/rescript/pull/7333
- Experimental: Support nested/inline record types - records defined inside of other records, without needing explicit separate type definitions. https://github.com/rescript-lang/rescript/pull/7241
- Add unified exponentiation (`**`) operator for numeric types using ES7 `**`. https://github.com/rescript-lang/rescript-compiler/pull/7153
- Add built-in support for the JavaScript `in` operator. https://github.com/rescript-lang/rescript/pull/7342
Copy link
Member

Choose a reason for hiding this comment

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

I think changelog should be updated


#### :boom: Breaking Change

Expand Down
1 change: 1 addition & 0 deletions compiler/core/j.ml
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,7 @@ and expression_desc =
[typeof] is an operator
*)
| Typeof of expression
| In of expression * expression (* prop in obj *)
| Js_not of expression (* !v *)
(* TODO: Add some primitives so that [js inliner] can do a better job *)
| Seq of expression * expression
Expand Down
3 changes: 2 additions & 1 deletion compiler/core/js_analyzer.ml
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,7 @@ let rec no_side_effect_expression_desc (x : J.expression_desc) =
&& Ext_list.for_all strings no_side_effect
&& Ext_list.for_all values no_side_effect
| Js_not e -> no_side_effect e
| In (prop, obj) -> no_side_effect prop && no_side_effect obj
| Cond (a, b, c) -> no_side_effect a && no_side_effect b && no_side_effect c
| Call ({expression_desc = Str {txt = "Array.isArray"}}, [e], _) ->
no_side_effect e
Expand Down Expand Up @@ -227,7 +228,7 @@ let rec eq_expression ({expression_desc = x0} : J.expression)
eq_expression_list ls0 ls1 && flag0 = flag1 && eq_expression tag0 tag1
| _ -> false)
| Length _ | Is_null_or_undefined _ | String_append _ | Typeof _ | Js_not _
| Cond _ | FlatCall _ | New _ | Fun _ | Raw_js_code _ | Array _
| In _ | Cond _ | FlatCall _ | New _ | Fun _ | Raw_js_code _ | Array _
| Caml_block_tag _ | Object _ | Tagged_template _ | Await _ ->
false
| Spread _ -> false
Expand Down
9 changes: 7 additions & 2 deletions compiler/core/js_dump.ml
Original file line number Diff line number Diff line change
Expand Up @@ -166,8 +166,8 @@ let rec exp_need_paren ?(arrow = false) (e : J.expression) =
| Length _ | Call _ | Caml_block_tag _ | Seq _ | Static_index _ | Cond _
| Bin _ | Is_null_or_undefined _ | String_index _ | Array_index _
| String_append _ | Var _ | Undefined _ | Null | Str _ | Array _
| Caml_block _ | FlatCall _ | Typeof _ | Number _ | Js_not _ | Bool _ | New _
->
| Caml_block _ | FlatCall _ | Typeof _ | Number _ | Js_not _ | In _ | Bool _
| New _ ->
false
| Await _ -> false
| Spread _ -> false
Expand Down Expand Up @@ -677,6 +677,11 @@ and expression_desc cxt ~(level : int) f x : cxt =
P.cond_paren_group f (level > 13) (fun _ ->
P.string f "!";
expression ~level:13 cxt f e)
| In (prop, obj) ->
P.cond_paren_group f (level > 12) (fun _ ->
let cxt = expression ~level:0 cxt f prop in
P.string f " in ";
expression ~level:0 cxt f obj)
| Typeof e ->
P.string f "typeof";
P.space f;
Expand Down
3 changes: 3 additions & 0 deletions compiler/core/js_exp_make.ml
Original file line number Diff line number Diff line change
Expand Up @@ -1128,6 +1128,9 @@ let or_ ?comment (e1 : t) (e2 : t) =
| Some e -> e
| None -> {expression_desc = Bin (Or, e1, e2); comment})

let in_ (prop : t) (obj : t) : t =
{expression_desc = In (prop, obj); comment = None}

let not (e : t) : t =
match e.expression_desc with
| Number (Int {i; _}) -> bool (i = 0l)
Expand Down
2 changes: 2 additions & 0 deletions compiler/core/js_exp_make.mli
Original file line number Diff line number Diff line change
Expand Up @@ -356,6 +356,8 @@ val and_ : ?comment:string -> t -> t -> t

val or_ : ?comment:string -> t -> t -> t

val in_ : t -> t -> t

(** we don't expose a general interface, since a general interface is generally not safe *)

val dummy_obj : ?comment:string -> Lam_tag_info.t -> t
Expand Down
4 changes: 4 additions & 0 deletions compiler/core/js_fold.ml
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,10 @@ class fold =
| Js_not _x0 ->
let _self = _self#expression _x0 in
_self
| In (_x0, _x1) ->
let _self = _self#expression _x0 in
let _self = _self#expression _x1 in
_self
| Seq (_x0, _x1) ->
let _self = _self#expression _x0 in
let _self = _self#expression _x1 in
Expand Down
4 changes: 4 additions & 0 deletions compiler/core/js_record_fold.ml
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,10 @@ let expression_desc : 'a. ('a, expression_desc) fn =
| Js_not _x0 ->
let st = _self.expression _self st _x0 in
st
| In (_x0, _x1) ->
let st = _self.expression _self st _x0 in
let st = _self.expression _self st _x1 in
st
| Seq (_x0, _x1) ->
let st = _self.expression _self st _x0 in
let st = _self.expression _self st _x1 in
Expand Down
3 changes: 3 additions & 0 deletions compiler/core/js_record_iter.ml
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,9 @@ let expression_desc : expression_desc fn =
| Bool _ -> ()
| Typeof _x0 -> _self.expression _self _x0
| Js_not _x0 -> _self.expression _self _x0
| In (_x0, _x1) ->
_self.expression _self _x0;
_self.expression _self _x1
| Seq (_x0, _x1) ->
_self.expression _self _x0;
_self.expression _self _x1
Expand Down
4 changes: 4 additions & 0 deletions compiler/core/js_record_map.ml
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,10 @@ let expression_desc : expression_desc fn =
| Js_not _x0 ->
let _x0 = _self.expression _self _x0 in
Js_not _x0
| In (_x0, _x1) ->
let _x0 = _self.expression _self _x0 in
let _x1 = _self.expression _self _x1 in
In (_x0, _x1)
| Seq (_x0, _x1) ->
let _x0 = _self.expression _self _x0 in
let _x1 = _self.expression _self _x1 in
Expand Down
2 changes: 1 addition & 1 deletion compiler/core/lam_analysis.ml
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ let rec no_side_effects (lam : Lam.t) : bool =
(* list primitives *)
| Pmakelist
(* dict primitives *)
| Pmakedict
| Pmakedict | Pdict_has
(* Test if the argument is a block or an immediate integer *)
| Pisint | Pis_poly_var_block
(* Test if the (integer) argument is outside an interval *)
Expand Down
7 changes: 7 additions & 0 deletions compiler/core/lam_compile_primitive.ml
Original file line number Diff line number Diff line change
Expand Up @@ -574,6 +574,13 @@ let translate output_prefix loc (cxt : Lam_compile_context.t)
Some (Js_op.Lit txt, expr)
| _ -> None))
| _ -> assert false)
| Pdict_has -> (
match args with
| [obj; prop] -> E.in_ prop obj
| _ ->
Location.raise_errorf ~loc
"Invalid external \"%%dict_has\" type signature. Expected to have two \
arguments.")
| Parraysetu -> (
match args with
(* wrong*)
Expand Down
1 change: 1 addition & 0 deletions compiler/core/lam_convert.ml
Original file line number Diff line number Diff line change
Expand Up @@ -314,6 +314,7 @@ let lam_prim ~primitive:(p : Lambda.primitive) ~args loc : Lam.t =
| Parraysets -> prim ~primitive:Parraysets ~args loc
| Pmakelist _mutable_flag (*FIXME*) -> prim ~primitive:Pmakelist ~args loc
| Pmakedict -> prim ~primitive:Pmakedict ~args loc
| Pdict_has -> prim ~primitive:Pdict_has ~args loc
| Pawait -> prim ~primitive:Pawait ~args loc
| Pimport -> prim ~primitive:Pimport ~args loc
| Pinit_mod -> (
Expand Down
3 changes: 2 additions & 1 deletion compiler/core/lam_primitive.ml
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,7 @@ type t =
| Pmakelist
(* dict primitives *)
| Pmakedict
| Pdict_has
(* promise *)
| Pawait
(* etc or deprecated *)
Expand Down Expand Up @@ -215,7 +216,7 @@ let eq_primitive_approx (lhs : t) (rhs : t) =
(* List primitives *)
| Pmakelist
(* dict primitives *)
| Pmakedict
| Pmakedict | Pdict_has
(* promise *)
| Pawait
(* etc *)
Expand Down
1 change: 1 addition & 0 deletions compiler/core/lam_primitive.mli
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,7 @@ type t =
| Pmakelist
(* dict primitives *)
| Pmakedict
| Pdict_has
(* promise *)
| Pawait
(* etc or deprecated *)
Expand Down
1 change: 1 addition & 0 deletions compiler/core/lam_print.ml
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,7 @@ let primitive ppf (prim : Lam_primitive.t) =
| Pmakearray -> fprintf ppf "makearray"
| Pmakelist -> fprintf ppf "makelist"
| Pmakedict -> fprintf ppf "makedict"
| Pdict_has -> fprintf ppf "dict.has"
| Parrayrefu -> fprintf ppf "array.unsafe_get"
| Parraysetu -> fprintf ppf "array.unsafe_set"
| Parrayrefs -> fprintf ppf "array.get"
Expand Down
1 change: 1 addition & 0 deletions compiler/ml/lambda.ml
Original file line number Diff line number Diff line change
Expand Up @@ -271,6 +271,7 @@ type primitive =
| Pmakelist of Asttypes.mutable_flag
(* dict primitives *)
| Pmakedict
| Pdict_has
(* promise *)
| Pawait
(* module *)
Expand Down
1 change: 1 addition & 0 deletions compiler/ml/lambda.mli
Original file line number Diff line number Diff line change
Expand Up @@ -238,6 +238,7 @@ type primitive =
| Pmakelist of Asttypes.mutable_flag
(* dict primitives *)
| Pmakedict
| Pdict_has
(* promise *)
| Pawait
(* modules *)
Expand Down
1 change: 1 addition & 0 deletions compiler/ml/printlambda.ml
Original file line number Diff line number Diff line change
Expand Up @@ -229,6 +229,7 @@ let primitive ppf = function
| Pmakelist Mutable -> fprintf ppf "makelist"
| Pmakelist Immutable -> fprintf ppf "makelist_imm"
| Pmakedict -> fprintf ppf "makedict"
| Pdict_has -> fprintf ppf "dict.has"
| Pisint -> fprintf ppf "isint"
| Pisout -> fprintf ppf "isout"
| Pisnullable -> fprintf ppf "isnullable"
Expand Down
1 change: 1 addition & 0 deletions compiler/ml/translcore.ml
Original file line number Diff line number Diff line change
Expand Up @@ -346,6 +346,7 @@ let primitives_table =
("%array_unsafe_set", Parraysetu);
(* dict primitives *)
("%makedict", Pmakedict);
("%dict_has", Pdict_has);
(* promise *)
("%await", Pawait);
(* module *)
Expand Down
3 changes: 0 additions & 3 deletions lib/es6/Stdlib_Dict.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,13 +22,10 @@ function mapValues(dict, f) {
return target;
}

let has = ((dict, key) => key in dict);

export {
$$delete$1 as $$delete,
forEach,
forEachWithKey,
mapValues,
has,
}
/* No side effect */
3 changes: 0 additions & 3 deletions lib/js/Stdlib_Dict.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,8 @@ function mapValues(dict, f) {
return target;
}

let has = ((dict, key) => key in dict);

exports.$$delete = $$delete$1;
exports.forEach = forEach;
exports.forEachWithKey = forEachWithKey;
exports.mapValues = mapValues;
exports.has = has;
/* No side effect */
2 changes: 1 addition & 1 deletion runtime/Stdlib_Dict.res
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,6 @@ let mapValues = (dict, f) => {
target
}

let has: (dict<'a>, string) => bool = %raw(`(dict, key) => key in dict`)
external has: (dict<'a>, string) => bool = "%dict_has"

external ignore: dict<'a> => unit = "%ignore"
11 changes: 7 additions & 4 deletions runtime/Stdlib_Dict.resi
Original file line number Diff line number Diff line change
Expand Up @@ -246,17 +246,20 @@ let mapValues: (dict<'a>, 'a => 'b) => dict<'b>
/**
`has(dictionary, "key")` returns true if the "key" is present in the dictionary.

Be aware that it uses the JavaScript `in` operator under the hood.

## Examples

```rescript
let dict = dict{"key1": Some(1), "key2": None}

dict->Dict.has("key1") // true
dict->Dict.has("key2") // true
dict->Dict.has("key3") // false
dict->Dict.has("key1")->assertEqual(true)
dict->Dict.has("key2")->assertEqual(true)
dict->Dict.has("key3")->assertEqual(false)
dict->Dict.has("toString")->assertEqual(true)
```
*/
let has: (dict<'a>, string) => bool
external has: (dict<'a>, string) => bool = "%dict_has"

/**
`ignore(dict)` ignores the provided dict and returns unit.
Expand Down
51 changes: 43 additions & 8 deletions tests/tests/src/DictTests.mjs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
// Generated by ReScript, PLEASE EDIT WITH CARE

import * as Stdlib_Dict from "rescript/lib/es6/Stdlib_Dict.js";

let someString = "hello";

Expand Down Expand Up @@ -43,40 +42,76 @@ let PatternMatching = {
};

let dict = {
key1: 1,
key1: false,
key2: undefined
};

if (Stdlib_Dict.has(dict, "key1") !== true) {
if (!("key1" in dict)) {
throw {
RE_EXN_ID: "Assert_failure",
_1: [
"DictTests.res",
43,
44,
2
],
Error: new Error()
};
}

if (Stdlib_Dict.has(dict, "key2") !== true) {
if (!("key2" in dict)) {
throw {
RE_EXN_ID: "Assert_failure",
_1: [
"DictTests.res",
44,
46,
2
],
Error: new Error()
};
}

if ("key3" in dict !== false) {
throw {
RE_EXN_ID: "Assert_failure",
_1: [
"DictTests.res",
48,
2
],
Error: new Error()
};
}

if ("toString" in dict !== false) {
Copy link
Member

Choose a reason for hiding this comment

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

How did this pass?

Copy link
Member Author

Choose a reason for hiding this comment

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

I'll double check.

Copy link
Member Author

Choose a reason for hiding this comment

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

Fixed. This file wasn't running in the test suite, since it wasn't ending with _test. I decided to move it to Core_DictTests.res (or Stdlib_DictTests.res later)

throw {
RE_EXN_ID: "Assert_failure",
_1: [
"DictTests.res",
50,
2
],
Error: new Error()
};
}

if (!("key1" in dict)) {
throw {
RE_EXN_ID: "Assert_failure",
_1: [
"DictTests.res",
52,
2
],
Error: new Error()
};
}

if (Stdlib_Dict.has(dict, "key3") !== false) {
if (typeof ("key1" in dict) !== "boolean") {
throw {
RE_EXN_ID: "Assert_failure",
_1: [
"DictTests.res",
45,
54,
2
],
Error: new Error()
Expand Down
15 changes: 12 additions & 3 deletions tests/tests/src/DictTests.res
Original file line number Diff line number Diff line change
Expand Up @@ -36,11 +36,20 @@ module PatternMatching = {

module DictHas = {
let dict = dict{
"key1": Some(1),
"key1": Some(false),
"key2": None,
}

assert(dict->Dict.has("key1") === true)
assert(dict->Dict.has("key2") === true)
// Test success path
assert(dict->Dict.has("key1"))
// Test undefined field
assert(dict->Dict.has("key2"))
// Test missing field
assert(dict->Dict.has("key3") === false)
// Test prototype field
assert(dict->Dict.has("toString") === false)
// Test without compile time knowledge
assert(dict->Dict.has(%raw(`"key1"`)))
// Test parantesis in generated code
assert(typeof(dict->Dict.has("key1")) === #boolean)
}