-
Notifications
You must be signed in to change notification settings - Fork 1
/
atdgen-tutorial-body.mlx
1068 lines (853 loc) · 27.3 KB
/
atdgen-tutorial-body.mlx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
% -*- latex -*-
##
#use "topfind";;
#require "caml2html";;
#require "atd";;
#require "unix";;
#use "macros.ml";;
##
\section{What is Atdgen?}
Atdgen is a tool that derives OCaml boilerplate code from type definitions.
Currently it provides support for:
\begin{itemize}
\item \href{http://json.org/}{JSON} serialization and deserialization.
\item \href{http://martin.jambon.free.fr/biniou-format.txt}{Biniou}
serialization and deserialization.
Biniou is a binary format extensible like JSON but more compact
and faster to process.
\item Convenience functions for creating and validating OCaml data.
\end{itemize}
\section{What are the advantages of Atdgen?}
Atdgen has a number of advantages over its predecessor json-static
which was based on Camlp4:
\begin{itemize}
\item produces explicit interfaces which describe what is available to
the user (\texttt{.mli} files).
\item produces readable OCaml code that can be easily reviewed
(\texttt{.ml} files).
\item produces fast code, 3x faster than json-static.
\item runs fast, keeping build times low.
\item same ATD definitions can be used to generate code other than
OCaml. See for instance
\href{https://github.com/MyLifeLabs/atdj}{Atdj}
which generates Java classes for JSON IO.
Auto-generating GUI widgets from type definitions is another
popular use of annotated type definitions. The implementation of
such code generators is facilitated by the
\href{http://oss.wink.com/atd/}{\texttt{atd}} library.
\end{itemize}
\section{Prerequisites}
This tutorial assumes that you are using Atdgen version 1.2.0 or above.
The following command tells you which version you are using:
\begin{verbatim}
$ atdgen -version
1.2.0
\end{verbatim}
A quick way of installing Atdgen and all its dependencies is via Godi.
Alternatively, read and follow the instructions in the
\texttt{INSTALL} file of the source package of Atdgen.
\section{Getting started}
From now on we assume that Atdgen 1.2.0 or above is installed properly.
\begin{verbatim}
$ atdgen -version
1.2.0
\end{verbatim}
Type definitions are placed in a \texttt{.atd} file (\texttt{hello.atd}):
## ocaml () ##
type date = {
year : int;
month : int;
day : int;
}
## () ##
Our handwritten OCaml program is \texttt{hello.ml}:
## ocaml () ##
open Hello_t
let () =
let date = { year = 1970; month = 1; day = 1 } in
print_endline (Hello_j.string_of_date date)
## () ##
We produce OCaml code from the type definitions using \texttt{atdgen}:
\begin{verbatim}
$ atdgen -t hello.atd # produces OCaml type definitions
$ atdgen -j hello.atd # produces OCaml code dealing with JSON
\end{verbatim}
We now have \texttt{\_t} and \texttt{\_j} files produced by \texttt{atdgen -t} and \texttt{atdgen -j}
respectively:
\begin{verbatim}
$ ls
hello.atd hello.ml hello_j.ml hello_j.mli hello_t.ml hello_t.mli
\end{verbatim}
We compile all \texttt{.mli} and \texttt{.ml} files:
\begin{verbatim}
$ ocamlfind ocamlc -c hello_t.mli -package atdgen
$ ocamlfind ocamlc -c hello_j.mli -package atdgen
$ ocamlfind ocamlopt -c hello_t.ml -package atdgen
$ ocamlfind ocamlopt -c hello_j.ml -package atdgen
$ ocamlfind ocamlopt -c hello.ml -package atdgen
$ ocamlfind ocamlopt -o hello hello_t.cmx hello_j.cmx hello.cmx \
-package atdgen -linkpkg
\end{verbatim}
And finally we run our \texttt{hello} program:
\begin{verbatim}
$ ./hello
{"year":1970,"month":1,"day":1}
\end{verbatim}
Source code for this section:
\url{https://github.com/MyLifeLabs/atdgen-tutorial/tree/master/hello}
\section{Inspecting and pretty-printing JSON}
Input JSON data:
\begin{verbatim}
$ cat single.json
[1234,"abcde",{"start_date":{"year":1970,"month":1,"day":1},
"end_date":{"year":1980,"month":1,"day":1}}]
\end{verbatim}
Pretty-printed JSON can be produced with the \texttt{ydump} command:
\begin{verbatim}
$ ydump single.json
[
1234,
"abcde",
{
"start_date": { "year": 1970, "month": 1, "day": 1 },
"end_date": { "year": 1980, "month": 1, "day": 1 }
}
]
\end{verbatim}
Multiple JSON objects separated by whitespace, typically one JSON object
per line, can also be pretty-printed with \texttt{ydump}. Input:
\begin{verbatim}
$ cat stream.json
[1234,"abcde",{"start_date":{"year":1970,"month":1,"day":1},
"end_date":{"year":1980,"month":1,"day":1}}]
[1,"a",{}]
\end{verbatim}
In this case the \texttt{-s} option is required:
\begin{verbatim}
$ ydump -s stream.json
[
1234,
"abcde",
{
"start_date": { "year": 1970, "month": 1, "day": 1 },
"end_date": { "year": 1980, "month": 1, "day": 1 }
}
]
[ 1, "a", {} ]
\end{verbatim}
From an OCaml program, pretty-printing can be done with
\texttt{Yojson.Safe.prettify}
which has the following signature:
## ocaml () ##
val prettify : string -> string
## () ##
We wrote a tiny program that simply calls the \texttt{prettify} function on
some predefined JSON data (file \texttt{prettify.ml}):
## ocaml () ##
let json =
"[1234,\"abcde\",{\"start_date\":{\"year\":1970,\"month\":1,\"day\":1},
\"end_date\":{\"year\":1980,\"month\":1,\"day\":1}}]"
let () = print_endline (Yojson.Safe.prettify json)
## () ##
We now compile and run prettify.ml:
\begin{verbatim}
$ ocamlfind ocamlopt -o prettify prettify.ml -package atdgen -linkpkg
$ ./prettify
[
1234,
"abcde",
{
"start_date": { "year": 1970, "month": 1, "day": 1 },
"end_date": { "year": 1980, "month": 1, "day": 1 }
}
]
\end{verbatim}
Source code for this section:
\url{https://github.com/MyLifeLabs/atdgen-tutorial/tree/master/pretty-json}
\section{Inspecting biniou data}
Biniou is a binary format that can be displayed as text using a generic
command called \texttt{bdump}. The only practical difficulty is to recover
the original field names and variant names which are stored as 31-bit hashes.
Unhashing them is done by consulting a dictionary (list of words)
maintained by the user.
Let's first produce a sample data file \texttt{tree.dat} containing the
biniou representation of a binary tree. In the same program
we will also demonstrate how to render biniou data into text from an
OCaml program.
Here is the ATD file defining our tree type (file \texttt{tree.atd}):
## atd () ##
type tree =
[ Empty
| Node of (tree * int * tree) ]
## () ##
This is our OCaml program (file \texttt{tree.ml}):
## ocaml () ##
open Printf
(* sample value *)
let tree : Tree_t.tree =
`Node (
`Node (`Empty, 1, `Empty),
2,
`Node (
`Node (`Empty, 3, `Empty),
4,
`Node (`Empty, 5, `Empty)
)
)
let () =
(* write sample value to file *)
let fname = "tree.dat" in
Ag_util.Biniou.to_file Tree_b.write_tree fname tree;
(* write sample value to string *)
let s = Tree_b.string_of_tree tree in
printf "raw value (saved as %s):\n%S\n" fname s;
printf "length: %i\n" (String.length s);
printf "pretty-printed value (without dictionary):\n";
print_endline (Bi_io.view s);
printf "pretty-printed value (with dictionary):\n";
let unhash = Bi_io.make_unhash ["Empty"; "Node"; "foo"; "bar" ] in
print_endline (Bi_io.view ~unhash s)
## () ##
Compilation:
\begin{verbatim}
$ atdgen -t tree.atd
$ atdgen -b tree.atd
$ ocamlfind ocamlopt -o tree \
tree_t.mli tree_t.ml tree_b.mli tree_b.ml tree.ml \
-package atdgen -linkpkg
\end{verbatim}
Running the program:
\begin{verbatim}
$ ./tree
raw value (saved as tree.dat):
"\023\179\2276\"\020\003\023\179\2276\"\020\003\023\003\007\170m\017\002\023\003\007\170m\017\004\023\179\2276\"\020\003\023\179\2276\"\020\003\023\003\007\170m\017\006\023\003\007\170m\017\b\023\179\2276\"\020\003\023\003\007\170m\017\n\023\003\007\170m"
length: 75
pretty-printed value (without dictionary):
<#33e33622:
(<#33e33622: (<#0307aa6d>, 1, <#0307aa6d>)>,
2,
<#33e33622:
(<#33e33622: (<#0307aa6d>, 3, <#0307aa6d>)>,
4,
<#33e33622: (<#0307aa6d>, 5, <#0307aa6d>)>)>)>
pretty-printed value (with dictionary):
<"Node":
(<"Node": (<"Empty">, 1, <"Empty">)>,
2,
<"Node":
(<"Node": (<"Empty">, 3, <"Empty">)>,
4,
<"Node": (<"Empty">, 5, <"Empty">)>)>)>
\end{verbatim}
Now let's see how to pretty-print any biniou data from the command line.
Our sample data are now in file \texttt{tree.dat}:
\begin{verbatim}
$ ls -l tree.dat
-rw-r--r-- 1 martin martin 75 Apr 17 01:46 tree.dat
\end{verbatim}
We use the command \texttt{bdump} to render our sample biniou data as text:
\begin{verbatim}
$ bdump tree.dat
<#33e33622:
(<#33e33622: (<#0307aa6d>, 1, <#0307aa6d>)>,
2,
<#33e33622:
(<#33e33622: (<#0307aa6d>, 3, <#0307aa6d>)>,
4,
<#33e33622: (<#0307aa6d>, 5, <#0307aa6d>)>)>)>
\end{verbatim}
We got hashes for the variant names \texttt{Empty} and \texttt{Node}.
Let's add them to the dictionary:
\begin{verbatim}
$ bdump -w Empty,Node tree.dat
<"Node":
(<"Node": (<"Empty">, 1, <"Empty">)>,
2,
<"Node":
(<"Node": (<"Empty">, 3, <"Empty">)>,
4,
<"Node": (<"Empty">, 5, <"Empty">)>)>)>
\end{verbatim}
\texttt{bdump} remembers the dictionary so we don't have to pass the
\texttt{-w} option anymore (for this user on this machine).
The following now works:
\begin{verbatim}
$ bdump tree.dat
<"Node":
(<"Node": (<"Empty">, 1, <"Empty">)>,
2,
<"Node":
(<"Node": (<"Empty">, 3, <"Empty">)>,
4,
<"Node": (<"Empty">, 5, <"Empty">)>)>)>
\end{verbatim}
Source code for this section:
\url{https://github.com/MyLifeLabs/atdgen-tutorial/tree/master/inspect-biniou}
\section{\label{defaults}Optional fields and default values}
Although OCaml records do not support optional fields, both the JSON
and biniou formats make it possible to omit certain fields on a
per-record basis.
For example the JSON record \texttt{\{ "x": 0, "y": 0 \}} can be more
compactly written as \texttt{\{\}} if the reader knows the default values for
the missing fields \texttt{x} and \texttt{y}. Here is the corresponding type
definition:
## atd () ##
type vector_v1 = { ~x: int; ~y: int }
## () ##
\texttt{\~{}x} means that field \texttt{x} supports a default
value. Since we do not
specify the default value ourselves, the built-in default is used,
which is 0.
If we want the default to be something else than 0, we just have to
specify it as follows:
## atd () ##
type vector_v2 = {
~x <ocaml default="1">: int; (* default x is 1 *)
~y: int; (* default y is 0 *)
}
## () ##
It is also possible to specify optional fields without a default
value. For example, let's add an optional \texttt{z} field:
## atd () ##
type vector_v3 = {
~x: int;
~y: int;
?z: int option;
}
## () ##
The following two examples are valid JSON representations of data of
type \texttt{vector\_v3}:
\begin{verbatim}
{ "x": 2, "y": 2, "z": 3 } // OCaml: { x = 2; y = 2; z = Some 3 }
\end{verbatim}
\begin{verbatim}
{ "x": 2, "y": 2 } // OCaml: { x = 2; y = 2; z = None }
\end{verbatim}
For a variety of good reasons JSON's \texttt{null} value may not be used to
indicate that a field is undefined.
Therefore the following JSON data cannot be read as a record of type
\texttt{vector\_v3}:
\begin{verbatim}
{ "x": 2, "y": 2, "z": null } // invalid value for field z
\end{verbatim}
Note also the difference between \texttt{?z: int option} and \texttt{\~{}z: int
option}:
## atd () ##
type vector_v4 = {
~x: int;
~y: int;
~z: int option; (* no unwrapping of the JSON field value! *)
}
## () ##
Here are valid values of type \texttt{vector\_v4}, showing that it is usually
not what is intended:
\begin{verbatim}
{ "x": 2, "y": 2, "z": [ "Some", 3 ] }
\end{verbatim}
\begin{verbatim}
{ "x": 2, "y": 2, "z": "None" }
\end{verbatim}
\begin{verbatim}
{ "x": 2, "y": 2 }
\end{verbatim}
\section{Smooth protocol upgrades}
Problem: you have a production system that uses a specific
JSON or biniou format. It may be data files or a client-server
pair. You now want to add a field to a record type or to add a case to
a variant type.
Both JSON and biniou allow extra record fields. If the
consumer does not know how to deal with the extra field, the default
behavior is to happily ignore it.
\subsection{Adding or removing an optional record field}
## atd () ##
type t = {
x: int;
y: int;
}
## () ##
Same \texttt{.atd} source file, edited:
## atd () ##
type t = {
x: int;
y: int;
~z: int; (* new field *)
}
## () ##
\begin{itemize}
\item Upgrade producers and consumers in any order
\item Converting old data is not required nor useful
\end{itemize}
\subsection{Adding a required record field}
## atd () ##
type t = {
x: int;
y: int;
}
## () ##
Same \texttt{.atd} source file, edited:
## atd () ##
type t = {
x: int;
y: int;
z: int; (* new field *)
}
## () ##
\begin{itemize}
\item Upgrade all producers before the consumers
\item Converting old data requires special-purpose hand-written code
\end{itemize}
\subsection{Removing a required record field}
\begin{itemize}
\item Upgrade all consumers before the producers
\item Converting old data is not required but may save some storage space
(just read and re-write each record using the new type)
\end{itemize}
\subsection{Adding a variant case}
## atd () ##
type t = [ A | B ]
## () ##
Same \texttt{.atd} source file, edited:
## atd () ##
type t = [ A | B | C ]
## () ##
\begin{itemize}
\item Upgrade all consumers before the producers
\item Converting old data is not required and would have no effect
\end{itemize}
\subsection{Removing a variant case}
\begin{itemize}
\item Upgrade all producers before the consumers
\item Converting old data requires special-purpose hand-written code
\end{itemize}
\subsection{Avoiding future problems}
\begin{itemize}
\item In doubt, use records rather than tuples because it makes it
possible to add or remove any field or to reorder them.
\item Do not hesitate to create variant types with only one case or
records with only one field if you think they might be extended
later.
\end{itemize}
\section{Data validation}
Atdgen can be used to produce data validators for all types defined
in an ATD file,
based on user-given validators specified only for certain types.
A simple example is:
## atd () ##
type t = string <ocaml validator="fun s -> String.length s >= 8"> option
## () ##
\texttt{atdgen -v} will produce something equivalent to the following
implementation:
## ocaml () ##
let validate_t x =
match x with
None -> true
| Some x -> (fun s -> String.length s >= 8) x
## () ##
Let's now consider a more realistic example with complex validators defined
in a separate .ml file. We created the following 3 source files:
\begin{itemize}
\item \texttt{resume.atd}: contains the type definitions with annotations
\item \texttt{resume\_util.ml}: contains our handwritten validators
\item \texttt{resume.ml}: is our main program that creates data and
calls the validators
\end{itemize}
In terms of OCaml modules we have:
\begin{itemize}
\item \texttt{Resume\_t}: produced by \texttt{atdgen -t resume.atd},
provides OCaml type definitions
\item \texttt{Resume\_util}: depends on \texttt{Resume\_t}, provides
validators mentioned in \texttt{resume.atd}
\item \texttt{Resume\_v}: produced by \texttt{atdgen -v resume.atd},
depends on \texttt{Resume\_util}, provides a validator for each type
\item \texttt{Resume}: depends on \texttt{Resume\_v}, uses the validators
\end{itemize}
Type definitions are placed in \texttt{resume.atd}:
## atd () ##
type text = string <ocaml validator="Resume_util.validate_some_text">
type date = {
year : int;
month : int;
day : int;
} <ocaml validator="Resume_util.validate_date">
type job = {
company : text;
title : text;
start_date : date;
?end_date : date option;
} <ocaml validator="Resume_util.validate_job">
type work_experience = job list
## () ##
\texttt{resume\_util.ml} contains our handwritten validators:
## ocaml () ##
open Resume_t
let ascii_printable c =
let n = Char.code c in
n >= 32 && n <= 127
(*
Check that string is not empty and contains only ASCII printable
characters (for the sake of the example; we use UTF-8 these days)
*)
let validate_some_text s =
s <> "" &&
try
String.iter (fun c -> if not (ascii_printable c) then raise Exit) s;
true
with Exit ->
false
(*
Check that the combination of year, month and day exists in the
Gregorian calendar.
*)
let validate_date x =
let y = x.year in
let m = x.month in
let d = x.day in
m >= 1 && m <= 12 && d >= 1 &&
(let dmax =
match m with
2 ->
if y mod 4 = 0 && not (y mod 100 = 0) || y mod 400 = 0 then 29
else 28
| 1 | 3 | 5 | 7 | 8 | 10 | 12 -> 31
| _ -> 30
in
d <= dmax)
(* Compare dates chronologically *)
let compare_date a b =
let c = compare a.year b.year in
if c <> 0 then c
else
let c = compare a.month b.month in
if c <> 0 then c
else compare a.day b.day
(* Check that the end_date, when defined, is not earlier than the start_date *)
let validate_job x =
match x.end_date with
None -> true
| Some end_date ->
compare_date x.start_date end_date <= 0
## () ##
\texttt{resume.ml} uses the \texttt{validate\_work\_experience}
function provided by the \texttt{Resume\_v} module:
## ocaml () ##
let check_experience x =
let is_valid = Resume_v.validate_work_experience x in
Printf.printf "%s:\n%s\n"
(if is_valid then "VALID" else "INVALID")
(Yojson.Safe.prettify (Resume_j.string_of_work_experience x))
let () =
(* one valid date *)
let valid = { Resume_t.year = 2000; month = 2; day = 29 } in
(* one invalid date *)
let invalid = { Resume_t.year = 1900; month = 0; day = 0 } in
(* two more valid dates, created with Resume_v.create_date *)
let date1 = { Resume_t.year = 2005; month = 8; day = 1 } in
let date2 = { Resume_t.year = 2006; month = 3; day = 22 } in
let job = {
Resume_t.company = "Acme Corp.";
title = "Tester";
start_date = date1;
end_date = Some date2;
}
in
let valid_job = { job with Resume_t.start_date = valid } in
let invalid_job = { job with Resume_t.end_date = Some invalid } in
let valid_experience = [ job; valid_job ] in
let invalid_experience = [ job; invalid_job ] in
check_experience valid_experience;
check_experience invalid_experience
## () ##
Output:
\begin{verbatim}
VALID:
[
{
"company": "Acme Corp.",
"title": "Tester",
"start_date": { "year": 2005, "month": 8, "day": 1 },
"end_date": { "year": 2006, "month": 3, "day": 22 }
},
{
"company": "Acme Corp.",
"title": "Tester",
"start_date": { "year": 2000, "month": 2, "day": 29 },
"end_date": { "year": 2006, "month": 3, "day": 22 }
}
]
INVALID:
[
{
"company": "Acme Corp.",
"title": "Tester",
"start_date": { "year": 2005, "month": 8, "day": 1 },
"end_date": { "year": 2006, "month": 3, "day": 22 }
},
{
"company": "Acme Corp.",
"title": "Tester",
"start_date": { "year": 2005, "month": 8, "day": 1 },
"end_date": { "year": 1900, "month": 0, "day": 0 }
}
]
\end{verbatim}
Source code for this section:
\url{https://github.com/MyLifeLabs/atdgen-tutorial/tree/master/validate}
\section{Modularity: referring to type definitions from another ATD file}
It is possible to define types that depend on types
defined in other \texttt{.atd} files.
The example below is self-explanatory.
\texttt{part1.atd}:
## atd () ##
type t = { x : int; y : int }
## () ##
\texttt{part2.atd}:
## atd () ##
type t1 <ocaml from="Part1" t="t"> = abstract
(*
Imports type t defined in file part1.atd.
The local name is t1. Because the local name (t1) is different from the
original name (t), we must specify the original name using t=.
*)
type t2 = t1 list
## () ##
\texttt{part3.atd}:
## atd () ##
type t2 <ocaml from="Part2"> = abstract
type t3 = {
name : string;
?data : t2 option;
}
## () ##
\texttt{main.ml}:
## ocaml () ##
let v = {
Part3_t.name = "foo";
data = Some [
{ Part1_t.x = 1; y = 2 };
{ Part1_t.x = 3; y = 4 };
]
}
let () =
Ag_util.Json.to_channel Part3_j.write_t3 stdout v;
print_newline ()
## () ##
Output:
\begin{verbatim}
{"name":"foo","data":[{"x":1,"y":2},{"x":3,"y":4}]}
\end{verbatim}
Source code for this section:
\url{https://github.com/MyLifeLabs/atdgen-tutorial/tree/master/modularity}
\section{Managing JSON configuration files}
JSON makes a good format for configuration files because it is
human-readable, easy to modify programmatically and widespread.
Here is an example of how to use atdgen to manage config files.
\begin{itemize}
\item \textbf{Specifying defaults} is done in the .atd file. See
section \ref{defaults} for details on how to do that.
\item \textbf{Auto-generating a template config file with default values}:
a sample value in the OCaml world needs to be created but only
fields without default need to be specified.
\item \textbf{Describing the format} is achieved by embedding the .atd
type definitions in the OCaml program and printing it out on request.
\item \textbf{Loading a config file and reporting illegal fields} is
achieved using the JSON deserializers produced by \texttt{atdgen
-j}. Option \texttt{-j-strict-fields} ensures the misspelled field
names are not ignored but reported as errors.
\item \textbf{Reindenting a config file} is achieved by the
pretty-printing function \texttt{Yojson.Safe.prettify} that takes a
JSON string and returns an equivalent JSON string.
\item \textbf{Showing implicit (default) settings} is achieved by
passing the \texttt{-j-defaults} option to \texttt{atdgen}.
The OCaml config data is then serialized into JSON containing all
fields, including those whose value is the default.
\end{itemize}
The example uses the following type definitions:
## print_atd (file_contents "config-file/config.atd") ##
Our program will perform the following actions:
\begin{verbatim}
$ ./config -template
{
"title": "",
"timeout": 10,
"credentials": [ { "name": "foo", "key": "0123456789abcdef" } ]
}
$ ./config -format
type config = {
title : string;
?description : string option;
~timeout <ocaml default="10"> : int;
~credentials : param list
<ocaml validator="fun l ->
l <> [] || failwith \"missing credentials\"">;
}
type param = {
name : string
<ocaml validator="fun s -> s <> \"\"">;
key : string
<ocaml validator="fun s -> String.length s = 16">;
}
$ cat sample-config.json
{
"title": "Example",
"credentials": [
{
"name": "joeuser",
"key": "db7c0877bdef3016"
},
{
"name": "tester",
"key": "09871ff387ac2b10"
}
]
}
$ ./config -validate sample-config.json
{
"title": "Example",
"timeout": 10,
"credentials": [
{ "name": "joeuser", "key": "db7c0877bdef3016" },
{ "name": "tester", "key": "09871ff387ac2b10" }
]
}
\end{verbatim}
This is our \texttt{demo.sh} script that builds and runs our example
program called \texttt{config}:
\verbatiminput{config-file/demo.sh}
This is the hand-written OCaml program. It can be used as a start
point for a real-world program using a JSON config file:
## print_ocaml (file_contents "config-file/config.ml") ##
The full source code for this section with examples can be inspected
and downloaded here:
\url{https://github.com/MyLifeLabs/atdgen-tutorial/tree/master/config-file}
\section{Integration with ocamldoc}
Ocamldoc is a tool that comes with the core OCaml distribution.
It uses comments within \texttt{(**} and \texttt{*)} to produce
hyperlinked documentation (HTML) of module signatures.
Atdgen can produce \texttt{.mli} files with comments in the syntax supported by
ocamldoc but regular ATD comments within \texttt{(*} and \texttt{*)}
are always discarded
by Atdgen. Instead, \texttt{<doc text="...">} must be used and placed after the
element they describe. The contents of the text field must be UTF8-encoded.
## atd () ##
type point = {
x : float;
y : float;
~z
<doc text="Optional depth, its default value is {{0.0}}.">
: float;
}
<doc text="Point with optional 3rd dimension.
OCaml example:
{{{
let p =
{ x = 0.5; y = 1.0; z = 0. }
}}}
">
## () ##
is converted into the following \texttt{.mli} file with
ocamldoc-compatible comments:
## ocaml () ##
(**
Point with optional 3rd dimension.
OCaml example:
{v
let p =
\{ x = 0.5; y = 1.0; z = 0. \}
v}
*)
type point = {
x: float;
y: float;
z: float (** Optional depth, its default value is [0.0]. *)
}
## () ##
The only two forms of markup supported by \texttt{<doc text="...">}
are \texttt{\{\{} ... \texttt{\}\}}
for inline code and \texttt{\{\{\{} ... \texttt{\}\}\}} for a block of
preformatted code.
\section{Integration with build systems}
\subsubsection{OMake}
We provide an
\href{https://github.com/MyLifeLabs/atdgen-omake}{Atdgen
plugin} for \href{http://omake.metaprl.org}{OMake}.
It allows to simplify the compilation rules to a minimum.
The plugin consists of a self-documented file to copy into a project's
root. The following is a sample \texttt{OMakefile} for a project using JSON and
five source files (\texttt{foo.atd}, \texttt{foo.ml},
\texttt{bar.atd}, \texttt{bar.ml} and \texttt{main.ml}):
\begin{verbatim}
include Atdgen
# requires file Atdgen.om
OCAMLFILES = foo_t foo_j foo bar_t bar_j bar main
# correspond to the OCaml modules we want to build
Atdgen(foo bar, -j-std)
OCamlProgram(foobar, $(OCAMLFILES))
.DEFAULT: foobar.opt
.PHONY: clean
clean:
rm -f *.cm[ioxa] *.cmx[as] *.[oa] *.opt *.run *~
rm -f $(ATDGEN_OUTFILES)
\end{verbatim}
Running \texttt{omake} builds the native code executable
\texttt{foobar.opt}.
\texttt{omake clean} removes all the products
of compilation including the \texttt{.mli} and \texttt{.ml} produced
by \texttt{atdgen}.