Skip to content

Commit 787a764

Browse files
committed
Optional fields pattern matching: untagged variants
Add support for untagged variants to optimised pattern matching for optional fields.
1 parent e1eaad3 commit 787a764

File tree

3 files changed

+80
-0
lines changed

3 files changed

+80
-0
lines changed

compiler/ml/parmatch.ml

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -539,6 +539,31 @@ let all_record_args lbls =
539539
[({pat_desc = Tpat_constant _} as c)] )
540540
when lbl_is_optional () ->
541541
(id, lbl, c)
542+
| Tpat_construct
543+
( {txt = Longident.Ldot (Longident.Lident "*predef*", "Some")},
544+
_,
545+
[({pat_desc = Tpat_construct (_, cd, _)} as pat_construct)] )
546+
when lbl_is_optional () -> (
547+
let block_type =
548+
match cd.cstr_res.desc with
549+
| Tconstr (path, _, _) -> (
550+
match Env.find_type path pat.pat_env with
551+
| {type_kind = Type_variant cstrs} ->
552+
Ext_list.find_opt cstrs (fun cstr ->
553+
if cstr.cd_id.name = cd.cstr_name then
554+
Ast_untagged_variants.get_block_type ~env:pat.pat_env
555+
cstr
556+
else None)
557+
| _ -> None)
558+
| _ -> None
559+
in
560+
match block_type with
561+
| Some
562+
( IntType | StringType | FloatType | BigintType | BooleanType
563+
| InstanceType _ | FunctionType | ObjectType ) ->
564+
(* These types cannot be undefined *)
565+
(id, lbl, pat_construct)
566+
| _ -> x)
542567
| _ -> x
543568
in
544569
t.(lbl.lbl_pos) <- x)
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
// Generated by ReScript, PLEASE EDIT WITH CARE
2+
3+
4+
function decodeGroup(group) {
5+
let id = group.id;
6+
if (id === null) {
7+
return [
8+
"e",
9+
"f"
10+
];
11+
}
12+
if (typeof id !== "string") {
13+
return [
14+
"e",
15+
"f"
16+
];
17+
}
18+
let name = group.name;
19+
if (typeof name !== "string") {
20+
return [
21+
"e",
22+
"f"
23+
];
24+
} else {
25+
return [
26+
id,
27+
name
28+
];
29+
}
30+
}
31+
32+
export {
33+
decodeGroup,
34+
}
35+
/* No side effect */
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
@unboxed
2+
type rec t =
3+
| Boolean(bool)
4+
| @as(null) Null
5+
| String(string)
6+
| Number(float)
7+
| Object(Dict.t<t>)
8+
| Array(array<t>)
9+
10+
type group = {
11+
id: string,
12+
name: string,
13+
}
14+
15+
let decodeGroup = group => {
16+
switch group {
17+
| dict{"id": String(id), "name": String(name)} => (id, name)
18+
| _ => ("e", "f")
19+
}
20+
}

0 commit comments

Comments
 (0)