Skip to content

Commit

Permalink
wip: deriving for type vars
Browse files Browse the repository at this point in the history
  • Loading branch information
benbellick committed Dec 10, 2024
1 parent 107b6e3 commit 7a61ac2
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 0 deletions.
21 changes: 21 additions & 0 deletions src/decoders_deriver.ml
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,8 @@ let rec expr_of_typ (typ : core_type)
match CCList.assoc_opt ~eq other_type substitutions with
| Some replacement -> replacement
| None -> Ast_builder.Default.evar ~loc (to_decoder_name lid))
| { ptyp_desc = Ptyp_var var; _ } ->
Ast_builder.Default.evar ~loc @@ to_decoder_name var
| _ ->
Location.raise_errorf ~loc "Cannot construct decoder for %s"
(string_of_core_type typ)
Expand Down Expand Up @@ -302,6 +304,7 @@ let single_type_decoder_gen ~(loc : location) ~rec_flag type_decl :
structure_item list =
let rec_flag = really_recursive rec_flag [ type_decl ] in
let name = to_decoder_name type_decl.ptype_name.txt in

let substitutions =
match rec_flag with
| Nonrecursive -> []
Expand All @@ -315,6 +318,24 @@ let single_type_decoder_gen ~(loc : location) ~rec_flag type_decl :
implementation_generator ~loc ~rec_flag ~substitutions type_decl
in
let name = to_decoder_name type_decl.ptype_name.txt in
let params =
(* TODO: can we drop the non type vars? What are these? *)
CCList.filter_map
(fun (param, _) ->
match param.ptyp_desc with Ptyp_var var -> Some var | _ -> None)
type_decl.ptype_params
in
let args =
CCList.map
(fun param -> Ast_builder.Default.pvar ~loc (to_decoder_name param))
params
in
let imple =
(* We need the type variables to become arguments *)
CCList.fold_left
(fun impl arg -> [%expr fun [%p arg] -> [%e impl]])
imple args
in
[%str let [%p Ast_builder.Default.pvar ~loc name] = [%e imple]]

let rec mutual_rec_fun_gen ~loc
Expand Down
2 changes: 2 additions & 0 deletions test/test_decoders.ml
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,8 @@ type a1 = { l : b1 option; m : c1 option }
and b1 = { n : c1 }
and c1 = { o : a1 } [@@deriving decoders]

type 'a with_type_var = { wrapped : 'a } [@@deriving decoders]

let%test "int" =
match D.decode_string my_int_decoder "1234" with
| Ok i -> i = 1234
Expand Down

0 comments on commit 7a61ac2

Please sign in to comment.