Skip to content

Commit

Permalink
Code gen: improve pattern matching of optional fields.
Browse files Browse the repository at this point in the history
Pattern matching of optional fields such as
```res
| {x: 1, y: "hello"}
```

can be specialised as the constants already imply the values cannot be absent.
  • Loading branch information
cristianoc committed Nov 1, 2024
1 parent 43d2bbf commit f04fb33
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 21 deletions.
20 changes: 19 additions & 1 deletion compiler/ml/parmatch.ml
Original file line number Diff line number Diff line change
Expand Up @@ -524,7 +524,25 @@ let all_record_args lbls =
(fun lbl -> (mknoloc (Longident.Lident "?temp?"), lbl, omega))
lbl_all
in
List.iter (fun ((_, lbl, _) as x) -> t.(lbl.lbl_pos) <- x) lbls;
List.iter
(fun ((id, lbl, pat) as x) ->
let lbl_is_optional () =
match lbl.lbl_repres with
| Record_optional_labels labels -> List.mem lbl.lbl_name labels
| _ -> false
in
let x =
match pat.pat_desc with
| Tpat_construct
( {txt = Longident.Ldot (Longident.Lident "*predef*", "Some")},
_,
[({pat_desc = Tpat_constant _} as c)] )
when lbl_is_optional () ->
(id, lbl, c)
| _ -> x
in
t.(lbl.lbl_pos) <- x)
lbls;
Array.to_list t
| _ -> fatal_error "Parmatch.all_record_args"

Expand Down
29 changes: 9 additions & 20 deletions tests/tests/src/DictTests.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -17,33 +17,22 @@ let intDict = {
};

function inferDictByPattern(dict) {
let match = dict.one;
if (match === 1) {
let match$1 = dict.three;
if (match$1 === 3) {
let match$2 = dict.four;
if (match$2 === 4) {
dict["five"] = 5;
return;
}

}

if (dict.one === 1 && dict.three === 3 && dict.four === 4) {
dict["five"] = 5;
return;
}
let match$3 = dict.two;
if (match$3 === 1) {
console.log("two");
} else {
if (dict.two !== 1) {
console.log("not one");
} else {
console.log("two");
}
}

function constrainedAsDict(dict) {
let match = dict.one;
if (match === 1) {
console.log("one");
} else {
if (dict.one !== 1) {
console.log("not one");
} else {
console.log("one");
}
}

Expand Down

0 comments on commit f04fb33

Please sign in to comment.