Skip to content

Commit aa2078e

Browse files
cknittclaude
andauthored
Match optional fields as options (#8842)
Testing an optional field for a value and for presence in one match crashed or miscompiled, because Parmatch.all_record_args rewrote Some(p) to p row by row. Remove the rewrite and recover the generated code with type-preserving optimizations in the match compiler. Claude-Session: https://claude.ai/code/session_01BC5F5QPeQh5cHBjGBnvJ2T Signed-off-by: Christoph Knittel <ck@cca.io> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 61caa2f commit aa2078e

12 files changed

Lines changed: 763 additions & 121 deletions
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
- Fix a compiler crash and wrong code for matches that test an optional record field or dict key both for a value (`{x: 1}`) and for presence (`{x: ?None}`, `{x: ?Some(v)}`), and for untagged variant cases on an optional field. https://github.com/rescript-lang/rescript/pull/8842

‎compiler/ml/matching.ml‎

Lines changed: 135 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1329,9 +1329,53 @@ let make_constr_matching p def ctx = function
13291329
pat = normalize_pat p;
13301330
}
13311331

1332+
(* Whether the payload pattern [p] of [Some] can't match the object that
1333+
represents [Some] of a value like [None] or undefined (see
1334+
[Primitive_option.some]): it doesn't bind the payload itself, and tests it
1335+
with a literal comparison or with a type test that an object fails. An
1336+
untagged case binds its argument only once its type test has passed. *)
1337+
let rec rejects_nested_some p =
1338+
match p.pat_desc with
1339+
| Tpat_any | Tpat_constant _ -> true
1340+
| Tpat_or (p1, p2, _) -> rejects_nested_some p1 && rejects_nested_some p2
1341+
| Tpat_construct (_, cstr, _) -> (
1342+
match cstr.cstr_kind with
1343+
| Ordinary_constructor representation
1344+
when not (Datarepr.constructor_has_optional_shape cstr) -> (
1345+
match Variant_runtime.representation representation with
1346+
| Constant {literal} -> literal <> Some Variant_runtime.Undefined
1347+
| Block (Untagged {block_type = ObjectType | UnknownType}) -> false
1348+
| Block (Untagged _) -> true
1349+
| Block (Tagged _) -> false)
1350+
| Ordinary_constructor _ | Extension_constructor _ -> false)
1351+
| _ -> false
1352+
1353+
(* A [Some] payload whose patterns all reject the representation of a nested
1354+
[Some] is matched as it is, without checking for that representation *)
1355+
let skip_nested_some_check (cell : cell) =
1356+
match cell.pm.args with
1357+
| (Lprim {primitive = Pval_from_option; args = [arg]; loc}, str) :: argl
1358+
when List.for_all
1359+
(function
1360+
| p :: _, _ -> rejects_nested_some p
1361+
| [], _ -> false)
1362+
cell.pm.cases ->
1363+
{
1364+
cell with
1365+
pm =
1366+
{
1367+
cell.pm with
1368+
args =
1369+
(prim ~primitive:Pval_from_option_not_nest ~args:[arg] loc, str)
1370+
:: argl;
1371+
};
1372+
}
1373+
| _ -> cell
1374+
13321375
let divide_constructor ctx pm =
13331376
divide make_constr_matching Types.same_constructor get_key_constr
13341377
get_args_constr ctx pm
1378+
|> List.map (fun (cstr, cell) -> (cstr, skip_nested_some_check cell))
13351379

13361380
(* Matching against a variant *)
13371381

@@ -2054,8 +2098,87 @@ type constructor_matching_plan =
20542098
| Switch_on_constructors of Lambda.lambda_switch
20552099
(** General nominal and untagged variant matching. *)
20562100

