Debian Codegraph @

README.org

raw
1 #+TITLE: ppx_sexp_conv
2
3 * [@@deriving sexp]
4
5 =ppx_sexp_conv= is a PPX syntax extension that generates code for
6 converting OCaml types to and from s-expressions, as defined in the
7 [[https://github.com/janestreet/sexplib][=sexplib=]] library. S-expressions are defined by the following type:
8
9 #+begin_src ocaml
10 type sexp = Atom of string | List of sexp list
11 #+end_src
12
13 and are rendered as parenthesized lists of strings, /e.g./ =(This (is
14 an) (s expression))=.
15
16 =ppx_sexp_conv= fits into the [[https://github.com/whitequark/ppx_deriving][=ppx_deriving=]] framework, so you can
17 invoke it the same way you invoke any other deriving plug-in. Thus,
18 we can write
19
20 #+begin_src ocaml
21 type int_pair = (int * int) [@@deriving sexp]
22 #+end_src
23
24 to get two values defined automatically, =sexp_of_int_pair= and
25 =int_pair_of_sexp=. If we only want one direction, we can write one
26 of the following.
27
28 #+begin_src ocaml
29 type int_pair = (int * int) [@@deriving sexp_of]
30 type int_pair = (int * int) [@@deriving of_sexp]
31 #+end_src
32
33 These sexp-converters depend on having a set of converters for basic
34 values (/e.g./, =int_of_sexp=) already in scope. This can be done by
35 writing:
36
37 #+begin_src ocaml
38 open Sexplib.Std
39 #+end_src
40
41 If you're using [[https://github.com/janestreet/core][=Core=]], you can get the same effect with =open Core=.
42
43 It's also possible to construct converters based on type expressions,
44 /i.e./:
45
46 #+begin_src ocaml
47 [%sexp_of: (int * string) list] [1,"one"; 2,"two"]
48 |> Sexp.to_string;;
49 => "((1 one) (2 two))"
50
51 [%sexp_of: (int * string) list] [1,"one"; 2,"two"]
52 |> [%of_sexp: (int * string) list];;
53 => [1,"one"; 2,"two"]
54 #+end_src
55
56 For =%sexp_of=, we can also omit the conversion of some types by
57 putting underscores for that type name.
58
59 #+begin_src ocaml
60 [%sexp_of: (int * _) list] [1,"one"; 2,"two"]
61 |> Sexp.to_string;;
62 => "((1 _)(2 _))"
63 #+end_src
64
65 * [@@deriving sexp_grammar]
66
67 If =ppx_sexp_conv= can derive =of_sexp=, it can also generate a description of
68 the sexps that the resulting =t_of_sexp= would accept. This is the sexp grammar.
69 See =Sexplib0.Sexp_grammar= for details. Use =[@@deriving sexp_grammar]= to derive
70 the grammar for a type.
71
72 It is possible to construct sexp grammars directly from type expressions, e.g.,
73
74 #+BEGIN_SRC ocaml
75 [%sexp_grammar: (int, bool array) Either.t Base.Map.M(String).t]
76 #+END_SRC
77
78 ** Tagging grammars
79
80 Use =[@sexp_grammar.tag key = value]=, where =(key : string)= and =(value :
81 Sexp.t)=, to annotate a grammar with a tag that can be inspected at runtime.
82
83 ** Custom grammars
84
85 Use =[@sexp_grammar.custom grammar]= to override a type's sexp grammar with
86 =grammar=.
87
88 ** Stub grammars
89
90 Annotate a type with =[@sexp_grammar.any]= to use a stub grammar that accepts
91 any sexp. Alternately, write =[@sexp_grammar.any desc]= where =(desc : string)=
92 to use =desc= as a human-readable description for the stub grammar.
93
94 * Conversion rules
95
96 In the following, we'll review the serialization rules for different
97 OCaml types.
98
99 ** Basic types
100
101 Basic types are represented as atoms. For numbers like =int=,
102 =int32=, =int64=, =float=, the string in the atom is what is accepted
103 the standard ocaml functions =int_of_string=, =Int32.of_string=, etc.
104 For the types =char= or =string=, the string in the atom is
105 respectively a one character string or the string itself.
106
107 ** Lists and arrays
108
109 OCaml-lists and arrays are represented as s-expression lists.
110
111 ** Tuples and unit
112
113 OCaml tuples are treated as lists of values in the same order as in
114 the tuple. The type =unit= is treated like a 0-tuple. /e.g./:
115
116 #+begin_src ocaml
117 (3.14, "foo", "bar bla", 27) => (3.14 foo "bar bla" 27)
118 #+end_src
119
120 ** Options
121
122 With options, =None= is treated as a zero-element list, and =Some= is
123 treated as a singleton list, as shown below.
124
125 #+begin_src ocaml
126 None => ()
127 Some value => (value)
128 #+end_src
129
130 We also support reading options following the ordinary rules for
131 variants /i.e./:
132
133 #+begin_src ocaml
134 None => None
135 Some value => (Some value)
136 #+end_src
137
138 The rules for variants are described below.
139
140 ** Records
141
142 Records are represented as lists of lists, where each inner list is a
143 key-value pair. Each pair consists of the name of the record field
144 (first element), and its value (second element). /e.g./:
145
146 #+begin_src ocaml
147 { foo = (3,4);
148 bar = "some string"; }
149 => ((foo (3 4)) (bar "some string"))
150 #+end_src
151
152 Type specifications of records allow the use of several attributes. The
153 attribute =sexp.option= indicates that a record field should be optional.
154 /e.g./:
155
156 #+begin_src ocaml
157 type t =
158 { x : int option;
159 y : int option [@sexp.option];
160 } [@@deriving sexp]
161 #+end_src
162
163 The following examples show how this works.
164
165 #+begin_src ocaml
166 { x = Some 1; y = Some 2; } => ((x (1)) (y 2))
167 { x = None ; y = None; } => ((x ()))
168 #+end_src
169
170 Note that, when present, an optional value is represented as the bare
171 value, rather than explicitly as an option.
172
173 The attribute =sexp.bool= indicates that a boolean record field is shown
174 as either present or absent, but not as containing a value.
175
176 #+begin_src ocaml
177 type t = { enabled : bool [@sexp.bool] } [@@deriving sexp]
178
179 { enabled = true } => ((enabled))
180 { enabled = false } => ()
181 #+end_src
182
183 The attributes =sexp.list= and =sexp.array= indicate that a list or array record
184 field, respectively, can be omitted when it is empty.
185
186 #+begin_src ocaml
187 type t =
188 { arr : int array [@sexp.array]
189 ; lst : int list [@sexp.list]
190 }
191 [@@deriving sexp]
192
193 { arr = [||]; lst = [] } => ()
194 { arr = [|1;2|]; lst = [3;4] } => ((arr (1 2)) (lst (3 4)))
195 #+end_src
196
197 *** Defaults
198
199 More complex default values can be specified explicitly using several
200 constructs, /e.g./:
201
202 #+begin_src ocaml
203 type t =
204 { a : int [@default 42];
205 b : int [@default 3] [@sexp_drop_default (=)];
206 c : int [@default 3] [@sexp_drop_if fun x -> x = 3];
207 d : int Queue.t [@sexp.omit_nil]
208 } [@@deriving sexp]
209 #+end_src
210
211 The =@default= annotation lets one specify a default value to be
212 selected if the field is not specified, when converting from an
213 s-expression. The =@sexp_drop_default= annotation implies that the
214 field will be dropped when generating the s-expression if the value
215 being serialized is equal to the default according to the specified equality
216 function. =@sexp_drop_if= is like =@sexp_drop_default=, except that
217 it lets you specify the condition under which the field is dropped.
218 Finally, [email protected]_nil= means to treat a missing field as if it
219 has value =List []= when reading, and drop the field if it has value
220 =List []= when writing.
221
222 **** Specifying equality for [@sexp_drop_default]
223
224 The equality used by [@sexp_drop_default] is customizable. There
225 are several ways to specify the equality function:
226
227 #+begin_src ocaml
228 type t =
229 { a : u [@default u0] [@sexp_drop_default (=)]; (* explicit user-provided function *)
230 b : u [@default u0] [@sexp_drop_default.compare]; (* uses [%compare.equal: u] *)
231 c : u [@default u0] [@sexp_drop_default.equal]; (* uses [%equal: u] *)
232 d : u [@default u0] [@sexp_drop_default.sexp]; (* compares sexp representations *)
233 e : u [@default u0] [@sexp_drop_default]; (* deprecated. uses polymorphic equality. *)
234 } [@@deriving sexp]
235 #+end_src
236
237 *** Allowing extra fields
238
239 The [email protected]_extra_fields= annotation lets one specify that the
240 sexp-converters should silently ignore extra fields, instead of
241 raising. This applies only to the record to which the annotation is
242 attached, and not to deeper sexp converters that may be called during
243 conversion of a sexp to the record.
244
245 #+begin_src ocaml
246 type t = { a: int } [@@deriving sexp]
247 ((a 0)(b b)) => exception
248
249 type t = { a: int } [@@deriving sexp] [@@sexp.allow_extra_fields]
250 ((a 0)(b b)) => {a = 0}
251
252 type t = A of { a : int } [@sexp.allow_extra_fields] [@@deriving sexp]
253 (A (a 0)(b b)) => A {a = 0}
254 #+end_src
255
256 ** Variants
257
258 Constant constructors in variants are represented as
259 strings. Constructors with arguments are represented as lists, the
260 first element being the constructor name, the rest being its
261 arguments. Constructors may also be started in lowercase in
262 S-expressions, but will always be converted to uppercase when
263 converting from OCaml values.
264
265 For example:
266
267 #+begin_src ocaml
268 type t = A | B of int * float * t [@@deriving sexp]
269 B (42, 3.14, B (-1, 2.72, A)) => (B 42 3.14 (B -1 2.72 A))
270 #+end_src
271
272 The above example also demonstrates recursion in data structures.
273
274 Variants support the attribute =sexp.list= when a clause has a single
275 list as its argument.
276
277 #+begin_src ocaml
278 type t =
279 | A of int list
280 | B of int list [@sexp.list]
281
282 A [1; 2; 3] => (A (1 2 3))
283 B [1; 2; 3] => (B 1 2 3)
284 #+end_src
285
286 *** Inline records
287
288 Constructors with inline records are represented as lists, the first element
289 being the constructor name, the rest being the record fields, represented the
290 same way as in record types, but without being wrapped in an extra layer of
291 parentheses.
292
293 #+begin_src ocaml
294 type t = A of { x : int }
295
296 A { x = 8 } => (A (x 8))
297 #+end_src
298
299 ** Polymorphic variants
300
301 Polymorphic variants behave almost the same as ordinary variants. The
302 notable difference is that polymorphic variant constructors must
303 always start with an either lower- or uppercase character, matching
304 the way it was specified in the type definition. This is because
305 OCaml distinguishes between upper and lowercase variant
306 constructors. Note that type specifications containing unions of
307 variant types are also supported by the S-expression converter, for
308 example as in:
309
310 #+begin_src ocaml
311 type ab = [ `A | `B ] [@@deriving sexp]
312 type cd = [ `C | `D ] [@@deriving sexp]
313 type abcd = [ ab | cd ] [@@deriving sexp]
314 #+end_src
315
316 However, because `ppx_sexp_conv` needs to generate additional code to
317 support inclusions of polymorphic variants, `ppx_sexp_conv` needs to
318 know when processing a type definition whether it might be included in
319 a polymorphic variant. `ppx_sexp_conv` will only generate the extra
320 code automatically in the common case where the type definition is
321 syntactically a polymorphic variant like in the example
322 above. Otherwise, you will need to indicate it by using `[@@deriving
323 sexp_poly]` (resp `of_sexp_poly`) instead of `[@@deriving sexp]` (resp
324 `of_sexp`):
325
326 #+begin_src ocaml
327 type ab = [ `A | `B ] [@@deriving sexp]
328 type alias_of_ab = ab [@@deriving sexp_poly]
329 type abcd = [ ab | `C | `D ] [@@deriving sexp]
330 #+end_src
331
332 ** Polymorphic values
333
334 There is nothing special about polymorphic values as long as there are
335 conversion functions for the type parameters. /e.g./:
336
337 #+begin_src ocaml
338 type 'a t = A | B of 'a [@@deriving sexp]
339 type foo = int t [@@deriving sexp]
340 #+end_src
341
342 In the above case the conversion functions will behave as if =foo= had
343 been defined as a monomorphic version of =t= with ='a= replaced by
344 =int= on the right hand side.
345
346 If a data structure is indeed polymorphic and you want to convert it,
347 you will have to supply the conversion functions for the type
348 parameters at runtime. If you wanted to convert a value of type ='a
349 t= as in the above example, you would have to write something like
350 this:
351
352 #+begin_src ocaml
353 sexp_of_t sexp_of_a v
354 #+end_src
355
356 where =sexp_of_a=, which may also be named differently in this
357 particular case, is a function that converts values of type ='a= to an
358 S-expression. Types with more than one parameter require passing
359 conversion functions for those parameters in the order of their
360 appearance on the left hand side of the type definition.
361
362 ** Opaque values
363
364 Opaque values are ones for which we do not want to perform
365 conversions. This may be, because we do not have S-expression
366 converters for them, or because we do not want to apply them in a
367 particular type context. /e.g./ to hide large, unimportant parts of
368 configurations. To prevent the preprocessor from generating calls to
369 converters, simply apply the attribute =sexp.opaque= to the type. If the type
370 is for a record field, it will likely need parentheses to avoid applying the
371 attribute to the record field itself, /e.g./:
372
373 #+begin_src ocaml
374 type foo = int * (stuff [@sexp.opaque]) [@@deriving sexp]
375
376 type bar =
377 { a : int
378 ; b : (stuff [@sexp.opaque])
379 }
380 [@@deriving sexp]
381 #+end_src
382
383 Thus, there is no need to specify converters for type =stuff=, and if
384 there are any, they will not be used in this particular context.
385 Needless to say, it is not possible to convert such an S-expression
386 back to the original value. Here is an example conversion:
387
388 #+begin_src ocaml
389 (42, some_stuff) => (42 <opaque>)
390 #+end_src
391
392 ** Exceptions
393
394 S-expression converters for exceptions can be automatically
395 registered.
396
397 #+begin_src ocaml
398 module M = struct
399 exception Foo of int [@@deriving sexp]
400 end
401 #+end_src
402
403 Such exceptions will be translated in a similar way as sum types, but
404 their constructor will be prefixed with the fully qualified module
405 path (here: =M.Foo=) so as to be able to discriminate between them
406 without problems.
407
408 The user can then easily convert an exception matching the above one
409 to an S-expression using =sexp_of_exn=. User-defined conversion
410 functions can be registered, too, by calling =add_exn_converter=.
411 This should make it very convenient for users to catch arbitrary
412 exceptions escaping their program and pretty-printing them, including
413 all arguments, as S-expressions. The library already contains
414 mappings for all known exceptions that can escape functions in the
415 OCaml standard library.
416
417 ** Hash tables
418
419 The Stdlib's Hash tables, which are abstract values in OCaml, are
420 represented as association lists, /i.e./ lists of key-value pairs,
421 /e.g./:
422
423 #+begin_src scheme
424 ((foo 42) (bar 3))
425 #+end_src
426
427 Reading in the above S-expression as hash table mapping strings to
428 integers (=(string, int) Hashtbl.t=) will map =foo= to =42= and =bar=
429 to =3=.
430
431 Note that the order of elements in the list may matter, because the
432 OCaml-implementation of hash tables keeps duplicates. Bindings will
433 be inserted into the hash table in the order of appearance. Therefore,
434 the last binding of a key will be the "visible" one, the others are
435 "hidden". See the OCaml documentation on hash tables for details.
436
437 * A note about signatures
438
439 In signatures, =ppx_sexp_conv= tries to generate an include of a named
440 interface, instead of a list of value bindings.
441 That is:
442
443 #+begin_src ocaml
444 type 'a t [@@deriving sexp]
445 #+end_src
446
447 will generate:
448
449 #+begin_src ocaml
450 include Sexpable.S1 with type 'a t := 'a t
451 #+end_src
452
453 instead of:
454
455 #+begin_src ocaml
456 val t_of_sexp : (Sexp.t -> 'a) -> Sexp.t -> 'a t
457 val sexp_of_t : ('a -> Sexp.t) -> 'a t -> Sexp.t
458 #+end_src
459
460 There are however a number of limitations:
461 - the type has to be named t
462 - the type can only have up to 3 parameters
463 - there shouldn't be any constraint on the type parameters
464
465 If these aren't met, then =ppx_sexp_conv= will simply generate a list of value
466 bindings.
467
468 ** Weird looking type errors
469
470 In some cases, a type can meet all the conditions listed above, in which case the
471 rewriting will apply, but lead to a type error. This happens when the type [t]
472 is an alias to a type which does have constraints on the parameters, for
473 instance:
474
475 #+begin_src ocaml
476 type 'a s constraint 'a = [> `read ]
477 val sexp_of_s : ...
478 val s_of_sexp : ...
479 type 'a t = 'a s [@@deriving_inline sexp]
480 include Sexpable.S1 with type 'a t := 'a t
481 [@@@end]
482 #+end_src
483
484 will give an error looking like:
485
486 #+begin_src
487 Error: In this `with' constraint, the new definition of t
488 does not match its original definition in the constrained signature:
489 Type declarations do not match:
490 type 'a t = 'a t constraint 'a = [> `read ]
491 is not included in
492 type 'a t
493 File "sexpable.mli", line 8, characters 21-58: Expected declaration
494 Their constraints differ.
495 #+end_src
496
497 To workaround that error, simply copy the constraint on the type which has the
498 =[@@deriving]= annotation. This will force generating a list of value bindings.
499
500 * Deprecated syntax
501
502 Originally, ~ppx_sexp_conv~ used special types instead of attributes. Those
503 types have been replaced with attributes. Here are the appropriate conversions
504 to update from code using the old types to the new attributes.
505
506
507 ** Opaque types
508
509 Convert uses of ~sexp_opaque~ to uses of ~[@sexp.opaque]~. The ~[@sexp.opaque]~
510 attribute usually needs explicit parentheses to clarify what type it annotate.
511
512 Before:
513
514 #+begin_src ocaml
515 type t = int sexp_opaque list
516 [@@deriving sexp]
517 #+end_src
518
519 After:
520
521 #+begin_src ocaml
522 type t = (int [@sexp.opaque]) list
523 [@@deriving sexp]
524 #+end_src
525
526 ** Record fields
527
528 Convert uses of ~sexp_option~, ~sexp_list~, ~sexp_array~, and ~sexp_bool~ to
529 uses of ~[@sexp.option]~, ~[@sexp.list]~, ~[@sexp.array]~, and ~[@sexp.bool]~ as
530 appropriate. The attribute only specifies the modification, not the type, so you
531 will need to use the regular types ~option~, ~list~, ~array~, and/or ~bool~ as
532 well. Unlike ~[@sexp.opaque]~, these attributes do not need extra parentheses.
533
534 Before:
535
536 #+begin_src ocaml
537 type t =
538 { a : int sexp_option
539 ; b : int sexp_list
540 ; c : int sexp_array
541 ; d : sexp_bool
542 }
543 [@@deriving sexp]
544 #+end_src
545
546 After:
547
548 #+begin_src ocaml
549 type t =
550 { a : int option [@sexp.option]
551 ; b : int list [@sexp.list]
552 ; c : int array [@sexp.array]
553 ; d : bool [@sexp.bool]
554 }
555 [@@deriving sexp]
556 #+end_src
557
558 ** Variant constructors
559
560 Convert uses of ~sexp_list~ in variants and polymorphic variants to uses of
561 ~[@sexp.list]~. You need to add the regular type ~list~ as well. Unlike
562 ~[@sexp.opaque]~, this attribute does not need extra parentheses.
563
564 Before:
565
566 #+begin_src ocaml
567 type t = A of int sexp_list
568 [@@deriving sexp]
569
570 type u = [`B of int sexp_list]
571 [@@deriving sexp]
572 #+end_src
573
574 After:
575
576 #+begin_src ocaml
577 type t = A of int list [@sexp.list]
578 [@@deriving sexp]
579
580 type u = [`B of int list [@sexp.list]]
581 [@@deriving sexp]
582 #+end_src