Skip to content

Commit b40f911

Browse files
committed
Add show @printer support for polymorphic variants
1 parent 4da03cd commit b40f911

File tree

1 file changed

+14
-5
lines changed

1 file changed

+14
-5
lines changed

src_plugins/show/ppx_deriving_show.ml

+14-5
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ let attr_printer context = Attribute.declare "deriving.show.printer" context
2323
Ast_pattern.(single_expr_payload __) (fun e -> e)
2424
let ct_attr_printer = attr_printer Attribute.Context.core_type
2525
let constr_attr_printer = attr_printer Attribute.Context.constructor_declaration
26+
let rtag_attr_printer = attr_printer Attribute.Context.rtag
2627

2728
let ct_attr_polyprinter = Attribute.declare "deriving.show.polyprinter" Attribute.Context.core_type
2829
Ast_pattern.(single_expr_payload __) (fun e -> e)
@@ -160,21 +161,29 @@ let rec expr_of_typ quoter typ =
160161
| { ptyp_desc = Ptyp_variant (fields, _, _); ptyp_loc } ->
161162
let cases =
162163
fields |> List.map (fun field ->
163-
match field.prf_desc with
164-
| Rtag(label, true (*empty*), []) ->
164+
match Attribute.get rtag_attr_printer field, field.prf_desc with
165+
| Some printer, Rtag(label, true (*empty*), []) ->
166+
let label = label.txt in
167+
Exp.case (Pat.variant label None)
168+
[%expr [%e wrap_printer quoter printer] fmt ()]
169+
| None, Rtag(label, true (*empty*), []) ->
165170
let label = label.txt in
166171
Exp.case (Pat.variant label None)
167172
[%expr Ppx_deriving_runtime.Format.pp_print_string fmt [%e str ("`" ^ label)]]
168-
| Rtag(label, false, [typ]) ->
173+
| Some printer, Rtag(label, false, [typ]) ->
174+
let label = label.txt in
175+
Exp.case (Pat.variant label (Some [%pat? x]))
176+
[%expr [%e wrap_printer quoter printer] fmt x]
177+
| None, Rtag(label, false, [typ]) ->
169178
let label = label.txt in
170179
Exp.case (Pat.variant label (Some [%pat? x]))
171180
[%expr Ppx_deriving_runtime.Format.fprintf fmt [%e str ("`" ^ label ^ " (@[<hov>")];
172181
[%e expr_of_typ typ] x;
173182
Ppx_deriving_runtime.Format.fprintf fmt "@])"]
174-
| Rinherit({ ptyp_desc = Ptyp_constr (tname, _) } as typ) ->
183+
| _, Rinherit({ ptyp_desc = Ptyp_constr (tname, _) } as typ) ->
175184
Exp.case [%pat? [%p Pat.type_ tname] as x]
176185
[%expr [%e expr_of_typ typ] x]
177-
| _ ->
186+
| _, _ ->
178187
raise_errorf ~loc:ptyp_loc "%s cannot be derived for %s"
179188
deriver (Ppx_deriving.string_of_core_type typ))
180189
in

0 commit comments

Comments
 (0)