2101+
(* Whether [present], the action for a value of the option [arg], starts with a
2102+
test of that value that takes [absent] for undefined. The presence test of
2103+
[arg] is then redundant: undefined reaches [absent] either way. *)
2104+
let rec value_test_defaults_on_undefined ~arg ~absent present =
2105+
let is_value = function
2106+
| Lprim {primitive = Pval_from_option_not_nest; args = [value]} ->
2107+
Lambda.eq_approx arg value
2108+
| e -> Lambda.eq_approx arg e
2109+
in
2110+
let is_equality = function
2111+
| Pboolcomp c
2112+
| Pintcomp c
2113+
| Pfloatcomp c
2114+
| Pbigintcomp c
2115+
| Pstringcomp c
2116+
| Pjscomp c ->
2117+
Some c
2118+
| _ -> None
2119+
in
2120+
(* A constant that undefined is unequal to, even loosely *)
2121+
let is_defined_constant = function
2122+
| Lconst
2123+
( Const_int _ | Const_char _ | Const_string _ | Const_float _
2124+
| Const_bigint _ | Const_js_false | Const_js_true ) ->
2125+
true
2126+
| _ -> false
2127+
in
2128+
let compares_value = function
2129+
| [a; b] ->
2130+
(is_value a && is_defined_constant b)
2131+
|| (is_defined_constant a && is_value b)
2132+
| _ -> false
2133+
in
2134+
match present with
2135+
| Llet
2136+
( Alias,
2137+
id,
2138+
(Lprim {primitive = Pval_from_option_not_nest; args = [value]} as def),
2139+
body )
2140+
when Lambda.eq_approx arg value ->
2141+
(* The value bound to a name *)
2142+
value_test_defaults_on_undefined ~arg:(Lambda.var id) ~absent body
2143+
|| value_test_defaults_on_undefined ~arg:def ~absent body
2144+
| Lswitch (scrutinee, ({sw_failaction = Some fail} as sw)) ->
2145+
is_value scrutinee
2146+
&& Lambda.eq_approx fail absent
2147+
&& switch_defaults_on_undefined sw
2148+
| Lstringswitch (scrutinee, _, Some fail) ->
2149+
is_value scrutinee && Lambda.eq_approx fail absent
2150+
(* undefined is unequal to every constant *)
2151+
| Lifthenelse (Lprim {primitive; args}, if_true, if_false)
2152+
when compares_value args -> (
2153+
match is_equality primitive with
2154+
| Some Cneq -> Lambda.eq_approx if_true absent
2155+
| Some Ceq -> Lambda.eq_approx if_false absent
2156+
| Some (Clt | Cgt | Cle | Cge) | None -> false)
2157+
| _ -> false
2158+
2159+
(* Whether the switch [sw] on an untagged variant takes its default action for
2160+
undefined: no case matches undefined, and each side of the switch that
2161+
undefined can reach has the default action *)
2162+
and switch_defaults_on_undefined (sw : lambda_switch) =
2163+
match sw.sw_dispatch with
2164+
| Switch_variant {block_types} ->
2165+
block_types <> []
2166+
&& (not (List.mem Variant_runtime.UnknownType block_types))
2167+
&& (not sw.sw_blocks_full)
2168+
&& (not (sw.sw_consts_full && sw.sw_consts <> []))
2169+
&& List.for_all
2170+
(function
2171+
| Switch_constructor (Constant {literal}), _ ->
2172+
literal <> Some Variant_runtime.Undefined
2173+
| _ -> true)
2174+
sw.sw_consts
2175+
| Switch_direct -> false
2176+
20572177
let lower_constructor_matching_plan ~loc ~arg = function
20582178
| Use_constructor_action action -> action
2179+
| Test_payload_presence {test = Is_present_option; absent; present}
2180+
when value_test_defaults_on_undefined ~arg ~absent present ->
2181+
present
20592182
| Test_payload_presence {test; absent; present} ->
20602183
let condition =
20612184
match test with
@@ -2465,9 +2588,20 @@ let rec comp_match_handlers comp_fun partial ctx arg first_match next_matchs =
24652588

24662589
(* To find reasonable names for variables *)
24672590

