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
(** {3 Type of the JSON tree} *)
type t =
[
| `Null
| `Bool of bool
| `Int of int
| `Intlit of string
| `Float of float
| `Floatlit of string
| `String of string
| `Stringlit of string
| `Assoc of (string * t) list
| `List of t list
| `Tuple of t list
| `Variant of (string * t option)
]
(**
All possible cases defined in Yojson:
- `Null: JSON null
- `Bool of bool: JSON boolean
- `Int of int: JSON number without decimal point or exponent.
- `Intlit of string: JSON number without decimal point or exponent,
preserved as a string.
- `Float of float: JSON number, Infinity, -Infinity or NaN.
- `Floatlit of string: JSON number, Infinity, -Infinity or NaN,
preserved as a string.
- `String of string: JSON string. Bytes in the range 128-255 are preserved
as-is without encoding validation for both reading
and writing.
- `Stringlit of string: JSON string literal including the double quotes.
- `Assoc of (string * json) list: JSON object.
- `List of json list: JSON array.
- `Tuple of json list: Tuple (non-standard extension of JSON).
Syntax: [("abc", 123)].
- `Variant of (string * json option): Variant (non-standard extension of JSON).
Syntax: [<"Foo">] or [<"Bar":123>].
*)
let hex n =
Char.chr (
if n < 10 then n + 48
else n + 87
)
let write_special src start stop ob str =
Buffer.add_substring ob src !start (stop - !start);
Buffer.add_string ob str;
start := stop + 1
let write_control_char src start stop ob c =
Buffer.add_substring ob src !start (stop - !start);
Buffer.add_string ob "\\u00";
Buffer.add_char ob (hex (Char.code c lsr 4));
Buffer.add_char ob (hex (Char.code c land 0xf));
start := stop + 1
let finish_string src start ob =
try
Buffer.add_substring ob src !start (String.length src - !start)
with exc ->
Printf.eprintf "src=%S start=%i len=%i\n%!"
src !start (String.length src - !start);
raise exc
let write_string_body ob s =
let start = ref 0 in
for i = 0 to String.length s - 1 do
match s.[i] with
'"' -> write_special s start i ob "\\\""
| '\\' -> write_special s start i ob "\\\\"
| '\b' -> write_special s start i ob "\\b"
| '\012' -> write_special s start i ob "\\f"
| '\n' -> write_special s start i ob "\\n"
| '\r' -> write_special s start i ob "\\r"
| '\t' -> write_special s start i ob "\\t"
| '\x00'..'\x1F'
| '\x7F' as c -> write_control_char s start i ob c
| _ -> ()
done;
finish_string s start ob
let write_string ob s =
Buffer.add_char ob '"';
write_string_body ob s;
Buffer.add_char ob '"'
let json_string_of_string s =
let ob = Buffer.create 10 in
write_string ob s;
Buffer.contents ob
let write_null ob () =
Buffer.add_string ob "null"
let write_bool ob x =
Buffer.add_string ob (if x then "true" else "false")
let dec n =
Char.chr (n + 48)
let rec write_digits s x =
if x = 0 then ()
else
let d = x mod 10 in
write_digits s (x / 10);
Buffer.add_char s (dec (abs d))
let write_int ob x =
if x > 0 then
write_digits ob x
else if x < 0 then (
Buffer.add_char ob '-';
write_digits ob x
)
else
Buffer.add_char ob '0'
let json_string_of_int i =
string_of_int i
let float_needs_period s =
try
for i = 0 to String.length s - 1 do
match s.[i] with
'0'..'9' | '-' -> ()
| _ -> raise Exit
done;
true
with Exit ->
false
let write_float ob x =
match classify_float x with
FP_nan ->
Buffer.add_string ob "NaN"
| FP_infinite ->
Buffer.add_string ob (if x > 0. then "Infinity" else "-Infinity")
| _ ->
let s1 = Printf.sprintf "%.16g" x in
let s =
if float_of_string s1 = x then s1
else Printf.sprintf "%.17g" x
in
Buffer.add_string ob s;
if float_needs_period s then
Buffer.add_string ob ".0"
let write_normal_float_prec significant_figures ob x =
let sprintf = Printf.sprintf in
let s =
match significant_figures with
1 -> sprintf "%.1g" x
| 2 -> sprintf "%.2g" x
| 3 -> sprintf "%.3g" x
| 4 -> sprintf "%.4g" x
| 5 -> sprintf "%.5g" x
| 6 -> sprintf "%.6g" x
| 7 -> sprintf "%.7g" x
| 8 -> sprintf "%.8g" x
| 9 -> sprintf "%.9g" x
| 10 -> sprintf "%.10g" x
| 11 -> sprintf "%.11g" x
| 12 -> sprintf "%.12g" x
| 13 -> sprintf "%.13g" x
| 14 -> sprintf "%.14g" x
| 15 -> sprintf "%.15g" x
| 16 -> sprintf "%.16g" x
| _ -> sprintf "%.17g" x
in
Buffer.add_string ob s;
if float_needs_period s then
Buffer.add_string ob ".0"
let write_float_prec significant_figures ob x =
match classify_float x with
FP_nan ->
Buffer.add_string ob "NaN"
| FP_infinite ->
Buffer.add_string ob (if x > 0. then "Infinity" else "-Infinity")
| _ ->
write_normal_float_prec significant_figures ob x
let json_string_of_float x =
let ob = Buffer.create 20 in
write_float ob x;
Buffer.contents ob
let write_std_float ob x =
match classify_float x with
FP_nan ->
Common.json_error "NaN value not allowed in standard JSON"
| FP_infinite ->
Common.json_error
(if x > 0. then
"Infinity value not allowed in standard JSON"
else
"-Infinity value not allowed in standard JSON")
| _ ->
let s1 = Printf.sprintf "%.16g" x in
let s =
if float_of_string s1 = x then s1
else Printf.sprintf "%.17g" x
in
Buffer.add_string ob s;
if float_needs_period s then
Buffer.add_string ob ".0"
let write_std_float_prec significant_figures ob x =
match classify_float x with
FP_nan ->
Common.json_error "NaN value not allowed in standard JSON"
| FP_infinite ->
Common.json_error
(if x > 0. then
"Infinity value not allowed in standard JSON"
else
"-Infinity value not allowed in standard JSON")
| _ ->
write_normal_float_prec significant_figures ob x
let std_json_string_of_float x =
let ob = Buffer.create 20 in
write_std_float ob x;
Buffer.contents ob
let write_intlit = Buffer.add_string
let write_floatlit = Buffer.add_string
let write_stringlit = Buffer.add_string
let rec iter2_aux f_elt f_sep x = function
[] -> ()
| y :: l ->
f_sep x;
f_elt x y;
iter2_aux f_elt f_sep x l
let iter2 f_elt f_sep x = function
[] -> ()
| y :: l ->
f_elt x y;
iter2_aux f_elt f_sep x l
let f_sep ob =
Buffer.add_char ob ','
let rec write_json ob (x : t) =
match x with
`Null -> write_null ob ()
| `Bool b -> write_bool ob b
| `Int i -> write_int ob i
| `Intlit s -> Buffer.add_string ob s
| `Float f -> write_float ob f
| `Floatlit s -> Buffer.add_string ob s
| `String s -> write_string ob s
| `Stringlit s -> Buffer.add_string ob s
| `Assoc l -> write_assoc ob l
| `List l -> write_list ob l
| `Tuple l -> write_tuple ob l
| `Variant (s, o) -> write_variant ob s o
and write_assoc ob l =
let f_elt ob (s, x) =
write_string ob s;
Buffer.add_char ob ':';
write_json ob x
in
Buffer.add_char ob '{';
iter2 f_elt f_sep ob l;
Buffer.add_char ob '}';
and write_list ob l =
Buffer.add_char ob '[';
iter2 write_json f_sep ob l;
Buffer.add_char ob ']'
and write_tuple ob l =
Buffer.add_char ob '(';
iter2 write_json f_sep ob l;
Buffer.add_char ob ')'
and write_variant ob s o =
Buffer.add_char ob '<';
write_string ob s;
(match o with
None -> ()
| Some x ->
Buffer.add_char ob ':';
write_json ob x
);
Buffer.add_char ob '>'
let write_t = write_json
let rec write_std_json ob (x : t) =
match x with
`Null -> write_null ob ()
| `Bool b -> write_bool ob b
| `Int i -> write_int ob i
| `Intlit s -> Buffer.add_string ob s
| `Float f -> write_std_float ob f
| `Floatlit s -> Buffer.add_string ob s
| `String s -> write_string ob s
| `Stringlit s -> Buffer.add_string ob s
| `Assoc l -> write_std_assoc ob l
| `List l -> write_std_list ob l
| `Tuple l -> write_std_tuple ob l
| `Variant (s, o) -> write_std_variant ob s o
and write_std_assoc ob l =
let f_elt ob (s, x) =
write_string ob s;
Buffer.add_char ob ':';
write_std_json ob x
in
Buffer.add_char ob '{';
iter2 f_elt f_sep ob l;
Buffer.add_char ob '}';
and write_std_list ob l =
Buffer.add_char ob '[';
iter2 write_std_json f_sep ob l;
Buffer.add_char ob ']'
and write_std_tuple ob l =
Buffer.add_char ob '[';
iter2 write_std_json f_sep ob l;
Buffer.add_char ob ']'
and write_std_variant ob s o =
match o with
None -> write_string ob s
| Some x ->
Buffer.add_char ob '[';
write_string ob s;
Buffer.add_char ob ',';
write_std_json ob x;
Buffer.add_char ob ']'
let to_buffer ?(suf = "") ?(std = false) ob x =
if std then
write_std_json ob x
else
write_json ob x;
Buffer.add_string ob suf
let to_string ?buf ?(len = 256) ?(suf = "") ?std x =
let ob =
match buf with
None -> Buffer.create len
| Some ob ->
Buffer.clear ob;
ob
in
to_buffer ~suf ?std ob x;
let s = Buffer.contents ob in
Buffer.clear ob;
s
let to_channel ?buf ?(len=4096) ?(suf = "") ?std oc x =
let ob =
match buf with
None -> Buffer.create len
| Some ob -> Buffer.clear ob; ob
in
to_buffer ~suf ?std ob x;
Buffer.output_buffer oc ob;
Buffer.clear ob
let to_output ?buf ?(len=4096) ?(suf = "") ?std out x =
let ob =
match buf with
None -> Buffer.create len
| Some ob -> Buffer.clear ob; ob
in
to_buffer ~suf ?std ob x;
let _ : int = out#output (Buffer.contents ob) 0 (Buffer.length ob) in
Buffer.clear ob
let to_file ?len ?std ?(suf = "\n") file x =
let oc = open_out file in
try
to_channel ?len ~suf ?std oc x;
close_out oc
with e ->
close_out_noerr oc;
raise e
let seq_to_buffer ?(suf = "\n") ?std ob st =
Seq.iter (to_buffer ~suf ?std ob) st
let seq_to_string ?buf ?(len = 256) ?(suf = "\n") ?std st =
let ob =
match buf with
None -> Buffer.create len
| Some ob ->
Buffer.clear ob;
ob
in
seq_to_buffer ~suf ?std ob st;
let s = Buffer.contents ob in
Buffer.clear ob;
s
let seq_to_channel ?buf ?(len=2096) ?(suf = "\n") ?std oc seq =
let ob =
match buf with
None -> Buffer.create len
| Some ob -> Buffer.clear ob; ob
in
Seq.iter (fun json ->
to_buffer ~suf ?std ob json;
Buffer.output_buffer oc ob;
Buffer.clear ob;
) seq
let seq_to_file ?len ?(suf = "\n") ?std file st =
let oc = open_out file in
try
seq_to_channel ?len ~suf ?std oc st;
close_out oc
with e ->
close_out_noerr oc;
raise e
let rec sort = function
| `Assoc l ->
let l = List.rev (List.rev_map (fun (k, v) -> (k, sort v)) l) in
`Assoc (List.stable_sort (fun (a, _) (b, _) -> String.compare a b) l)
| `List l ->
`List (List.rev (List.rev_map sort l))
| `Tuple l ->
`Tuple (List.rev (List.rev_map sort l))
| `Variant (k, Some v) as x ->
let v' = sort v in
if v == v' then x
else
`Variant (k, Some v')
| x -> x
let rec pp fmt =
function
| `Null -> Format.pp_print_string fmt "`Null"
| `Bool x ->
Format.fprintf fmt "`Bool (@[<hov>";
Format.fprintf fmt "%B" x;
Format.fprintf fmt "@])"
| `Int x ->
Format.fprintf fmt "`Int (@[<hov>";
Format.fprintf fmt "%d" x;
Format.fprintf fmt "@])"
| `Intlit x ->
Format.fprintf fmt "`Intlit (@[<hov>";
Format.fprintf fmt "%S" x;
Format.fprintf fmt "@])"
| `Float x ->
Format.fprintf fmt "`Float (@[<hov>";
Format.fprintf fmt "%F" x;
Format.fprintf fmt "@])"
| `Floatlit x ->
Format.fprintf fmt "`Floatlit (@[<hov>";
Format.fprintf fmt "%S" x;
Format.fprintf fmt "@])"
| `String x ->
Format.fprintf fmt "`String (@[<hov>";
Format.fprintf fmt "%S" x;
Format.fprintf fmt "@])"
| `Stringlit x ->
Format.fprintf fmt "`Stringlit (@[<hov>";
Format.fprintf fmt "%S" x;
Format.fprintf fmt "@])"
| `Assoc xs ->
Format.fprintf fmt "`Assoc (@[<hov>";
Format.fprintf fmt "@[<2>[";
ignore (List.fold_left
(fun sep (key, value) ->
if sep then
Format.fprintf fmt ";@ ";
Format.fprintf fmt "(@[";
Format.fprintf fmt "%S" key;
Format.fprintf fmt ",@ ";
pp fmt value;
Format.fprintf fmt "@])";
true) false xs);
Format.fprintf fmt "@,]@]";
Format.fprintf fmt "@])"
| `List xs ->
Format.fprintf fmt "`List (@[<hov>";
Format.fprintf fmt "@[<2>[";
ignore (List.fold_left
(fun sep x ->
if sep then
Format.fprintf fmt ";@ ";
pp fmt x;
true) false xs);
Format.fprintf fmt "@,]@]";
Format.fprintf fmt "@])"
| `Tuple tup ->
Format.fprintf fmt "`Tuple (@[<hov>";
Format.fprintf fmt "@[<2>[";
ignore (List.fold_left
(fun sep e ->
if sep then
Format.fprintf fmt ";@ ";
pp fmt e;
true) false tup);
Format.fprintf fmt "@,]@]";
Format.fprintf fmt "@])"
| `Variant (name, value) ->
Format.fprintf fmt "`Variant (@[<hov>";
Format.fprintf fmt "(@[";
Format.fprintf fmt "%S" name;
Format.fprintf fmt ",@ ";
(match value with
| None -> Format.pp_print_string fmt "None"
| Some x ->
Format.pp_print_string fmt "(Some ";
pp fmt x;
Format.pp_print_string fmt ")");
Format.fprintf fmt "@])";
Format.fprintf fmt "@])"
let show x =
Format.asprintf "%a" pp x
let rec equal a b =
match a, b with
| `Null, `Null -> true
| `Bool a, `Bool b -> a = b
| `Int a, `Int b -> a = b
| `Intlit a, `Intlit b -> a = b
| `Float a, `Float b -> a = b
| `Floatlit a, `Floatlit b -> a = b
| `String a, `String b -> a = b
| `Stringlit a, `Stringlit b -> a = b
| `Assoc xs, `Assoc ys ->
let compare_keys = fun (key, _) (key', _) -> String.compare key key' in
let xs = List.stable_sort compare_keys xs in
let ys = List.stable_sort compare_keys ys in
(match List.for_all2 (fun (key, value) (key', value') ->
match key = key' with
| false -> false
| true -> equal value value') xs ys with
| result -> result
| exception Invalid_argument _ ->
false)
| `Tuple xs, `Tuple ys
| `List xs, `List ys ->
(match List.for_all2 equal xs ys with
| result -> result
| exception Invalid_argument _ ->
false)
| `Variant (name, value), `Variant (name', value') ->
(match name = name' with
| false -> false
| true ->
match value, value' with
| None, None -> true
| Some x, Some y -> equal x y
| _ -> false)
| _ -> false
module Pretty = struct
let pp_list sep ppx out l =
let pp_sep out () = Format.fprintf out "%s@ " sep in
Format.pp_print_list ~pp_sep ppx out l
let is_atom (x: [> t]) =
match x with
| `Null
| `Bool _
| `Int _
| `Float _
| `String _
| `Intlit _
| `Floatlit _
| `Stringlit _
| `List []
| `Assoc []
| `Tuple []
| `Variant (_, None) -> true
| `List _
| `Assoc _
| `Tuple _
| `Variant (_, Some _) -> false
let is_atom_list l =
List.for_all is_atom l
let rec format ~inside_box std (out:Format.formatter) (x:t) : unit =
match x with
| `Null -> Format.pp_print_string out "null"
| `Bool x -> Format.pp_print_bool out x
| `Int x -> Format.pp_print_string out (json_string_of_int x)
| `Float x ->
let s =
if std then std_json_string_of_float x
else json_string_of_float x
in
Format.pp_print_string out s
| `String s -> Format.pp_print_string out (json_string_of_string s)
| `Intlit s -> Format.pp_print_string out s
| `Floatlit s -> Format.pp_print_string out s
| `Stringlit s -> Format.pp_print_string out s
| `List [] -> Format.pp_print_string out "[]"
| `List l ->
if not inside_box then Format.fprintf out "@[<hv2>";
if is_atom_list l then
Format.fprintf out "[@;<1 0>@[<hov>%a@]@;<1 -2>]"
(pp_list "," (format ~inside_box:false std)) l
else
Format.fprintf out "[@;<1 0>@[<hv>%a@]@;<1 -2>]"
(pp_list "," (format ~inside_box:false std)) l;
if not inside_box then Format.fprintf out "@]";
| `Assoc [] -> Format.pp_print_string out "{}"
| `Assoc l ->
if not inside_box then Format.fprintf out "@[<hv2>";
Format.fprintf out "{@;<1 0>%a@;<1 -2>}" (pp_list "," (format_field std)) l;
if not inside_box then Format.fprintf out "@]";
| `Tuple l ->
if std then
format ~inside_box std out (`List l)
else
if l = [] then
Format.pp_print_string out "()"
else (
if not inside_box then Format.fprintf out "@[<hov2>";
Format.fprintf out "(@,%a@;<0 -2>)" (pp_list "," (format ~inside_box:false std)) l;
if not inside_box then Format.fprintf out "@]";
)
| `Variant (s, None) ->
if std then
let representation = `String s in
format ~inside_box std out representation
else
Format.fprintf out "<%s>" (json_string_of_string s)
| `Variant (s, Some x) ->
if std then
let representation = `String s in
format ~inside_box std out (`List [ representation; x ])
else
let op = json_string_of_string s in
Format.fprintf out "<@[<hv2>%s: %a@]>" op (format ~inside_box:true std) x
and format_field std out (name, x) =
Format.fprintf out "@[<hv2>%s: %a@]" (json_string_of_string name) (format ~inside_box:true std) x
let pp ?(std = false) out x =
Format.fprintf out "@[<hv2>%a@]" (format ~inside_box:true std) (x :> t)
let to_string ?std x =
Format.asprintf "%a" (pp ?std) x
let to_channel ?std oc x =
let fmt = Format.formatter_of_out_channel oc in
Format.fprintf fmt "%a@?" (pp ?std) x
end
let pretty_print ?std out x = Pretty.pp ?std out x
let pretty_to_string ?std x = Pretty.to_string ?std x
let pretty_to_channel ?std oc x = Pretty.to_channel ?std oc x