Skip to content

Commit 15b6eca

Browse files
committed
reuse more logic from ast_untagged
1 parent 6cdc49e commit 15b6eca

File tree

1 file changed

+14
-25
lines changed

1 file changed

+14
-25
lines changed

jscomp/ml/variant_coercion.ml

Lines changed: 14 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -7,44 +7,33 @@ let check_constructors (constructors : Types.constructor_declaration list) check
77
check c.cd_args (Ast_untagged_variants.process_tag_type c.cd_attributes))
88
constructors
99

10-
let can_coerce_to_string (constructors : Types.constructor_declaration list) =
11-
check_constructors constructors (fun args payload ->
12-
match (args, payload) with
13-
| Cstr_tuple [], (None | Some (String _)) -> true
14-
| _ -> false)
15-
16-
let can_coerce_to_int (constructors : Types.constructor_declaration list) =
17-
check_constructors constructors (fun args payload ->
18-
match (args, payload) with
19-
| Cstr_tuple [], Some (Int _) -> true
20-
| _ -> false)
21-
22-
let can_coerce_to_float (constructors : Types.constructor_declaration list) =
23-
check_constructors constructors (fun args payload ->
24-
match (args, payload) with
25-
| Cstr_tuple [], Some (Float _) -> true
26-
| _ -> false)
27-
10+
(* Right now we only allow coercing to primitives string/int/float *)
2811
let can_coerce_path (path : Path.t) =
2912
Path.same path Predef.path_string
3013
|| Path.same path Predef.path_int
3114
|| Path.same path Predef.path_float
3215

3316
let can_coerce_variant ~(path : Path.t)
3417
(constructors : Types.constructor_declaration list) =
35-
if Path.same path Predef.path_string && can_coerce_to_string constructors then
36-
true
37-
else if Path.same path Predef.path_int && can_coerce_to_int constructors then
38-
true
39-
else if Path.same path Predef.path_float && can_coerce_to_float constructors
40-
then true
41-
else false
18+
constructors
19+
|> List.for_all (fun (c : Types.constructor_declaration) ->
20+
let args = c.cd_args in
21+
let payload = Ast_untagged_variants.process_tag_type c.cd_attributes in
22+
match args with
23+
| Cstr_tuple [] -> (
24+
match payload with
25+
| None | Some (String _) -> Path.same path Predef.path_string
26+
| Some (Int _) -> Path.same path Predef.path_int
27+
| Some (Float _) -> Path.same path Predef.path_float
28+
| Some (Null | Undefined | Bool _ | Untagged _) -> false)
29+
| _ -> false)
4230

4331
let can_try_coerce_variant_to_primitive
4432
((_, p, typedecl) : Path.t * Path.t * Types.type_declaration) =
4533
match typedecl with
4634
| {type_kind = Type_variant constructors; type_params = []}
4735
when Path.name p <> "bool" ->
36+
(* bool is represented as a variant internally, so we need to account for that *)
4837
Some constructors
4938
| _ -> None
5039

0 commit comments

Comments
 (0)