Source file YojsonSafe.ml
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
[@@@warning "-unused-var-strict"]
open struct
module Common = YojsonCommon
end
(** {3 Type of the JSON tree} *)
type t =
[ `Null
| `Bool of bool
| `Int of int
| `Intlit of string
| `Float of float
| `String of string
| `Assoc of (string * t) list
| `List of t list ]
(**
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.
*)
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 json_string_of_float x =
let ob = Buffer.create 20 in
write_float ob x;
Buffer.contents ob
let write_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 = write_float
let write_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 write_std_float_prec = write_float_prec
let write_intlit = 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
| `String s -> write_string ob s
| `Assoc l -> write_assoc ob l
| `List l -> write_list ob l
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 ']'
let write_t = write_json
let write_std_json = write_json
let to_buffer ?(suf = "") ?(std = true) ob x =
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))
| x -> x
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 [] ->
true
| `List _ | `Assoc _ -> false
let is_atom_list l = List.for_all is_atom l
let rec format ~inside_box (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 -> Format.pp_print_string out (json_string_of_float x)
| `String s -> Format.pp_print_string out (json_string_of_string s)
| `Intlit 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))
l
else
Format.fprintf out "[@;<1 0>@[<hv>%a@]@;<1 -2>]"
(pp_list "," (format ~inside_box:false))
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) l;
if not inside_box then Format.fprintf out "@]"
and format_field out (name, x) =
Format.fprintf out "@[<hv2>%s: %a@]"
(json_string_of_string name)
(format ~inside_box:true) x
let pp ?(std = true) out x =
Format.fprintf out "@[<hv2>%a@]" (format ~inside_box:true) (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 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 "@])"
| `String x ->
Format.fprintf fmt "`String (@[<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 "@])"
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
| `String a, `String b -> a = b
| `Assoc xs, `Assoc ys -> (
let compare_keys (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)
| `List xs, `List ys -> (
match List.for_all2 equal xs ys with
| result -> result
| exception Invalid_argument _ ->
false)
| _ -> false
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
module Util = struct
exception Type_error of string * t
let typeof = function
| `Assoc _ -> "object"
| `Bool _ -> "bool"
| `Float _ -> "float"
| `Int _ -> "int"
| `List _ -> "array"
| `Null -> "null"
| `String _ -> "string"
| `Intlit _ -> "intlit"
| `Floatlit _ -> "floatlit"
let typerr msg js = raise (Type_error (msg ^ typeof js, js))
exception Undefined of string * t
let assoc name obj = try List.assoc name obj with Not_found -> `Null
let member name = function
| `Assoc obj -> assoc name obj
| js -> typerr ("Can't get member '" ^ name ^ "' of non-object type ") js
let rec path l obj =
match l with
| [] -> Some obj
| key :: l ->
match obj with
| `Assoc assoc -> (
match List.assoc key assoc with
| obj -> path l obj
| exception Not_found -> None)
| _ -> None
let index i = function
| `List l as js ->
let len = List.length l in
let wrapped_index = if i < 0 then len + i else i in
if wrapped_index < 0 || wrapped_index >= len then
raise (Undefined ("Index " ^ string_of_int i ^ " out of bounds", js))
else List.nth l wrapped_index
| js ->
typerr ("Can't get index " ^ string_of_int i ^ " of non-array type ") js
let map f = function
| `List l -> `List (List.map f l)
| js -> typerr "Can't map function over non-array type " js
let to_assoc = function
| `Assoc obj -> obj
| js -> typerr "Expected object, got " js
let to_option f = function `Null -> None | x -> Some (f x)
let to_bool = function `Bool b -> b | js -> typerr "Expected bool, got " js
let to_bool_option = function
| `Bool b -> Some b
| `Null -> None
| js -> typerr "Expected bool or null, got " js
let to_number = function
| `Int i -> float i
| `Float f -> f
| js -> typerr "Expected number, got " js
let to_number_option = function
| `Int i -> Some (float i)
| `Float f -> Some f
| `Null -> None
| js -> typerr "Expected number or null, got " js
let to_float = function
| `Float f -> f
| js -> typerr "Expected float, got " js
let to_float_option = function
| `Float f -> Some f
| `Null -> None
| js -> typerr "Expected float or null, got " js
let to_int = function `Int i -> i | js -> typerr "Expected int, got " js
let to_int_option = function
| `Int i -> Some i
| `Null -> None
| js -> typerr "Expected int or null, got " js
let to_list = function `List l -> l | js -> typerr "Expected array, got " js
let to_string = function
| `String s -> s
| js -> typerr "Expected string, got " js
let to_string_option = function
| `String s -> Some s
| `Null -> None
| js -> typerr "Expected string or null, got " js
let convert_each f = function
| `List l -> List.map f l
| js -> typerr "Can't convert each element of non-array type " js
let rec rev_filter_map f acc l =
match l with
| [] -> acc
| x :: tl ->
match f x with
| None -> rev_filter_map f acc tl
| Some y -> rev_filter_map f (y :: acc) tl
let filter_map f l = List.rev (rev_filter_map f [] l)
let rec rev_flatten acc l =
match l with
| [] -> acc
| x :: tl ->
match x with
| `List l2 -> rev_flatten (List.rev_append l2 acc) tl
| _ -> rev_flatten acc tl
let flatten l = List.rev (rev_flatten [] l)
let filter_index i l =
filter_map
(function
| `List l -> ( try Some (List.nth l i) with _ -> None) | _ -> None)
l
let filter_list l = filter_map (function `List l -> Some l | _ -> None) l
let filter_member k l =
filter_map
(function
| `Assoc l -> ( try Some (List.assoc k l) with _ -> None) | _ -> None)
l
let filter_assoc l = filter_map (function `Assoc l -> Some l | _ -> None) l
let filter_bool l = filter_map (function `Bool x -> Some x | _ -> None) l
let filter_int l = filter_map (function `Int x -> Some x | _ -> None) l
let filter_float l = filter_map (function `Float x -> Some x | _ -> None) l
let filter_number l =
filter_map
(function `Int x -> Some (float x) | `Float x -> Some x | _ -> None)
l
let filter_string l =
filter_map (function `String x -> Some x | _ -> None) l
let keys o = to_assoc o |> List.map (fun (key, _) -> key)
let values o = to_assoc o |> List.map (fun (_, value) -> value)
let combine (first : t) (second : t) =
match (first, second) with
| `Assoc a, `Assoc b -> (`Assoc (a @ b) : t)
| a, b -> raise (Invalid_argument "Expected two objects, check inputs")
end