2591+
(* A name for the value [pat] matches, also found under an option's [Some] *)
2592+
let id_of_pattern pat =
2593+
match Typecore.id_of_pattern pat with
2594+
| Some id -> Some id
2595+
| None -> (
2596+
match pat.pat_desc with
2597+
| Tpat_construct (_, cstr, [payload])
2598+
when Datarepr.constructor_has_optional_shape cstr ->
2599+
Typecore.id_of_pattern payload
2600+
| _ -> None)
2601+
24682602
let rec name_pattern default = function
24692603
| (pat :: _, _) :: rem -> (
2470-
match Typecore.id_of_pattern pat with
2604+
match id_of_pattern pat with
24712605
| Some id -> id
24722606
| None -> name_pattern default rem)
24732607
| _ -> Ident.create default

‎compiler/ml/parmatch.ml‎

Lines changed: 1 addition & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -544,40 +544,7 @@ let all_record_args lbls =
544544
(fun lbl -> (mknoloc (Longident.Lident "?temp?"), lbl, omega, opt))
545545
lbl_all
546546
in
547-
List.iter
548-
(fun ((id, lbl, pat, o) as x) ->
549-
let lbl_is_optional () =
550-
match lbl.lbl_repres with
551-
| Record_inlined _ -> false
552-
| _ -> lbl.lbl_optional
553-
in
554-
let x =
555-
match pat.pat_desc with
556-
| Tpat_construct
557-
( {txt = Longident.Ldot (Longident.Lident "*predef*", "Some")},
558-
_,
559-
[({pat_desc = Tpat_constant _} as c)] )
560-
when lbl_is_optional () ->
561-
(id, lbl, c, o)
562-
| Tpat_construct
563-
( {txt = Longident.Ldot (Longident.Lident "*predef*", "Some")},
564-
_,
565-
[({pat_desc = Tpat_construct (_, cd, _)} as pat_construct)] )
566-
when lbl_is_optional () -> (
567-
match cd.cstr_kind with
568-
| Extension_constructor _ -> x
569-
| Ordinary_constructor representation -> (
570-
match Variant_runtime.representation representation with
571-
| Block (Untagged {block_type})
572-
when not
573-
(Ast_untagged_variants.block_type_can_be_undefined
574-
block_type) ->
575-
(id, lbl, pat_construct, o)
576-
| Constant _ | Block _ -> x))
577-
| _ -> x
578-
in
579-
t.(lbl.lbl_pos) <- x)
580-
lbls;
547+
List.iter (fun ((_, lbl, _, _) as x) -> t.(lbl.lbl_pos) <- x) lbls;
581548
Array.to_list t
582549

583550
(* Build argument list when p2 >= p1, where p1 is a simple pattern *)

‎tests/belt_tests/src/bs_poly_map_test.mjs‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -153,7 +153,6 @@ Mocha.describe("Bs_poly_map_test", () => {
153153
let v3 = Belt_Map.update(v1, 10, inc);
154154
let v4 = Belt_Map.update(v3, -10, inc);
155155
let match = Belt_Map.split(v3, 5000);
156-
let pres = match[1];
157156
let match$1 = match[0];
158157
let match$2 = Belt_Map.get(v3, 10);
159158
Test_utils.ok("File \"bs_poly_map_test.res\", line 163, characters 6-13", match$2 === 11);
@@ -163,7 +162,7 @@ Mocha.describe("Bs_poly_map_test", () => {
163162
Test_utils.ok("File \"bs_poly_map_test.res\", line 177, characters 6-13", match$4 === 0);
164163
Test_utils.ok("File \"bs_poly_map_test.res\", line 183, characters 7-14", Belt_Map.isEmpty(Belt_Map.remove(Belt_Map.make(Icmp), 0)));
165164
Test_utils.ok("File \"bs_poly_map_test.res\", line 184, characters 7-14", Belt_Map.isEmpty(Belt_Map.removeMany(Belt_Map.make(Icmp), [0])));
166-
Test_utils.ok("File \"bs_poly_map_test.res\", line 186, characters 6-13", pres === 5000);
165+
Test_utils.ok("File \"bs_poly_map_test.res\", line 186, characters 6-13", match[1] === 5000);
167166
Test_utils.ok("File \"bs_poly_map_test.res\", line 192, characters 7-14", Belt_Array.eq(Belt_Map.keysToArray(match$1[0]), Belt_Array.makeBy(5000, i => i), (a, b) => a === b));
168167
Test_utils.ok("File \"bs_poly_map_test.res\", line 193, characters 7-14", Belt_Array.eq(Belt_Map.keysToArray(match$1[1]), Belt_Array.makeBy(5000, i => 5001 + i | 0), (a, b) => a === b));
169168
let v7 = Belt_Map.remove(v3, 5000);

‎tests/tests/src/gpr_3875_test.mjs‎

Lines changed: 6 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -16,27 +16,13 @@ let Xx = {
1616
};
1717

1818
function compilerBug(a, b, c, f) {
19-
let exit = 0;
20-
if (a !== "x") {
21-
exit = 2;
22-
}
23-
if (exit === 2) {
24-
if (b === undefined) {
25-
if (c) {
26-
result.contents = "No x, c is true";
27-
} else {
28-
result.contents = "No x, c is false";
29-
}
30-
return;
31-
}
32-
if (b !== "x") {
33-
if (c) {
34-
result.contents = "No x, c is true";
35-
} else {
36-
result.contents = "No x, c is false";
37-
}
38-
return;
19+
if (a !== "x" && b !== "x") {
20+
if (c) {
21+
result.contents = "No x, c is true";
22+
} else {
23+
result.contents = "No x, c is false";
3924
}
25+
return;
4026
}
4127
if (f()) {
4228
result.contents = "Some x, f returns true";

‎tests/tests/src/nested_pattern_match_test.mjs‎

Lines changed: 20 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -66,69 +66,53 @@ function f_opion(x) {
6666
if (match$3 === 0) {
6767
return 0;
6868
}
69-
let match$4 = match$3.hd;
70-
if (match$4 === undefined) {
69+
if (match$3.hd !== 2) {
7170
return 0;
7271
}
73-
if (match$4 !== 2) {
72+
let match$4 = match$3.tl;
73+
if (match$4 === 0) {
7474
return 0;
7575
}
76-
let match$5 = match$3.tl;
77-
if (match$5 === 0) {
76+
if (match$4.hd !== 1) {
7877
return 0;
7978
}
80-
let match$6 = match$5.hd;
81-
if (match$6 === undefined) {
82-
return 0;
83-
}
84-
if (match$6 !== 1) {
85-
return 0;
86-
}
87-
let match$7 = match$5.tl;
88-
if (match$7 !== 0 && match$7.hd !== undefined) {
79+
let match$5 = match$4.tl;
80+
if (match$5 !== 0 && match$5.hd !== undefined) {
8981
return 2;
9082
} else {
9183
return 0;
9284
}
9385
}
94-
let match$8 = x.lo;
95-
if (match$8 === 0) {
96-
return 0;
97-
}
98-
if (match$8.hd !== undefined) {
99-
return 0;
100-
}
101-
let match$9 = match$8.tl;
102-
if (match$9 === 0) {
86+
let match$6 = x.lo;
87+
if (match$6 === 0) {
10388
return 0;
10489
}
105-
if (match$9.hd !== undefined) {
90+
if (match$6.hd !== undefined) {
10691
return 0;
10792
}
108-
let match$10 = match$9.tl;
109-
if (match$10 === 0) {
93+
let match$7 = match$6.tl;
94+
if (match$7 === 0) {
11095
return 0;
11196
}
112-
let match$11 = match$10.hd;
113-
if (match$11 === undefined) {
97+
if (match$7.hd !== undefined) {
11498
return 0;
11599
}
116-
if (match$11 !== 2) {
100+
let match$8 = match$7.tl;
101+
if (match$8 === 0) {
117102
return 0;
118103
}
119-
let match$12 = match$10.tl;
120-
if (match$12 === 0) {
104+
if (match$8.hd !== 2) {
121105
return 0;
122106
}
123-
let match$13 = match$12.hd;
124-
if (match$13 === undefined) {
107+
let match$9 = match$8.tl;
108+
if (match$9 === 0) {
125109
return 0;
126110
}
127-
if (match$13 !== 1) {
111+
if (match$9.hd !== 1) {
128112
return 0;
129113
}
130-
let match$14 = match$12.tl;
131-
if (match$14 !== 0 && match$14.hd !== undefined) {
114+
let match$10 = match$9.tl;
115+
if (match$10 !== 0 && match$10.hd !== undefined) {
132116
return 3;
133117
} else {
134118
return 0;

‎tests/tests/src/pattern_match_json.mjs‎

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -25,11 +25,7 @@ function decodeGroup(group) {
2525
}
2626

2727
function decodeNull(x) {
28-
let match = x.field;
29-
if (match === undefined) {
30-
return "no";
31-
}
32-
let tmp = Primitive_option.valFromOption(match);
28+
let tmp = x.field;
3329
if (tmp === null) {
3430
return "yes it's null";
3531
} else {

0 commit comments

Comments
 (0)