Skip to content

Commit 8ba7928

Browse files
cristianoczth
authored andcommitted
Draft dict pattern matching.
Works for this: ``` type myDict = {name?:string, anyOtherField?: int} let tst = (d: myDict) => switch d { | {name:n, something:i} => String.length(n) + i | {name:n} => String.length(n) | {something:i} => i | _ => 0 } ```
1 parent ac30044 commit 8ba7928

File tree

1 file changed

+21
-3
lines changed

1 file changed

+21
-3
lines changed

jscomp/ml/typecore.ml

Lines changed: 21 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -788,6 +788,8 @@ module NameChoice(Name : sig
788788
val get_name: t -> string
789789
val get_type: t -> type_expr
790790
val get_descrs: Env.type_descriptions -> t list
791+
792+
val set_name: t -> string -> t
791793
val unbound_name_error: Env.t -> Longident.t loc -> 'a
792794

793795
end) = struct
@@ -798,13 +800,19 @@ end) = struct
798800
| Tconstr(p, _, _) -> p
799801
| _ -> assert false
800802

801-
let lookup_from_type env tpath lid =
803+
let lookup_from_type env tpath (lid : Longident.t loc) : Name.t =
802804
let descrs = get_descrs (Env.find_type_descrs tpath env) in
803805
Env.mark_type_used env (Path.last tpath) (Env.find_type tpath env);
804806
match lid.txt with
805-
Longident.Lident s -> begin
807+
Longident.Lident s_ -> begin
808+
let s = if List.exists (fun nd -> get_name nd = s_) descrs
809+
then s_
810+
else "anyOtherField" in
806811
try
807-
List.find (fun nd -> get_name nd = s) descrs
812+
let x = List.find (fun nd -> get_name nd = s) descrs in
813+
if s = "anyOtherField"
814+
then set_name x s_
815+
else x
808816
with Not_found ->
809817
let names = List.map get_name descrs in
810818
raise (Error (lid.loc, env,
@@ -884,6 +892,14 @@ module Label = NameChoice (struct
884892
type t = label_description
885893
let type_kind = "record"
886894
let get_name lbl = lbl.lbl_name
895+
let set_name lbl name =
896+
let l =
897+
{lbl with
898+
lbl_name = name;
899+
lbl_repres = Record_optional_labels [name]} in
900+
let lbl_all = lbl.lbl_all in
901+
lbl_all.(Array.length lbl_all - 1) <- l; (* assume "anyOtherField" is the last label *)
902+
l
887903
let get_type lbl = lbl.lbl_res
888904
let get_descrs = snd
889905
let unbound_name_error = Typetexp.unbound_label_error
@@ -1040,6 +1056,8 @@ module Constructor = NameChoice (struct
10401056
let type_kind = "variant"
10411057
let get_name cstr = cstr.cstr_name
10421058
let get_type cstr = cstr.cstr_res
1059+
1060+
let set_name _cstr _name = assert false
10431061
let get_descrs = fst
10441062
let unbound_name_error = Typetexp.unbound_constructor_error
10451063
end)

0 commit comments

Comments
 (0)