Debian Codegraph @

expander/expand_of_sexp.ml

raw symbols SCIP
1 open! Base
2 open! Ppxlib
3 open Ast_builder.Default
4 open Helpers
5 open Lifted.Monad_infix
6
7 (* Generates the signature for type conversion from S-expressions *)
8 module Sig_generate_of_sexp = struct
9 let type_of_of_sexp ~loc t =
10 let loc = { loc with loc_ghost = true } in
11 [%type: Sexplib0.Sexp.t -> [%t t]]
12 ;;
13
14 let mk_type td = combinator_type_of_type_declaration td ~f:type_of_of_sexp
15
16 let sig_of_td with_poly td =
17 let of_sexp_type = mk_type td in
18 let loc = td.ptype_loc in
19 let of_sexp_item =
20 psig_value
21 ~loc
22 (value_description
23 ~loc
24 ~name:(Located.map (fun s -> s ^ "_of_sexp") td.ptype_name)
25 ~type_:of_sexp_type
26 ~prim:[])
27 in
28 match with_poly, is_polymorphic_variant td ~sig_:true with
29 | true, `Surely_not ->
30 Location.raise_errorf
31 ~loc
32 "Sig_generate_of_sexp.sig_of_td: sexp_poly annotation but type is surely not a \
33 polymorphic variant"
34 | false, (`Surely_not | `Maybe) -> [ of_sexp_item ]
35 | (true | false), `Definitely | true, `Maybe ->
36 [ of_sexp_item
37 ; psig_value
38 ~loc
39 (value_description
40 ~loc
41 ~name:(Located.map (fun s -> "__" ^ s ^ "_of_sexp__") td.ptype_name)
42 ~type_:of_sexp_type
43 ~prim:[])
44 ]
45 ;;
46
47 let mk_sig ~poly ~loc:_ ~path:_ (_rf, tds) = List.concat_map tds ~f:(sig_of_td poly)
48 end
49
50 module Str_generate_of_sexp = struct
51 module Ptag_error_function = struct
52 type t =
53 | Ptag_no_args
54 | Ptag_takes_args
55 end
56
57 module Row_or_constructor = struct
58 type t =
59 | Row of row_field
60 | Constructor of constructor_declaration
61 end
62
63 let with_error_source ~loc ~full_type_name make_body =
64 let lifted =
65 let name = lazy (Fresh_name.create "error_source" ~loc) in
66 make_body ~error_source:(fun () -> Fresh_name.expression (force name))
67 >>| fun body ->
68 match Lazy.is_val name with
69 | false ->
70 (* no references to [name], no need to define it *)
71 body
72 | true ->
73 (* add a definition for [name] *)
74 [%expr
75 let [%p Fresh_name.pattern (force name)] = [%e estring ~loc full_type_name] in
76 [%e body]]
77 in
78 Lifted.let_bind_user_expressions lifted ~loc
79 ;;
80
81 (* Utility functions for polymorphic variants *)
82
83 (* Handle backtracking when variants do not match *)
84 let handle_no_variant_match loc expr =
85 [ [%pat? Sexplib0.Sexp_conv_error.No_variant_match] --> expr ]
86 ;;
87
88 (* Generate code depending on whether to generate a match for the last
89 case of matching a variant *)
90 let handle_variant_match_last loc ~match_last ~fresh_atom matches =
91 match match_last, matches with
92 | true, [ { pc_lhs = _; pc_guard = None; pc_rhs = expr } ]
93 | _, [ { pc_lhs = [%pat? _]; pc_guard = None; pc_rhs = expr } ] -> expr
94 | _ -> pexp_match ~loc (Fresh_name.expression fresh_atom) matches
95 ;;
96
97 (* Generate code for matching malformed S-expressions *)
98 let mk_variant_other_matches ~error_source ~fresh__sexp loc rev_els call =
99 let coll_structs acc (loc, cnstr) =
100 (pstring ~loc cnstr
101 -->
102 match (call : Ptag_error_function.t) with
103 | Ptag_no_args ->
104 [%expr
105 Sexplib0.Sexp_conv_error.ptag_no_args
106 [%e error_source ()]
107 [%e Fresh_name.expression fresh__sexp]]
108 | Ptag_takes_args ->
109 [%expr
110 Sexplib0.Sexp_conv_error.ptag_takes_args
111 [%e error_source ()]
112 [%e Fresh_name.expression fresh__sexp]])
113 :: acc
114 in
115 let exc_no_variant_match =
116 [%pat? _] --> [%expr Sexplib0.Sexp_conv_error.no_variant_match ()]
117 in
118 List.fold_left ~f:coll_structs ~init:[ exc_no_variant_match ] rev_els
119 ;;
120
121 (* Split the row fields of a variant type into lists of atomic variants,
122 structured variants, atomic variants + included variant types,
123 and structured variants + included variant types. *)
124 let split_row_field ~loc (atoms, structs, ainhs, sinhs) row_field =
125 match row_field.prf_desc with
126 | Rtag ({ txt = cnstr; _ }, true, []) ->
127 let tpl = loc, cnstr in
128 tpl :: atoms, structs, `A tpl :: ainhs, sinhs
129 | Rtag ({ txt = cnstr; _ }, false, [ tp ]) ->
130 let loc = tp.ptyp_loc in
131 atoms, (loc, cnstr) :: structs, ainhs, `S (loc, cnstr, tp, row_field) :: sinhs
132 | Rinherit inh ->
133 let iinh = `I inh in
134 atoms, structs, iinh :: ainhs, iinh :: sinhs
135 | Rtag (_, true, [ _ ]) | Rtag (_, _, _ :: _ :: _) ->
136 Location.raise_errorf ~loc "unsupported: polymorphic variant intersection type"
137 | Rtag (_, false, []) ->
138 Location.raise_errorf ~loc "unsupported: polymorphic variant empty type"
139 ;;
140
141 let type_constr_of_sexp ?(internal = false) id args =
142 type_constr_conv id args ~f:(fun s ->
143 let s = s ^ "_of_sexp" in
144 if internal then "__" ^ s ^ "__" else s)
145 ;;
146
147 (* Conversion of types *)
148 let rec type_of_sexp ~error_source ~typevars ?full_type ?(internal = false) typ
149 : Conversion.t
150 =
151 let loc = typ.ptyp_loc in
152 match Ppxlib_jane.Jane_syntax.Core_type.of_ast typ with
153 | Some (Jtyp_tuple alist, (_ : attributes)) ->
154 Conversion.of_reference_exn
155 (labeled_tuple_of_sexp ~error_source ~typevars ~loc alist)
156 | Some (Jtyp_layout _, _) | None ->
157 (match typ with
158 | _ when Option.is_some (Attribute.get Attrs.opaque typ) ->
159 Conversion.of_reference_exn [%expr Sexplib0.Sexp_conv.opaque_of_sexp]
160 | [%type: [%t? _] sexp_opaque] | [%type: _] ->
161 Conversion.of_reference_exn [%expr Sexplib0.Sexp_conv.opaque_of_sexp]
162 | [%type: [%t? ty1] sexp_list] ->
163 let arg1 =
164 Conversion.to_expression ~loc (type_of_sexp ~error_source ~typevars ty1)
165 in
166 Conversion.of_reference_exn [%expr Sexplib0.Sexp_conv.list_of_sexp [%e arg1]]
167 | [%type: [%t? ty1] sexp_array] ->
168 let arg1 =
169 Conversion.to_expression ~loc (type_of_sexp ~error_source ~typevars ty1)
170 in
171 Conversion.of_reference_exn [%expr Sexplib0.Sexp_conv.array_of_sexp [%e arg1]]
172 | { ptyp_desc = Ptyp_tuple tp; _ } ->
173 Conversion.of_lambda (tuple_of_sexp ~error_source ~typevars (loc, tp))
174 | { ptyp_desc = Ptyp_var parm; _ } ->
175 (match Map.find typevars parm with
176 | Some fresh -> Conversion.of_reference_exn (Fresh_name.expression fresh)
177 | None ->
178 Location.raise_errorf ~loc "ppx_sexp_conv: unbound type variable '%s" parm)
179 | { ptyp_desc = Ptyp_constr (id, args); _ } ->
180 let args =
181 List.map args ~f:(fun arg ->
182 Conversion.to_expression ~loc (type_of_sexp ~error_source ~typevars arg))
183 in
184 Conversion.of_reference_exn (type_constr_of_sexp ~loc ~internal id args)
185 | { ptyp_desc = Ptyp_arrow (_, _, _); _ } ->
186 Conversion.of_reference_exn [%expr Sexplib0.Sexp_conv.fun_of_sexp]
187 | { ptyp_desc = Ptyp_variant (row_fields, Closed, _); _ } ->
188 variant_of_sexp ~error_source ~typevars ?full_type (loc, row_fields)
189 | { ptyp_desc = Ptyp_poly (parms, poly_tp); _ } ->
190 poly_of_sexp ~error_source ~typevars parms poly_tp
191 | { ptyp_desc = Ptyp_variant (_, Open, _); _ }
192 | { ptyp_desc = Ptyp_object (_, _); _ }
193 | { ptyp_desc = Ptyp_class (_, _); _ }
194 | { ptyp_desc = Ptyp_alias (_, _); _ }
195 | { ptyp_desc = Ptyp_package _; _ }
196 | { ptyp_desc = Ptyp_extension _; _ }
197 | { ptyp_desc = Ptyp_open _; _ } ->
198 Location.raise_errorf ~loc "Type unsupported for ppx [of_sexp] conversion")
199
200 (* Conversion of (unlabeled) tuples *)
201 and tuple_of_sexp ~error_source ~typevars (loc, tps) =
202 let fps = List.map ~f:(type_of_sexp ~error_source ~typevars) tps in
203 let ({ bindings; arguments; converted } : Conversion.Apply_all.t) =
204 Conversion.apply_all ~loc fps
205 in
206 let n = List.length fps in
207 let fresh_sexp = Fresh_name.create "sexp" ~loc in
208 [ [%pat? Sexplib0.Sexp.List [%p plist ~loc arguments]]
209 --> pexp_let ~loc Nonrecursive bindings (pexp_tuple ~loc converted)
210 ; Fresh_name.pattern fresh_sexp
211 --> [%expr
212 Sexplib0.Sexp_conv_error.tuple_of_size_n_expected
213 [%e error_source ()]
214 [%e eint ~loc n]
215 [%e Fresh_name.expression fresh_sexp]]
216 ]
217
218 (* Conversion of labeled tuples *)
219 and labeled_tuple_of_sexp ~error_source ~typevars ~loc alist =
220 assert (Labeled_tuple.is_valid alist);
221 let fields_expr =
222 List.fold_right
223 alist
224 ~init:[%expr Empty]
225 ~f:(fun (label_option, core_type) rest_expr ->
226 let name_expr = estring ~loc (Labeled_tuple.atom_of_label label_option) in
227 let conv_expr =
228 type_of_sexp ~error_source ~typevars core_type
229 |> Conversion.to_expression ~loc:core_type.ptyp_loc
230 in
231 [%expr
232 Field { name = [%e name_expr]; conv = [%e conv_expr]; rest = [%e rest_expr] }])
233 in
234 let create_expr =
235 let pats, exprs =
236 List.map alist ~f:(fun (label_option, _) ->
237 let name = Fresh_name.create ~loc "field" in
238 Fresh_name.pattern name, (label_option, Fresh_name.expression name))
239 |> List.unzip
240 in
241 let pat =
242 List.fold_right pats ~init:(punit ~loc) ~f:(fun pat1 pat2 ->
243 ppat_tuple ~loc [ pat1; pat2 ])
244 in
245 let expr = Ppxlib_jane.Jane_syntax.Labeled_tuples.expr_of ~loc exprs in
246 [%expr fun [%p pat] -> [%e expr]]
247 in
248 pexp_apply
249 ~loc
250 [%expr Sexplib0.Sexp_conv_labeled_tuple.labeled_tuple_of_sexp]
251 [ Labelled "caller", error_source ()
252 ; Labelled "fields", fields_expr
253 ; Labelled "create", create_expr
254 ]
255
256 (* Generate code for matching included variant types *)
257 and handle_variant_inh
258 ~error_source
259 ~typevars
260 ~fresh_atom
261 ~fresh__sexp
262 full_type
263 ~match_last
264 other_matches
265 inh
266 =
267 let loc = inh.ptyp_loc in
268 let func_expr = type_of_sexp ~error_source ~typevars ~internal:true inh in
269 let app =
270 Conversion.of_reference_exn
271 (Conversion.apply ~loc func_expr (Fresh_name.expression fresh__sexp))
272 in
273 let match_exc =
274 handle_no_variant_match
275 loc
276 (handle_variant_match_last loc ~match_last ~fresh_atom other_matches)
277 in
278 let new_other_matches =
279 [ [%pat? _]
280 --> pexp_try
281 ~loc
282 [%expr
283 ([%e Conversion.to_expression ~loc app]
284 :> [%t replace_variables_by_underscores full_type])]
285 match_exc
286 ]
287 in
288 new_other_matches, true
289
290 (* Generate code for matching atomic variants *)
291 and mk_variant_match_atom
292 ~error_source
293 ~typevars
294 ~fresh_atom
295 ~fresh__sexp
296 loc
297 full_type
298 rev_atoms_inhs
299 rev_structs
300 =
301 let coll (other_matches, match_last) = function
302 | `A (loc, cnstr) ->
303 let new_match = pstring ~loc cnstr --> pexp_variant ~loc cnstr None in
304 new_match :: other_matches, false
305 | `I inh ->
306 handle_variant_inh
307 ~error_source
308 ~typevars
309 ~fresh_atom
310 ~fresh__sexp
311 full_type
312 ~match_last
313 other_matches
314 inh
315 in
316 let other_matches =
317 mk_variant_other_matches ~error_source ~fresh__sexp loc rev_structs Ptag_takes_args
318 in
319 let match_atoms_inhs, match_last =
320 List.fold_left ~f:coll ~init:(other_matches, false) rev_atoms_inhs
321 in
322 handle_variant_match_last loc ~match_last ~fresh_atom match_atoms_inhs
323
324 (* Variant conversions *)
325
326 (* Match arguments of constructors (variants or sum types) *)
327 and mk_cnstr_args_match
328 ~error_source
329 ~typevars
330 ~loc
331 ~is_variant
332 ~fresh__sexp
333 ~fresh__tag
334 ~fresh_sexp_args
335 cnstr
336 tps
337 row
338 =
339 let cnstr vars_expr =
340 if is_variant
341 then pexp_variant ~loc cnstr (Some vars_expr)
342 else pexp_construct ~loc (Located.lident ~loc cnstr) (Some vars_expr)
343 in
344 match tps with
345 | [ tp ]
346 when Option.is_some
347 (match (row : Row_or_constructor.t) with
348 | Row r -> Attribute.get Attrs.list_poly r
349 | Constructor c -> Attribute.get Attrs.list_variant c) ->
350 (match tp with
351 | [%type: [%t? tp] list] ->
352 let cnv =
353 Conversion.to_expression ~loc (type_of_sexp ~error_source ~typevars tp)
354 in
355 cnstr
356 [%expr
357 Sexplib0.Sexp_conv.list_map
358 [%e cnv]
359 [%e Fresh_name.expression fresh_sexp_args]]
360 | _ ->
361 (match row with
362 | Row _ -> Attrs.invalid_attribute ~loc Attrs.list_poly "_ list"
363 | Constructor _ -> Attrs.invalid_attribute ~loc Attrs.list_variant "_ list"))
364 | [ [%type: [%t? tp] sexp_list] ] ->
365 let cnv = Conversion.to_expression ~loc (type_of_sexp ~error_source ~typevars tp) in
366 cnstr
367 [%expr
368 Sexplib0.Sexp_conv.list_map [%e cnv] [%e Fresh_name.expression fresh_sexp_args]]
369 | _ ->
370 let bindings, patts, good_arg_match =
371 let fps = List.map ~f:(type_of_sexp ~error_source ~typevars) tps in
372 let ({ bindings; arguments; converted } : Conversion.Apply_all.t) =
373 Conversion.apply_all ~loc fps
374 in
375 let good_arg_match = cnstr (pexp_tuple ~loc converted) in
376 bindings, arguments, good_arg_match
377 in
378 [%expr
379 match [%e Fresh_name.expression fresh_sexp_args] with
380 | [%p plist ~loc patts] -> [%e pexp_let ~loc Nonrecursive bindings good_arg_match]
381 | _ ->
382 [%e
383 if is_variant
384 then
385 [%expr
386 Sexplib0.Sexp_conv_error.ptag_incorrect_n_args
387 [%e error_source ()]
388 [%e Fresh_name.expression fresh__tag]
389 [%e Fresh_name.expression fresh__sexp]]
390 else
391 [%expr
392 Sexplib0.Sexp_conv_error.stag_incorrect_n_args
393 [%e error_source ()]
394 [%e Fresh_name.expression fresh__tag]
395 [%e Fresh_name.expression fresh__sexp]]]]
396
397 (* Generate code for matching structured variants *)
398 and mk_variant_match_struct
399 ~error_source
400 ~typevars
401 ~fresh_atom
402 ~fresh__sexp
403 ~fresh_sexp_args
404 loc
405 full_type
406 rev_structs_inhs
407 rev_atoms
408 =
409 let has_structs_ref = ref false in
410 let coll (other_matches, match_last) = function
411 | `S (loc, cnstr, tp, row) ->
412 has_structs_ref := true;
413 let fresh__tag = Fresh_name.create "_tag" ~loc in
414 let expr =
415 mk_cnstr_args_match
416 ~error_source
417 ~typevars
418 ~loc:tp.ptyp_loc
419 ~is_variant:true
420 ~fresh__sexp
421 ~fresh__tag
422 ~fresh_sexp_args
423 cnstr
424 [ tp ]
425 (Row row)
426 in
427 let new_match =
428 ppat_alias
429 ~loc
430 [%pat? [%p pstring ~loc cnstr]]
431 (Fresh_name.to_string_loc fresh__tag)
432 --> expr
433 in
434 new_match :: other_matches, false
435 | `I inh ->
436 handle_variant_inh
437 ~error_source
438 ~typevars
439 ~fresh_atom
440 ~fresh__sexp
441 full_type
442 ~match_last
443 other_matches
444 inh
445 in
446 let other_matches =
447 mk_variant_other_matches ~error_source ~fresh__sexp loc rev_atoms Ptag_no_args
448 in
449 let match_structs_inhs, match_last =
450 List.fold_left ~f:coll ~init:(other_matches, false) rev_structs_inhs
451 in
452 ( handle_variant_match_last loc ~match_last ~fresh_atom match_structs_inhs
453 , !has_structs_ref )
454
455 (* Generate code for handling atomic and structured variants (i.e. not
456 included variant types) *)
457 and handle_variant_tag ~error_source ~typevars loc full_type row_field_list =
458 let fresh_atom = Fresh_name.create "atom" ~loc in
459 let fresh_sexp = Fresh_name.create "sexp" ~loc in
460 let fresh__sexp = Fresh_name.create "_sexp" ~loc in
461 let fresh_sexp_args = Fresh_name.create "sexp_args" ~loc in
462 let rev_atoms, rev_structs, rev_atoms_inhs, rev_structs_inhs =
463 List.fold_left ~f:(split_row_field ~loc) ~init:([], [], [], []) row_field_list
464 in
465 let match_struct, has_structs =
466 mk_variant_match_struct
467 ~error_source
468 ~typevars
469 ~fresh_atom
470 ~fresh__sexp
471 ~fresh_sexp_args
472 loc
473 full_type
474 rev_structs_inhs
475 rev_atoms
476 in
477 let maybe_sexp_args_patt =
478 if has_structs then Fresh_name.pattern fresh_sexp_args else [%pat? _]
479 in
480 [ ppat_alias
481 ~loc
482 [%pat? Sexplib0.Sexp.Atom [%p Fresh_name.pattern fresh_atom]]
483 (Fresh_name.to_string_loc fresh__sexp)
484 --> mk_variant_match_atom
485 ~error_source
486 ~typevars
487 ~fresh_atom
488 ~fresh__sexp
489 loc
490 full_type
491 rev_atoms_inhs
492 rev_structs
493 ; ppat_alias
494 ~loc
495 [%pat?
496 Sexplib0.Sexp.List
497 (Sexplib0.Sexp.Atom [%p Fresh_name.pattern fresh_atom]
498 :: [%p maybe_sexp_args_patt])]
499 (Fresh_name.to_string_loc fresh__sexp)
500 --> match_struct
501 ; ppat_alias
502 ~loc
503 [%pat? Sexplib0.Sexp.List (Sexplib0.Sexp.List _ :: _)]
504 (Fresh_name.to_string_loc fresh_sexp)
505 --> [%expr
506 Sexplib0.Sexp_conv_error.nested_list_invalid_poly_var
507 [%e error_source ()]
508 [%e Fresh_name.expression fresh_sexp]]
509 ; ppat_alias ~loc [%pat? Sexplib0.Sexp.List []] (Fresh_name.to_string_loc fresh_sexp)
510 --> [%expr
511 Sexplib0.Sexp_conv_error.empty_list_invalid_poly_var
512 [%e error_source ()]
513 [%e Fresh_name.expression fresh_sexp]]
514 ]
515
516 (* Generate matching code for variants *)
517 and variant_of_sexp ~error_source ~typevars ?full_type (loc, row_fields) =
518 let is_contained, full_type =
519 match full_type with
520 | None -> true, ptyp_variant ~loc row_fields Closed None
521 | Some full_type -> false, full_type
522 in
523 let top_match =
524 let fresh_sexp = Fresh_name.create ~loc "sexp" in
525 match row_fields with
526 | { prf_desc = Rinherit inh; _ } :: rest ->
527 let rec loop inh row_fields =
528 let call =
529 [%expr
530 ([%e
531 Conversion.to_expression
532 ~loc
533 (type_of_sexp ~error_source ~typevars ~internal:true inh)]
534 [%e Fresh_name.expression fresh_sexp]
535 :> [%t replace_variables_by_underscores full_type])]
536 in
537 match row_fields with
538 | [] -> call
539 | h :: t ->
540 let expr =
541 match h.prf_desc with
542 | Rinherit inh -> loop inh t
543 | _ ->
544 let rftag_matches =
545 handle_variant_tag ~error_source ~typevars loc full_type row_fields
546 in
547 pexp_match ~loc (Fresh_name.expression fresh_sexp) rftag_matches
548 in
549 pexp_try ~loc call (handle_no_variant_match loc expr)
550 in
551 [ Fresh_name.pattern fresh_sexp --> loop inh rest ]
552 | _ :: _ -> handle_variant_tag ~error_source ~typevars loc full_type row_fields
553 | [] ->
554 Location.raise_errorf
555 ~loc
556 "of_sexp is not supported for empty polymorphic variants (impossible?)"
557 in
558 if is_contained
559 then (
560 let fresh_sexp = Fresh_name.create "sexp" ~loc in
561 Conversion.of_lambda
562 [ Fresh_name.pattern fresh_sexp
563 --> [%expr
564 try [%e pexp_match ~loc (Fresh_name.expression fresh_sexp) top_match] with
565 | Sexplib0.Sexp_conv_error.No_variant_match ->
566 Sexplib0.Sexp_conv_error.no_matching_variant_found
567 [%e error_source ()]
568 [%e Fresh_name.expression fresh_sexp]]
569 ])
570 else Conversion.of_lambda top_match
571
572 and poly_of_sexp ~error_source ~typevars parms tp =
573 let loc = tp.ptyp_loc in
574 let typevars =
575 List.fold parms ~init:typevars ~f:(fun map parm ->
576 Map.set
577 map
578 ~key:parm.txt
579 ~data:(Fresh_name.create ("_of_" ^ parm.txt) ~loc:parm.loc))
580 in
581 let bindings =
582 let mk_binding parm =
583 let fresh = Map.find_exn typevars parm.txt in
584 let fresh_sexp = Fresh_name.create "sexp" ~loc in
585 value_binding
586 ~loc
587 ~pat:(Fresh_name.pattern fresh)
588 ~expr:
589 [%expr
590 fun [%p Fresh_name.pattern fresh_sexp] ->
591 Sexplib0.Sexp_conv_error.record_poly_field_value
592 [%e error_source ()]
593 [%e Fresh_name.expression fresh_sexp]]
594 in
595 List.map ~f:mk_binding parms
596 in
597 Conversion.bind (type_of_sexp ~error_source ~typevars tp) bindings
598 ;;
599
600 type record_poly_type =
601 { type_and_field_name : Fresh_name.t
602 ; params : string loc list
603 ; body : core_type
604 }
605
606 let record_poly_type field =
607 match field.pld_type.ptyp_desc with
608 | Ptyp_poly (params, body) ->
609 let type_and_field_name = Fresh_name.of_string_loc field.pld_name in
610 Some { type_and_field_name; params; body }
611 | _ -> None
612 ;;
613
614 let record_field_conv field ~poly ~loc ~error_source ~typevars =
615 match poly with
616 | None ->
617 type_of_sexp ~error_source ~typevars field.pld_type |> Conversion.to_expression ~loc
618 | Some { type_and_field_name; params; body } ->
619 let fresh_sexp = Fresh_name.create "sexp" ~loc in
620 let fresh_params =
621 List.map params ~f:(fun { loc; txt } -> Fresh_name.create ~loc ("_" ^ txt))
622 in
623 let pat = Fresh_name.pattern fresh_sexp in
624 let body =
625 let label = Located.map_lident (Fresh_name.to_string_loc type_and_field_name) in
626 let typevars =
627 List.fold2_exn
628 params
629 fresh_params
630 ~init:typevars
631 ~f:(fun typevars param fresh -> Map.set typevars ~key:param.txt ~data:fresh)
632 in
633 let expr =
634 pexp_let
635 ~loc
636 Nonrecursive
637 (List.map fresh_params ~f:(fun fresh ->
638 let { loc; txt } = Fresh_name.to_string_loc fresh in
639 let expr =
640 [%expr
641 Sexplib0.Sexp_conv_error.record_poly_field_value [%e error_source ()]]
642 in
643 value_binding ~loc ~pat:(pvar ~loc txt) ~expr))
644 (Conversion.apply
645 (type_of_sexp ~error_source ~typevars body)
646 ~loc
647 (Fresh_name.expression fresh_sexp))
648 in
649 pexp_record ~loc [ label, expr ] None
650 in
651 eabstract ~loc [ pat ] body
652 ;;
653
654 let fields_arg_for_record_of_sexp poly_fields ~loc ~error_source ~typevars =
655 List.fold_right
656 poly_fields
657 ~init:(Lifted.return [%expr Empty])
658 ~f:(fun (poly, field) rest_lifted ->
659 rest_lifted
660 >>= fun rest_expr ->
661 let label_expr = estring ~loc:field.pld_name.loc field.pld_name.txt in
662 match Record_field_attrs.Of_sexp.create ~loc field with
663 | Specific Required ->
664 Lifted.return
665 [%expr
666 Field
667 { name = [%e label_expr]
668 ; kind = Required
669 ; conv = [%e record_field_conv field ~poly ~loc ~error_source ~typevars]
670 ; rest = [%e rest_expr]
671 }]
672 | Specific (Default lifted) ->
673 lifted
674 >>| fun default ->
675 [%expr
676 Field
677 { name = [%e label_expr]
678 ; kind = Default (fun () -> [%e default])
679 ; conv = [%e record_field_conv field ~poly ~loc ~error_source ~typevars]
680 ; rest = [%e rest_expr]
681 }]
682 | Omit_nil ->
683 Lifted.return
684 [%expr
685 Field
686 { name = [%e label_expr]
687 ; kind = Omit_nil
688 ; conv = [%e record_field_conv field ~poly ~loc ~error_source ~typevars]
689 ; rest = [%e rest_expr]
690 }]
691 | Sexp_bool ->
692 Lifted.return
693 [%expr
694 Field
695 { name = [%e label_expr]
696 ; kind = Sexp_bool
697 ; conv = ()
698 ; rest = [%e rest_expr]
699 }]
700 | Sexp_array core_type ->
701 let conv_expr =
702 type_of_sexp ~error_source ~typevars core_type
703 |> Conversion.to_expression ~loc
704 in
705 Lifted.return
706 [%expr
707 Field
708 { name = [%e label_expr]
709 ; kind = Sexp_array
710 ; conv = [%e conv_expr]
711 ; rest = [%e rest_expr]
712 }]
713 | Sexp_list core_type ->
714 let conv_expr =
715 type_of_sexp ~error_source ~typevars core_type
716 |> Conversion.to_expression ~loc
717 in
718 Lifted.return
719 [%expr
720 Field
721 { name = [%e label_expr]
722 ; kind = Sexp_list
723 ; conv = [%e conv_expr]
724 ; rest = [%e rest_expr]
725 }]
726 | Sexp_option core_type ->
727 let conv_expr =
728 type_of_sexp ~error_source ~typevars core_type
729 |> Conversion.to_expression ~loc
730 in
731 Lifted.return
732 [%expr
733 Field
734 { name = [%e label_expr]
735 ; kind = Sexp_option
736 ; conv = [%e conv_expr]
737 ; rest = [%e rest_expr]
738 }])
739 ;;
740
741 let index_of_field_arg_for_record_of_sexp fields ~loc =
742 let field_cases =
743 List.mapi fields ~f:(fun i (_, field) ->
744 let lhs = pstring ~loc:field.pld_name.loc field.pld_name.txt in
745 let rhs = eint ~loc i in
746 case ~lhs ~guard:None ~rhs)
747 in
748 let default_case = case ~lhs:(ppat_any ~loc) ~guard:None ~rhs:(eint ~loc (-1)) in
749 let cases = List.concat [ field_cases; [ default_case ] ] in
750 pexp_function_cases ~loc cases
751 ;;
752
753 let create_arg_for_record_of_sexp td fields ~loc ~constructor =
754 let pat =
755 List.fold_right
756 fields
757 ~init:[%pat? ()]
758 ~f:(fun (poly, field) tail ->
759 let head =
760 let pat = pvar ~loc:field.pld_name.loc field.pld_name.txt in
761 match poly with
762 | None -> pat
763 | Some { type_and_field_name; _ } ->
764 (* Extract a polymorphic value from a polymorphic record defined explicitly
765 for this purpose. *)
766 let label =
767 Located.map_lident (Fresh_name.to_string_loc type_and_field_name)
768 in
769 ppat_record ~loc [ label, pat ] Closed
770 in
771 ppat_tuple ~loc [ head; tail ])
772 in
773 let body =
774 let record_expr =
775 pexp_record
776 ~loc
777 (List.map fields ~f:(fun (_, field) ->
778 let label = Located.map_lident field.pld_name in
779 let expr = evar ~loc:field.pld_name.loc field.pld_name.txt in
780 label, expr))
781 None
782 in
783 match constructor with
784 | None -> record_expr
785 | Some label ->
786 (* variant constructor with inline record *)
787 pexp_construct ~loc label (Some record_expr)
788 in
789 let core_type =
790 ptyp_constr
791 ~loc
792 (Located.map_lident td.ptype_name)
793 (List.map td.ptype_params ~f:(fun (core_type, _) ->
794 ptyp_any ~loc:core_type.ptyp_loc))
795 in
796 eabstract ~loc [ pat ] (pexp_constraint ~loc body core_type)
797 ;;
798
799 let polymorphic_record_types_for_record_of_sexp fields ~loc =
800 (* Define fresh types to contain polymorphic values parsed from sexps. *)
801 List.filter_map fields ~f:(fun (poly, _) ->
802 match poly with
803 | Some { type_and_field_name; params; body } ->
804 let fresh_field =
805 label_declaration
806 ~loc
807 ~name:(Fresh_name.to_string_loc type_and_field_name)
808 ~mutable_:Immutable
809 ~type_:(strip_attributes#core_type (ptyp_poly ~loc params body))
810 in
811 let type_decl =
812 type_declaration
813 ~loc
814 ~name:(Fresh_name.to_string_loc type_and_field_name)
815 ~params:[]
816 ~cstrs:[]
817 ~kind:(Ptype_record [ fresh_field ])
818 ~private_:Public
819 ~manifest:None
820 in
821 Some
822 { type_decl with
823 ptype_attributes =
824 (* define unboxed types to avoid allocation *)
825 [ { attr_loc = loc
826 ; attr_name = { loc; txt = "unboxed" }
827 ; attr_payload = PStr []
828 }
829 ]
830 }
831 | None -> None)
832 ;;
833
834 let args_for_record_of_sexp
835 td
836 fields
837 ~loc
838 ~error_source
839 ~typevars
840 ~constructor
841 ~allow_extra_fields
842 =
843 let caller_expr = error_source () in
844 let allow_extra_fields_expr = ebool ~loc allow_extra_fields in
845 let fields = List.map fields ~f:(fun field -> record_poly_type field, field) in
846 let index_of_field_expr = index_of_field_arg_for_record_of_sexp fields ~loc in
847 let create_expr = create_arg_for_record_of_sexp td fields ~loc ~constructor in
848 let fields_expr_lifted =
849 fields_arg_for_record_of_sexp fields ~loc ~error_source ~typevars
850 in
851 fields_expr_lifted
852 >>| fun fields_expr ->
853 let types = polymorphic_record_types_for_record_of_sexp fields ~loc in
854 let args =
855 [ Labelled "caller", caller_expr
856 ; Labelled "fields", fields_expr
857 ; Labelled "index_of_field", index_of_field_expr
858 ; Labelled "allow_extra_fields", allow_extra_fields_expr
859 ; Labelled "create", create_expr
860 ]
861 in
862 types, args
863 ;;
864
865 (* Generate matching code for records *)
866 let record_of_sexp ~error_source ~typevars ~allow_extra_fields td (loc, flds) =
867 args_for_record_of_sexp
868 td
869 flds
870 ~loc
871 ~error_source
872 ~typevars
873 ~constructor:None
874 ~allow_extra_fields
875 >>| fun (types, args) ->
876 let conv =
877 pexp_apply ~loc [%expr Sexplib0.Sexp_conv_record.record_of_sexp] args
878 |> Conversion.of_reference_exn
879 in
880 Conversion.bind_types conv types
881 ;;
882
883 (* Sum type conversions *)
884
885 (* Generate matching code for well-formed S-expressions wrt. sum types *)
886 let mk_good_sum_matches ~error_source ~typevars td (_, cds) =
887 List.map cds ~f:(fun cd ->
888 let loc = cd.pcd_loc in
889 match cd with
890 | { pcd_name = constructor; pcd_args = Pcstr_record fields; _ } ->
891 let allow_extra_fields =
892 Option.is_some (Attribute.get Attrs.allow_extra_fields_cd cd)
893 in
894 args_for_record_of_sexp
895 td
896 fields
897 ~loc
898 ~error_source
899 ~typevars
900 ~constructor:(Some (Located.map_lident constructor))
901 ~allow_extra_fields
902 >>| fun (types, args) ->
903 let string_pat =
904 let loc = constructor.loc in
905 ppat_or
906 ~loc
907 (pstring ~loc (String.uncapitalize constructor.txt))
908 (pstring ~loc constructor.txt)
909 in
910 let fresh_sexp = Fresh_name.create "sexp" ~loc in
911 let fresh_sexps = Fresh_name.create "sexps" ~loc in
912 ppat_alias
913 ~loc
914 [%pat?
915 Sexplib0.Sexp.List
916 (Sexplib0.Sexp.Atom [%p string_pat] :: [%p Fresh_name.pattern fresh_sexps])]
917 (Fresh_name.to_string_loc fresh_sexp)
918 --> (pexp_apply
919 ~loc
920 [%expr Sexplib0.Sexp_conv_record.record_of_sexps]
921 (List.concat
922 [ [ Labelled "context", Fresh_name.expression fresh_sexp ]
923 ; args
924 ; [ Nolabel, Fresh_name.expression fresh_sexps ]
925 ])
926 |> with_types ~loc ~types)
927 | { pcd_name = cnstr; pcd_args = Pcstr_tuple []; _ } ->
928 Attrs.fail_if_allow_extra_field_cd ~loc cd;
929 let lcstr = pstring ~loc (String.uncapitalize cnstr.txt) in
930 let str = pstring ~loc cnstr.txt in
931 [%pat? Sexplib0.Sexp.Atom ([%p lcstr] | [%p str])]
932 --> pexp_construct ~loc (Located.lident ~loc cnstr.txt) None
933 |> Lifted.return
934 | { pcd_name = cnstr; pcd_args = Pcstr_tuple (_ :: _ as tps); _ } ->
935 Attrs.fail_if_allow_extra_field_cd ~loc cd;
936 let lcstr = pstring ~loc (String.uncapitalize cnstr.txt) in
937 let str = pstring ~loc cnstr.txt in
938 let fresh__sexp = Fresh_name.create "_sexp" ~loc in
939 let fresh__tag = Fresh_name.create "_tag" ~loc in
940 let fresh_sexp_args = Fresh_name.create "sexp_args" ~loc in
941 ppat_alias
942 ~loc
943 [%pat?
944 Sexplib0.Sexp.List
945 (Sexplib0.Sexp.Atom
946 [%p
947 ppat_alias
948 ~loc
949 [%pat? [%p lcstr] | [%p str]]
950 (Fresh_name.to_string_loc fresh__tag)]
951 :: [%p Fresh_name.pattern fresh_sexp_args])]
952 (Fresh_name.to_string_loc fresh__sexp)
953 --> mk_cnstr_args_match
954 ~error_source
955 ~typevars
956 ~loc
957 ~is_variant:false
958 ~fresh__sexp
959 ~fresh__tag
960 ~fresh_sexp_args
961 cnstr.txt
962 tps
963 (Constructor cd)
964 |> Lifted.return)
965 ;;
966
967 (* Generate matching code for malformed S-expressions with good tags
968 wrt. sum types *)
969 let mk_bad_sum_matches ~error_source (loc, cds) =
970 let fresh_sexp = Fresh_name.create "sexp" ~loc in
971 List.map cds ~f:(function
972 | { pcd_name = cnstr; pcd_args = Pcstr_tuple []; _ } ->
973 let lcstr = pstring ~loc (String.uncapitalize cnstr.txt) in
974 let str = pstring ~loc cnstr.txt in
975 ppat_alias
976 ~loc
977 [%pat? Sexplib0.Sexp.List (Sexplib0.Sexp.Atom ([%p lcstr] | [%p str]) :: _)]
978 (Fresh_name.to_string_loc fresh_sexp)
979 --> [%expr
980 Sexplib0.Sexp_conv_error.stag_no_args
981 [%e error_source ()]
982 [%e Fresh_name.expression fresh_sexp]]
983 | { pcd_name = cnstr; pcd_args = Pcstr_tuple (_ :: _) | Pcstr_record _; _ } ->
984 let lcstr = pstring ~loc (String.uncapitalize cnstr.txt) in
985 let str = pstring ~loc cnstr.txt in
986 ppat_alias
987 ~loc
988 [%pat? Sexplib0.Sexp.Atom ([%p lcstr] | [%p str])]
989 (Fresh_name.to_string_loc fresh_sexp)
990 --> [%expr
991 Sexplib0.Sexp_conv_error.stag_takes_args
992 [%e error_source ()]
993 [%e Fresh_name.expression fresh_sexp]])
994 ;;
995
996 (* Generate matching code for sum types *)
997 let sum_of_sexp ~error_source ~typevars td (loc, alts) =
998 let fresh_sexp = Fresh_name.create "sexp" ~loc in
999 [ mk_good_sum_matches ~error_source ~typevars td (loc, alts) |> Lifted.all
1000 ; mk_bad_sum_matches ~error_source (loc, alts) |> Lifted.return
1001 ; [ ppat_alias
1002 ~loc
1003 [%pat? Sexplib0.Sexp.List (Sexplib0.Sexp.List _ :: _)]
1004 (Fresh_name.to_string_loc fresh_sexp)
1005 --> [%expr
1006 Sexplib0.Sexp_conv_error.nested_list_invalid_sum
1007 [%e error_source ()]
1008 [%e Fresh_name.expression fresh_sexp]]
1009 ; ppat_alias
1010 ~loc
1011 [%pat? Sexplib0.Sexp.List []]
1012 (Fresh_name.to_string_loc fresh_sexp)
1013 --> [%expr
1014 Sexplib0.Sexp_conv_error.empty_list_invalid_sum
1015 [%e error_source ()]
1016 [%e Fresh_name.expression fresh_sexp]]
1017 ; Fresh_name.pattern fresh_sexp
1018 --> [%expr
1019 Sexplib0.Sexp_conv_error.unexpected_stag
1020 [%e error_source ()]
1021 [%e Fresh_name.expression fresh_sexp]]
1022 ]
1023 |> Lifted.return
1024 ]
1025 |> Lifted.all
1026 >>| List.concat
1027 >>| Conversion.of_lambda
1028 ;;
1029
1030 (* Empty type *)
1031 let nil_of_sexp ~error_source loc : Conversion.t =
1032 Conversion.of_reference_exn
1033 [%expr Sexplib0.Sexp_conv_error.empty_type [%e error_source ()]]
1034 ;;
1035
1036 (* Generate code from type definitions *)
1037
1038 let td_of_sexp ~typevars ~loc:_ ~poly ~path ~rec_flag ~values_being_defined td =
1039 let tps = List.map td.ptype_params ~f:get_type_param_name in
1040 let { ptype_name = { txt = type_name; loc = _ }; ptype_loc = loc; _ } = td in
1041 let full_type =
1042 core_type_of_type_declaration td |> replace_variables_by_underscores
1043 in
1044 let is_private =
1045 match td.ptype_private with
1046 | Private -> true
1047 | Public -> false
1048 in
1049 if is_private
1050 then Location.raise_errorf ~loc "of_sexp is not supported for private type";
1051 let create_internal_function =
1052 match is_polymorphic_variant td ~sig_:false with
1053 | `Definitely -> true
1054 | `Maybe -> poly
1055 | `Surely_not ->
1056 if poly
1057 then
1058 Location.raise_errorf
1059 ~loc
1060 "sexp_poly annotation on a type that is surely not a polymorphic variant";
1061 false
1062 in
1063 let body ~error_source =
1064 let body =
1065 match td.ptype_kind with
1066 | Ptype_variant alts ->
1067 Attrs.fail_if_allow_extra_field_td ~loc td;
1068 sum_of_sexp ~error_source ~typevars td (td.ptype_loc, alts)
1069 | Ptype_record lbls ->
1070 record_of_sexp
1071 ~error_source
1072 ~typevars
1073 ~allow_extra_fields:
1074 (Option.is_some (Attribute.get Attrs.allow_extra_fields_td td))
1075 td
1076 (loc, lbls)
1077 | Ptype_open ->
1078 Location.raise_errorf ~loc "ppx_sexp_conv: open types not supported"
1079 | Ptype_abstract ->
1080 Attrs.fail_if_allow_extra_field_td ~loc td;
1081 (match td.ptype_manifest with
1082 | None -> nil_of_sexp ~error_source td.ptype_loc |> Lifted.return
1083 | Some ty ->
1084 type_of_sexp
1085 ~error_source
1086 ~full_type
1087 ~typevars
1088 ~internal:create_internal_function
1089 ty
1090 |> Lifted.return)
1091 in
1092 (* Prevent violation of value restriction, problems with recursive types, and
1093 toplevel effects by eta-expanding function definitions *)
1094 body >>| Conversion.to_value_expression ~loc ~rec_flag ~values_being_defined
1095 in
1096 let external_name = type_name ^ "_of_sexp" in
1097 let internal_name = "__" ^ type_name ^ "_of_sexp__" in
1098 let arg_patts, arg_exprs =
1099 List.unzip
1100 (List.map
1101 ~f:(fun tp ->
1102 let name = Map.find_exn typevars tp.txt in
1103 Fresh_name.pattern name, Fresh_name.expression name)
1104 tps)
1105 in
1106 let full_type_name = Printf.sprintf "%s.%s" path type_name in
1107 let internal_fun_body =
1108 if create_internal_function
1109 then
1110 Some
1111 (with_error_source ~loc ~full_type_name (fun ~error_source ->
1112 body ~error_source
1113 >>| fun body ->
1114 eta_reduce_if_possible_and_nonrec ~rec_flag (eabstract ~loc arg_patts body)))
1115 else None
1116 in
1117 let external_fun_body =
1118 let body_below_lambdas ~error_source =
1119 let fresh_sexp = Fresh_name.create "sexp" ~loc in
1120 if create_internal_function
1121 then (
1122 let no_variant_match_mc =
1123 [ [%pat? Sexplib0.Sexp_conv_error.No_variant_match]
1124 --> [%expr
1125 Sexplib0.Sexp_conv_error.no_matching_variant_found
1126 [%e error_source ()]
1127 [%e Fresh_name.expression fresh_sexp]]
1128 ]
1129 in
1130 let internal_call =
1131 let internal_expr = pexp_ident ~loc { loc; txt = Lident internal_name } in
1132 eapply ~loc internal_expr (arg_exprs @ [ Fresh_name.expression fresh_sexp ])
1133 in
1134 let try_with = pexp_try ~loc internal_call no_variant_match_mc in
1135 [%expr fun [%p Fresh_name.pattern fresh_sexp] -> [%e try_with]] |> Lifted.return)
1136 else body ~error_source
1137 in
1138 let body_with_lambdas ~error_source =
1139 body_below_lambdas ~error_source
1140 >>| fun body ->
1141 eta_reduce_if_possible_and_nonrec ~rec_flag (eabstract ~loc arg_patts body)
1142 in
1143 with_error_source ~loc ~full_type_name body_with_lambdas
1144 in
1145 let typ = Sig_generate_of_sexp.mk_type td in
1146 let mk_binding func_name body =
1147 constrained_function_binding loc td typ ~tps ~func_name body
1148 in
1149 let internal_bindings =
1150 match internal_fun_body with
1151 | None -> []
1152 | Some body -> [ mk_binding internal_name body ]
1153 in
1154 let external_binding = mk_binding external_name external_fun_body in
1155 internal_bindings, [ external_binding ]
1156 ;;
1157
1158 (* Generate code from type definitions *)
1159 let tds_of_sexp ~loc ~poly ~path (rec_flag, tds) =
1160 let tds = List.map ~f:name_type_params_in_td tds in
1161 let typevars td =
1162 List.fold
1163 td.ptype_params
1164 ~init:(Map.empty (module String))
1165 ~f:(fun map param ->
1166 let name = get_type_param_name param in
1167 Map.set
1168 map
1169 ~key:name.txt
1170 ~data:(Fresh_name.create ("_of_" ^ name.txt) ~loc:name.loc))
1171 in
1172 let singleton =
1173 match tds with
1174 | [ _ ] -> true
1175 | _ -> false
1176 in
1177 let values_being_defined =
1178 List.map tds ~f:(fun td -> td.ptype_name.txt ^ "_of_sexp")
1179 |> Set.of_list (module String)
1180 in
1181 if singleton
1182 then (
1183 let rec_flag = really_recursive_respecting_opaque rec_flag tds in
1184 match rec_flag with
1185 | Recursive ->
1186 let bindings =
1187 List.concat_map tds ~f:(fun td ->
1188 let typevars = typevars td in
1189 let internals, externals =
1190 td_of_sexp ~typevars ~loc ~poly ~path ~rec_flag ~values_being_defined td
1191 in
1192 internals @ externals)
1193 in
1194 pstr_value_list ~loc Recursive bindings
1195 | Nonrecursive ->
1196 List.concat_map tds ~f:(fun td ->
1197 let typevars = typevars td in
1198 let internals, externals =
1199 td_of_sexp ~typevars ~loc ~poly ~path ~rec_flag ~values_being_defined td
1200 in
1201 pstr_value_list ~loc Nonrecursive internals
1202 @ pstr_value_list ~loc Nonrecursive externals))
1203 else (
1204 let bindings =
1205 List.concat_map tds ~f:(fun td ->
1206 let typevars = typevars td in
1207 let internals, externals =
1208 td_of_sexp ~typevars ~poly ~loc ~path ~rec_flag ~values_being_defined td
1209 in
1210 internals @ externals)
1211 in
1212 pstr_value_list ~loc rec_flag bindings)
1213 ;;
1214
1215 let core_type_of_sexp ~path core_type =
1216 let loc = { core_type.ptyp_loc with loc_ghost = true } in
1217 let full_type_name =
1218 Printf.sprintf
1219 "%s line %i: %s"
1220 path
1221 loc.loc_start.pos_lnum
1222 (string_of_core_type core_type)
1223 in
1224 with_error_source ~loc ~full_type_name (fun ~error_source ->
1225 type_of_sexp ~error_source ~typevars:(Map.empty (module String)) core_type
1226 |> Conversion.to_value_expression
1227 ~loc
1228 ~rec_flag:Nonrecursive
1229 ~values_being_defined:(Set.empty (module String))
1230 |> Merlin_helpers.hide_expression
1231 |> Lifted.return)
1232 ;;
1233 end