File: read.mll

package info (click to toggle)
yojson 2.2.2-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,216 kB
  • sloc: ml: 3,890; makefile: 28
file content (1193 lines) | stat: -rw-r--r-- 41,062 bytes parent folder | download
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
{
  module Lexing =
    (*
      We override Lexing.engine in order to avoid creating a new position
      record each time a rule is matched.
      This reduces total parsing time by about 31%.
    *)
  struct
    include Lexing

    external c_engine : lex_tables -> int -> lexbuf -> int = "caml_lex_engine"

    let engine tbl state buf =
      let result = c_engine tbl state buf in
      (*
      if result >= 0 then begin
        buf.lex_start_p <- buf.lex_curr_p;
        buf.lex_curr_p <- {buf.lex_curr_p
                           with pos_cnum = buf.lex_abs_pos + buf.lex_curr_pos};
      end;
      *)
      result
  end

  (* see description in common.mli *)
  type lexer_state = Common.Lexer_state.t = {
    buf : Buffer.t;
    mutable lnum : int;
    mutable bol : int;
    mutable fname : string option;
  }

  let dec c =
    Char.code c - 48

  let hex c =
    match c with
        '0'..'9' -> int_of_char c - int_of_char '0'
      | 'a'..'f' -> int_of_char c - int_of_char 'a' + 10
      | 'A'..'F' -> int_of_char c - int_of_char 'A' + 10
      | _ -> assert false

  let custom_error descr v (lexbuf : Lexing.lexbuf) =
    let offs = lexbuf.lex_abs_pos - 1 in
    let bol = v.bol in
    let pos1 = offs + lexbuf.lex_start_pos - bol - 1 in
    let pos2 = max pos1 (offs + lexbuf.lex_curr_pos - bol) in
    let file_line =
      match v.fname with
          None -> "Line"
        | Some s ->
            Printf.sprintf "File %s, line" s
    in
    let bytes =
      if pos1 = pos2 then
        Printf.sprintf "byte %i" (pos1+1)
      else
        Printf.sprintf "bytes %i-%i" (pos1+1) (pos2+1)
    in
    let msg = Printf.sprintf "%s %i, %s:\n%s" file_line v.lnum bytes descr in
    Common.json_error msg


  let lexer_error descr v lexbuf =
    custom_error
      (Printf.sprintf "%s '%s'" descr (Lexing.lexeme lexbuf))
      v lexbuf

  let long_error descr v lexbuf =
    let junk = Lexing.lexeme lexbuf in
    let buf_size = 32 in
    let buf = Buffer.create buf_size in
    let () = Lexer_utils.read_junk_without_positions buf buf_size lexbuf in
    let extra_junk = Buffer.contents buf in
    custom_error
      (Printf.sprintf "%s '%s%s'" descr junk extra_junk)
      v lexbuf

  let min10 = min_int / 10 - (if min_int mod 10 = 0 then 0 else 1)
  let max10 = max_int / 10 + (if max_int mod 10 = 0 then 0 else 1)

  exception Int_overflow

  let extract_positive_int (lexbuf : Lexing.lexbuf) =
    let start = lexbuf.lex_start_pos in
    let stop = lexbuf.lex_curr_pos in
    let s = lexbuf.lex_buffer in
    let n = ref 0 in
    for i = start to stop - 1 do
      if !n >= max10 then
        raise Int_overflow
      else
        n := 10 * !n + dec (Bytes.get s i)
    done;
    if !n < 0 then
      raise Int_overflow
    else
      !n

  let make_positive_int v lexbuf =
    #ifdef INT
      try `Int (extract_positive_int lexbuf)
      with Int_overflow ->
    #endif
      #ifdef INTLIT
        `Intlit (Lexing.lexeme lexbuf)
      #else
        lexer_error "Int overflow" v lexbuf
      #endif

  let extract_negative_int (lexbuf : Lexing.lexbuf)  =
    let start = lexbuf.lex_start_pos + 1 in
    let stop = lexbuf.lex_curr_pos in
    let s = lexbuf.lex_buffer in
    let n = ref 0 in
    for i = start to stop - 1 do
      if !n <= min10 then
        raise Int_overflow
      else
        n := 10 * !n - dec (Bytes.get s i)
    done;
    if !n > 0 then
      raise Int_overflow
    else
      !n

  let make_negative_int v lexbuf =
    #ifdef INT
      try `Int (extract_negative_int lexbuf)
      with Int_overflow ->
    #endif
      #ifdef INTLIT
        `Intlit (Lexing.lexeme lexbuf)
      #else
        lexer_error "Int overflow" v lexbuf
      #endif

  let newline v (lexbuf : Lexing.lexbuf) =
    v.lnum <- v.lnum + 1;
    v.bol <- lexbuf.lex_abs_pos + lexbuf.lex_curr_pos

  let add_lexeme buf (lexbuf : Lexing.lexbuf) =
    let len = lexbuf.lex_curr_pos - lexbuf.lex_start_pos in
    Buffer.add_subbytes buf lexbuf.lex_buffer lexbuf.lex_start_pos len

  let map_lexeme f (lexbuf : Lexing.lexbuf) =
    let len = lexbuf.lex_curr_pos - lexbuf.lex_start_pos in
    f (Bytes.sub_string lexbuf.lex_buffer lexbuf.lex_start_pos len) 0 len

  type variant_kind = [ `Edgy_bracket | `Square_bracket | `Double_quote ]
}

let space = [' ' '\t' '\r']+

let digit = ['0'-'9']
let nonzero = ['1'-'9']
let digits = digit+
let frac = '.' digits
let e = ['e' 'E']['+' '-']?
let exp = e digits

let positive_int = (digit | nonzero digits)
let float = '-'? positive_int (frac | exp | frac exp)
let number = '-'? positive_int (frac | exp | frac exp)?

let hex = [ '0'-'9' 'a'-'f' 'A'-'F' ]

let ident = ['a'-'z' 'A'-'Z' '_']['a'-'z' 'A'-'Z' '_' '0'-'9']*

rule read_json v = parse
  | "true"      { `Bool true }
  | "false"     { `Bool false }
  | "null"      { `Null }
  | "NaN"       {
                  #ifdef FLOAT
                    `Float nan
                  #elif defined FLOATLIT
                    `Floatlit "NaN"
                  #endif
                }
  | "Infinity"  {
                  #ifdef FLOAT
                    `Float infinity
                  #elif defined FLOATLIT
                    `Floatlit "Infinity"
                  #endif
                }
  | "-Infinity" {
                  #ifdef FLOAT
                    `Float neg_infinity
                  #elif defined FLOATLIT
                    `Floatlit "-Infinity"
                  #endif
                }
  | '"'         {
                  #ifdef STRING
                    Buffer.clear v.buf;
                    `String (finish_string v lexbuf)
                  #elif defined STRINGLIT
                    `Stringlit (finish_stringlit v lexbuf)
                  #endif
                }
  | positive_int         { make_positive_int v lexbuf }
  | '-' positive_int     { make_negative_int v lexbuf }
  | float       {
                  #ifdef FLOAT
                    `Float (float_of_string (Lexing.lexeme lexbuf))
                  #elif defined FLOATLIT
                    `Floatlit (Lexing.lexeme lexbuf)
                  #endif
                 }

  | '{'          { let acc = ref [] in
                   try
                     read_space v lexbuf;
                     read_object_end lexbuf;
                     let field_name = read_ident v lexbuf in
                     read_space v lexbuf;
                     read_colon v lexbuf;
                     read_space v lexbuf;
                     acc := (field_name, read_json v lexbuf) :: !acc;
                     while true do
                       read_space v lexbuf;
                       read_object_sep v lexbuf;
                       read_space v lexbuf;
                       let field_name = read_ident v lexbuf in
                       read_space v lexbuf;
                       read_colon v lexbuf;
                       read_space v lexbuf;
                       acc := (field_name, read_json v lexbuf) :: !acc;
                     done;
                     assert false
                   with Common.End_of_object ->
                     `Assoc (List.rev !acc)
                 }

  | '['          { let acc = ref [] in
                   try
                     read_space v lexbuf;
                     read_array_end lexbuf;
                     acc := read_json v lexbuf :: !acc;
                     while true do
                       read_space v lexbuf;
                       read_array_sep v lexbuf;
                       read_space v lexbuf;
                       acc := read_json v lexbuf :: !acc;
                     done;
                     assert false
                   with Common.End_of_array ->
                     `List (List.rev !acc)
                 }

  | '('          {
                   #ifdef TUPLE
                     let acc = ref [] in
                     try
                       read_space v lexbuf;
                       read_tuple_end lexbuf;
                       acc := read_json v lexbuf :: !acc;
                       while true do
                         read_space v lexbuf;
                         read_tuple_sep v lexbuf;
                         read_space v lexbuf;
                         acc := read_json v lexbuf :: !acc;
                       done;
                       assert false
                     with Common.End_of_tuple ->
                       `Tuple (List.rev !acc)
                   #else
                     long_error "Invalid token" v lexbuf
                   #endif
                 }

  | '<'          {
                   #ifdef VARIANT
                     read_space v lexbuf;
                     let cons = read_ident v lexbuf in
                     read_space v lexbuf;
                     `Variant (cons, finish_variant v lexbuf)
                   #else
                     long_error "Invalid token" v lexbuf
                   #endif
                 }

  | "//"[^'\n']* { read_json v lexbuf }
  | "/*"         { finish_comment v lexbuf; read_json v lexbuf }
  | "\n"         { newline v lexbuf; read_json v lexbuf }
  | space        { read_json v lexbuf }
  | eof          { custom_error "Unexpected end of input" v lexbuf }
  | _            { long_error "Invalid token" v lexbuf }


and finish_string v = parse
    '"'           { Buffer.contents v.buf }
  | '\\'          { finish_escaped_char v lexbuf;
                    finish_string v lexbuf }
  | [^ '"' '\\']+ { add_lexeme v.buf lexbuf;
                    finish_string v lexbuf }
  | eof           { custom_error "Unexpected end of input" v lexbuf }

and map_string v f = parse
    '"'           { let b = v.buf in
                    f (Buffer.contents b) 0 (Buffer.length b) }
  | '\\'          { finish_escaped_char v lexbuf;
                    map_string v f lexbuf }
  | [^ '"' '\\']+ { add_lexeme v.buf lexbuf;
                    map_string v f lexbuf }
  | eof           { custom_error "Unexpected end of input" v lexbuf }

and finish_escaped_char v = parse
    '"'
  | '\\'
  | '/' as c { Buffer.add_char v.buf c }
  | 'b'  { Buffer.add_char v.buf '\b' }
  | 'f'  { Buffer.add_char v.buf '\012' }
  | 'n'  { Buffer.add_char v.buf '\n' }
  | 'r'  { Buffer.add_char v.buf '\r' }
  | 't'  { Buffer.add_char v.buf '\t' }
  | 'u' (hex as a) (hex as b) (hex as c) (hex as d)
         { let x =
             (hex a lsl 12) lor (hex b lsl 8) lor (hex c lsl 4) lor hex d
           in
           if x >= 0xD800 && x <= 0xDBFF then
             finish_surrogate_pair v x lexbuf
           else
             Codec.utf8_of_code v.buf x

         }
  | _    { long_error "Invalid escape sequence" v lexbuf }
  | eof  { custom_error "Unexpected end of input" v lexbuf }

and finish_surrogate_pair v x = parse
  | "\\u" (hex as a) (hex as b) (hex as c) (hex as d)
         { let y =
             (hex a lsl 12) lor (hex b lsl 8) lor (hex c lsl 4) lor hex d
           in
           if y >= 0xDC00 && y <= 0xDFFF then
             Codec.utf8_of_surrogate_pair v.buf x y
           else
             long_error "Invalid low surrogate for code point beyond U+FFFF"
               v lexbuf
         }
  | _    { long_error "Missing escape sequence representing low surrogate \
                       for code point beyond U+FFFF" v lexbuf }
  | eof  { custom_error "Unexpected end of input" v lexbuf }

and finish_stringlit v = parse
    ( '\\' (['"' '\\' '/' 'b' 'f' 'n' 'r' 't'] | 'u' hex hex hex hex)
    | [^'"' '\\'] )* '"'
         { let len = lexbuf.lex_curr_pos - lexbuf.lex_start_pos in
           let s = Bytes.create (len+1) in
           Bytes.set s 0 '"';
           Bytes.blit lexbuf.lex_buffer lexbuf.lex_start_pos s 1 len;
           Bytes.to_string s
         }
  | _    { long_error "Invalid string literal" v lexbuf }
  | eof  { custom_error "Unexpected end of input" v lexbuf }

and finish_variant v = parse
    ':'  { let x = read_json v lexbuf in
           read_space v lexbuf;
           read_gt v lexbuf;
           Some x }
  | '>'  { None }
  | _    { long_error "Expected ':' or '>' but found" v lexbuf }
  | eof  { custom_error "Unexpected end of input" v lexbuf }

and read_lt v = parse
    '<'      { () }
  | _        { long_error "Expected '<' but found" v lexbuf }
  | eof      { custom_error "Unexpected end of input" v lexbuf }

and read_gt v = parse
    '>'  { () }
  | _    { long_error "Expected '>' but found" v lexbuf }
  | eof  { custom_error "Unexpected end of input" v lexbuf }

and read_comma v = parse
    ','  { () }
  | _    { long_error "Expected ',' but found" v lexbuf }
  | eof  { custom_error "Unexpected end of input" v lexbuf }

and start_any_variant v = parse
    '<'      { `Edgy_bracket }
  | '"'      { Buffer.clear v.buf;
               `Double_quote }
  | '['      { `Square_bracket }
  | _        { long_error "Expected '<', '\"' or '[' but found" v lexbuf }
  | eof      { custom_error "Unexpected end of input" v lexbuf }

and finish_comment v = parse
  | "*/" { () }
  | eof  { long_error "Unterminated comment" v lexbuf }
  | '\n' { newline v lexbuf; finish_comment v lexbuf }
  | _    { finish_comment v lexbuf }




(* Readers expecting a particular JSON construct *)

and read_eof = parse
    eof       { true }
  | ""        { false }

and read_space v = parse
  | "//"[^'\n']* ('\n'|eof)  { newline v lexbuf; read_space v lexbuf }
  | "/*"                     { finish_comment v lexbuf; read_space v lexbuf }
  | '\n'                     { newline v lexbuf; read_space v lexbuf }
  | [' ' '\t' '\r']+         { read_space v lexbuf }
  | ""                       { () }

and read_null v = parse
    "null"    { () }
  | _         { long_error "Expected 'null' but found" v lexbuf }
  | eof       { custom_error "Unexpected end of input" v lexbuf }

and read_null_if_possible v = parse
    "null"    { true }
  | ""        { false }

and read_bool v = parse
    "true"      { true }
  | "false"     { false }

  (* tolerate booleans passed as strings without \u obfuscation *)
  | "\"true\""  { true }
  | "\"false\"" { false }

  | _           { long_error "Expected 'true' or 'false' but found" v lexbuf }
  | eof         { custom_error "Unexpected end of input" v lexbuf }

and read_int v = parse
    positive_int         { try extract_positive_int lexbuf
                           with Int_overflow ->
                             lexer_error "Int overflow" v lexbuf }
  | '-' positive_int     { try extract_negative_int lexbuf
                           with Int_overflow ->
                             lexer_error "Int overflow" v lexbuf }
  | '"'                  { (* Support for double-quoted "ints" *)
                           Buffer.clear v.buf;
                           let s = finish_string v lexbuf in
                           try
                             (* Any OCaml-compliant int will pass,
                                including hexadecimal and octal notations,
                                and embedded underscores *)
                             int_of_string s
                           with _ ->
                             custom_error
                               "Expected an integer but found a string that \
                                doesn't even represent an integer"
                               v lexbuf
                         }
  | _                    { long_error "Expected integer but found" v lexbuf }
  | eof                  { custom_error "Unexpected end of input" v lexbuf }

and read_int32 v = parse
    '-'? positive_int    { try Int32.of_string (Lexing.lexeme lexbuf)
                           with _ ->
                             lexer_error "Int32 overflow" v lexbuf }
  | '"'                  { (* Support for double-quoted "ints" *)
                           Buffer.clear v.buf;
                           let s = finish_string v lexbuf in
                           try
                             (* Any OCaml-compliant int will pass,
                                including hexadecimal and octal notations,
                                and embedded underscores *)
                             Int32.of_string s
                           with _ ->
                             custom_error
                               "Expected an int32 but found a string that \
                                doesn't even represent an integer"
                               v lexbuf
                         }
  | _                    { long_error "Expected int32 but found" v lexbuf }
  | eof                  { custom_error "Unexpected end of input" v lexbuf }

and read_int64 v = parse
    '-'? positive_int    { try Int64.of_string (Lexing.lexeme lexbuf)
                           with _ ->
                             lexer_error "Int32 overflow" v lexbuf }
  | '"'                  { (* Support for double-quoted "ints" *)
                           Buffer.clear v.buf;
                           let s = finish_string v lexbuf in
                           try
                             (* Any OCaml-compliant int will pass,
                                including hexadecimal and octal notations,
                                and embedded underscores *)
                             Int64.of_string s
                           with _ ->
                             custom_error
                               "Expected an int64 but found a string that \
                                doesn't even represent an integer"
                               v lexbuf
                         }
  | _                    { long_error "Expected int64 but found" v lexbuf }
  | eof                  { custom_error "Unexpected end of input" v lexbuf }

and read_number v = parse
  | "NaN"       { nan }
  | "Infinity"  { infinity }
  | "-Infinity" { neg_infinity }
  | number      { float_of_string (Lexing.lexeme lexbuf) }
  | '"'         { Buffer.clear v.buf;
                  let s = finish_string v lexbuf in
                  try
                    (* Any OCaml-compliant float will pass,
                       including hexadecimal and octal notations,
                       and embedded underscores. *)
                    float_of_string s
                  with _ ->
                    match s with
                        "NaN" -> nan
                      | "Infinity" -> infinity
                      | "-Infinity" -> neg_infinity
                      | _ ->
                          custom_error
                            "Expected a number but found a string that \
                             doesn't even represent a number"
                            v lexbuf
                }
  | _           { long_error "Expected number but found" v lexbuf }
  | eof         { custom_error "Unexpected end of input" v lexbuf }

and read_string v = parse
    '"'      { Buffer.clear v.buf;
               finish_string v lexbuf }
  | _        { long_error "Expected '\"' but found" v lexbuf }
  | eof      { custom_error "Unexpected end of input" v lexbuf }

and read_ident v = parse
    '"'      { Buffer.clear v.buf;
               finish_string v lexbuf }
  | ident as s
             { s }
  | _        { long_error "Expected string or identifier but found" v lexbuf }
  | eof      { custom_error "Unexpected end of input" v lexbuf }

and map_ident v f = parse
    '"'      { Buffer.clear v.buf;
               map_string v f lexbuf }
  | ident
             { map_lexeme f lexbuf }
  | _        { long_error "Expected string or identifier but found" v lexbuf }
  | eof      { custom_error "Unexpected end of input" v lexbuf }

and read_sequence read_cell init_acc v = parse
    '['      { let acc = ref init_acc in
               try
                 read_space v lexbuf;
                 read_array_end lexbuf;
                 acc := read_cell !acc v lexbuf;
                 while true do
                   read_space v lexbuf;
                   read_array_sep v lexbuf;
                   read_space v lexbuf;
                   acc := read_cell !acc v lexbuf;
                 done;
                 assert false
               with Common.End_of_array ->
                 !acc
             }
  | _        { long_error "Expected '[' but found" v lexbuf }
  | eof      { custom_error "Unexpected end of input" v lexbuf }

and read_list_rev read_cell v = parse
    '['      { let acc = ref [] in
               try
                 read_space v lexbuf;
                 read_array_end lexbuf;
                 acc := read_cell v lexbuf :: !acc;
                 while true do
                   read_space v lexbuf;
                   read_array_sep v lexbuf;
                   read_space v lexbuf;
                   acc := read_cell v lexbuf :: !acc;
                 done;
                 assert false
               with Common.End_of_array ->
                 !acc
             }
  | _        { long_error "Expected '[' but found" v lexbuf }
  | eof      { custom_error "Unexpected end of input" v lexbuf }

and read_array_end = parse
    ']'      { raise Common.End_of_array }
  | ""       { () }

and read_array_sep v = parse
    ','      { () }
  | ']'      { raise Common.End_of_array }
  | _        { long_error "Expected ',' or ']' but found" v lexbuf }
  | eof      { custom_error "Unexpected end of input" v lexbuf }


and read_tuple read_cell init_acc v = parse
    '('          {
                   #ifdef TUPLE
                     let pos = ref 0 in
                     let acc = ref init_acc in
                     try
                       read_space v lexbuf;
                       read_tuple_end lexbuf;
                       acc := read_cell !pos !acc v lexbuf;
                       incr pos;
                       while true do
                         read_space v lexbuf;
                         read_tuple_sep v lexbuf;
                         read_space v lexbuf;
                         acc := read_cell !pos !acc v lexbuf;
                         incr pos;
                       done;
                       assert false
                     with Common.End_of_tuple ->
                       !acc
                   #else
                     long_error "Invalid token" v lexbuf
                   #endif
                 }
  | _        { long_error "Expected ')' but found" v lexbuf }
  | eof      { custom_error "Unexpected end of input" v lexbuf }

and read_tuple_end = parse
    ')'      { raise Common.End_of_tuple }
  | ""       { () }

and read_tuple_end2 v std = parse
    ')'      { if std then
                 long_error "Expected ')' or '' but found" v lexbuf
               else
                 raise Common.End_of_tuple }
  | ']'      { if std then
                 raise Common.End_of_tuple
               else
                 long_error "Expected ']' or '' but found" v lexbuf }
  | ""       { () }

and read_tuple_sep v = parse
    ','      { () }
  | ')'      { raise Common.End_of_tuple }
  | _        { long_error "Expected ',' or ')' but found" v lexbuf }
  | eof      { custom_error "Unexpected end of input" v lexbuf }

and read_tuple_sep2 v std = parse
    ','      { () }
  | ')'      { if std then
                 long_error "Expected ',' or ']' but found" v lexbuf
               else
                 raise Common.End_of_tuple }
  | ']'      { if std then
                 raise Common.End_of_tuple
               else
                 long_error "Expected ',' or ')' but found" v lexbuf }
  | _        { long_error "Expected ',' or ')' but found" v lexbuf }
  | eof      { custom_error "Unexpected end of input" v lexbuf }

(* Read a JSON object, reading the keys using a custom parser *)
and read_abstract_fields read_key read_field init_acc v = parse
    '{'      { let acc = ref init_acc in
               try
                 read_space v lexbuf;
                 read_object_end lexbuf;
                 let field_name = read_key v lexbuf in
                 read_space v lexbuf;
                 read_colon v lexbuf;
                 read_space v lexbuf;
                 acc := read_field !acc field_name v lexbuf;
                 while true do
                   read_space v lexbuf;
                   read_object_sep v lexbuf;
                   read_space v lexbuf;
                   let field_name = read_key v lexbuf in
                   read_space v lexbuf;
                   read_colon v lexbuf;
                   read_space v lexbuf;
                   acc := read_field !acc field_name v lexbuf;
                 done;
                 assert false
               with Common.End_of_object ->
                 !acc
             }
  | _        { long_error "Expected '{' but found" v lexbuf }
  | eof      { custom_error "Unexpected end of input" v lexbuf }

and read_lcurl v = parse
    '{'      { () }
  | _        { long_error "Expected '{' but found" v lexbuf }
  | eof      { custom_error "Unexpected end of input" v lexbuf }

and read_object_end = parse
    '}'      { raise Common.End_of_object }
  | ""       { () }

and read_object_sep v = parse
    ','      { () }
  | '}'      { raise Common.End_of_object }
  | _        { long_error "Expected ',' or '}' but found" v lexbuf }
  | eof      { custom_error "Unexpected end of input" v lexbuf }

and read_colon v = parse
    ':'      { () }
  | _        { long_error "Expected ':' but found" v lexbuf }
  | eof      { custom_error "Unexpected end of input" v lexbuf }

and start_any_tuple v = parse
    '('      { false }
  | '['      { true }
  | _        { long_error "Expected '(' or '[' but found" v lexbuf }
  | eof      { custom_error "Unexpected end of input" v lexbuf }

and read_lpar v = parse
    '('      { () }
  | _        { long_error "Expected '(' but found" v lexbuf }
  | eof      { custom_error "Unexpected end of input" v lexbuf }

and read_rpar v = parse
    ')'      { () }
  | _        { long_error "Expected ')' but found" v lexbuf }
  | eof      { custom_error "Unexpected end of input" v lexbuf }

and read_lbr v = parse
    '['      { () }
  | _        { long_error "Expected '[' but found" v lexbuf }
  | eof      { custom_error "Unexpected end of input" v lexbuf }

and read_rbr v = parse
    ']'      { () }
  | _        { long_error "Expected ']' but found" v lexbuf }
  | eof      { custom_error "Unexpected end of input" v lexbuf }

(*** And now pretty much the same thing repeated,
     only for the purpose of skipping ignored field values ***)

and skip_json v = parse
  | "true"      { () }
  | "false"     { () }
  | "null"      { () }
  | "NaN"       { () }
  | "Infinity"  { () }
  | "-Infinity" { () }
  | '"'         { finish_skip_stringlit v lexbuf }
  | '-'? positive_int     { () }
  | float       { () }

  | '{'          { try
                     read_space v lexbuf;
                     read_object_end lexbuf;
                     skip_ident v lexbuf;
                     read_space v lexbuf;
                     read_colon v lexbuf;
                     read_space v lexbuf;
                     skip_json v lexbuf;
                     while true do
                       read_space v lexbuf;
                       read_object_sep v lexbuf;
                       read_space v lexbuf;
                       skip_ident v lexbuf;
                       read_space v lexbuf;
                       read_colon v lexbuf;
                       read_space v lexbuf;
                       skip_json v lexbuf;
                     done;
                     assert false
                   with Common.End_of_object ->
                     ()
                 }

  | '['          { try
                     read_space v lexbuf;
                     read_array_end lexbuf;
                     skip_json v lexbuf;
                     while true do
                       read_space v lexbuf;
                       read_array_sep v lexbuf;
                       read_space v lexbuf;
                       skip_json v lexbuf;
                     done;
                     assert false
                   with Common.End_of_array ->
                     ()
                 }

  | '('          {
                   #ifdef TUPLE
                     try
                       read_space v lexbuf;
                       read_tuple_end lexbuf;
                       skip_json v lexbuf;
                       while true do
                         read_space v lexbuf;
                         read_tuple_sep v lexbuf;
                         read_space v lexbuf;
                         skip_json v lexbuf;
                       done;
                       assert false
                     with Common.End_of_tuple ->
                       ()
                   #else
                     long_error "Invalid token" v lexbuf
                   #endif
                 }

  | '<'          {
                   #ifdef VARIANT
                     read_space v lexbuf;
                     skip_ident v lexbuf;
                     read_space v lexbuf;
                     finish_skip_variant v lexbuf
                   #else
                     long_error "Invalid token" v lexbuf
                   #endif
                 }

  | "//"[^'\n']* { skip_json v lexbuf }
  | "/*"         { finish_comment v lexbuf; skip_json v lexbuf }
  | "\n"         { newline v lexbuf; skip_json v lexbuf }
  | space        { skip_json v lexbuf }
  | eof          { custom_error "Unexpected end of input" v lexbuf }
  | _            { long_error "Invalid token" v lexbuf }


and finish_skip_stringlit v = parse
    ( '\\' (['"' '\\' '/' 'b' 'f' 'n' 'r' 't'] | 'u' hex hex hex hex)
    | [^'"' '\\'] )* '"'
         { () }
  | _    { long_error "Invalid string literal" v lexbuf }
  | eof  { custom_error "Unexpected end of input" v lexbuf }

and finish_skip_variant v = parse
    ':'  { skip_json v lexbuf;
           read_space v lexbuf;
           read_gt v lexbuf }
  | '>'  { () }
  | _    { long_error "Expected ':' or '>' but found" v lexbuf }
  | eof  { custom_error "Unexpected end of input" v lexbuf }

and skip_ident v = parse
    '"'      { finish_skip_stringlit v lexbuf }
  | ident    { () }
  | _        { long_error "Expected string or identifier but found" v lexbuf }
  | eof      { custom_error "Unexpected end of input" v lexbuf }

(*** And now pretty much the same thing repeated,
     only for the purpose of buffering deferred field values ***)

and buffer_json v = parse
  | "true"
  | "false"
  | "null"
  | "NaN"
  | "Infinity"
  | "-Infinity"
  | '-'? positive_int
  | float       { add_lexeme v.buf lexbuf }

  | '"'         { finish_buffer_stringlit v lexbuf }
  | '{'          { try
                     Buffer.add_char v.buf '{';
                     buffer_space v lexbuf;
                     buffer_object_end v lexbuf;
                     buffer_ident v lexbuf;
                     buffer_space v lexbuf;
                     buffer_colon v lexbuf;
                     buffer_space v lexbuf;
                     buffer_json v lexbuf;
                     while true do
                       buffer_space v lexbuf;
                       buffer_object_sep v lexbuf;
                       buffer_space v lexbuf;
                       buffer_ident v lexbuf;
                       buffer_space v lexbuf;
                       buffer_colon v lexbuf;
                       buffer_space v lexbuf;
                       buffer_json v lexbuf;
                     done;
                     assert false
                   with Common.End_of_object ->
                     ()
                 }

  | '['          { try
                     Buffer.add_char v.buf '[';
                     buffer_space v lexbuf;
                     buffer_array_end v lexbuf;
                     buffer_json v lexbuf;
                     while true do
                       buffer_space v lexbuf;
                       buffer_array_sep v lexbuf;
                       buffer_space v lexbuf;
                       buffer_json v lexbuf;
                     done;
                     assert false
                   with Common.End_of_array ->
                     ()
                 }

  | '('          {
                   #ifdef TUPLE
                     try
                       Buffer.add_char v.buf '(';
                       buffer_space v lexbuf;
                       buffer_tuple_end v lexbuf;
                       buffer_json v lexbuf;
                       while true do
                         buffer_space v lexbuf;
                         buffer_tuple_sep v lexbuf;
                         buffer_space v lexbuf;
                         buffer_json v lexbuf;
                       done;
                       assert false
                     with Common.End_of_tuple ->
                       ()
                   #else
                     long_error "Invalid token" v lexbuf
                   #endif
                 }

  | '<'          {
                   #ifdef VARIANT
                     Buffer.add_char v.buf '<';
                     buffer_space v lexbuf;
                     buffer_ident v lexbuf;
                     buffer_space v lexbuf;
                     finish_buffer_variant v lexbuf
                   #else
                     long_error "Invalid token" v lexbuf
                   #endif
                 }

  | "//"[^'\n']* { add_lexeme v.buf lexbuf; buffer_json v lexbuf }
  | "/*"         { Buffer.add_string v.buf "/*";
                   finish_buffer_comment v lexbuf;
                   buffer_json v lexbuf }
  | "\n"         { Buffer.add_char v.buf '\n';
                   newline v lexbuf;
                   buffer_json v lexbuf }
  | space        { add_lexeme v.buf lexbuf; buffer_json v lexbuf }
  | eof          { custom_error "Unexpected end of input" v lexbuf }
  | _            { long_error "Invalid token" v lexbuf }


and finish_buffer_stringlit v = parse
    ( '\\' (['"' '\\' '/' 'b' 'f' 'n' 'r' 't'] | 'u' hex hex hex hex)
    | [^'"' '\\'] )* '"'
         { Buffer.add_char v.buf '"';
           add_lexeme v.buf lexbuf
         }
  | _    { long_error "Invalid string literal" v lexbuf }
  | eof  { custom_error "Unexpected end of input" v lexbuf }

and finish_buffer_variant v = parse
    ':'  { Buffer.add_char v.buf ':';
           buffer_json v lexbuf;
           buffer_space v lexbuf;
           buffer_gt v lexbuf }
  | '>'  { Buffer.add_char v.buf '>' }
  | _    { long_error "Expected ':' or '>' but found" v lexbuf }
  | eof  { custom_error "Unexpected end of input" v lexbuf }

and buffer_ident v = parse
    '"'      { finish_buffer_stringlit v lexbuf }
  | ident    { add_lexeme v.buf lexbuf }
  | _        { long_error "Expected string or identifier but found" v lexbuf }
  | eof      { custom_error "Unexpected end of input" v lexbuf }

and buffer_space v = parse
  | "//"[^'\n']* ('\n'|eof)  {
    add_lexeme v.buf lexbuf;
    newline v lexbuf;
    buffer_space v lexbuf }
  | "/*"                     {
    Buffer.add_string v.buf "/*";
    finish_buffer_comment v lexbuf;
    buffer_space v lexbuf }
  | '\n'                     {
    Buffer.add_char v.buf '\n';
    newline v lexbuf;
    buffer_space v lexbuf }
  | [' ' '\t' '\r']+         {
    add_lexeme v.buf lexbuf;
    buffer_space v lexbuf }
  | ""                       { () }

and buffer_object_end v = parse
    '}'      {
      Buffer.add_char v.buf '}';
      raise Common.End_of_object }
  | ""       { () }

and buffer_object_sep v = parse
    ','      { Buffer.add_char v.buf ',' }
  | '}'      { Buffer.add_char v.buf '}'; raise Common.End_of_object }
  | _        { long_error "Expected ',' or '}' but found" v lexbuf }
  | eof      { custom_error "Unexpected end of input" v lexbuf }

and buffer_array_end v = parse
    ']'      { Buffer.add_char v.buf ']'; raise Common.End_of_array }
  | ""       { () }

and buffer_array_sep v = parse
    ','      { Buffer.add_char v.buf ',' }
  | ']'      { Buffer.add_char v.buf ']'; raise Common.End_of_array }
  | _        { long_error "Expected ',' or ']' but found" v lexbuf }
  | eof      { custom_error "Unexpected end of input" v lexbuf }

and buffer_tuple_end v = parse
    ')'      {
      Buffer.add_char v.buf ')';
      raise Common.End_of_tuple }
  | ""       { () }

and buffer_tuple_sep v = parse
    ','      { Buffer.add_char v.buf ',' }
  | ')'      { Buffer.add_char v.buf ')'; raise Common.End_of_tuple }
  | _        { long_error "Expected ',' or ')' but found" v lexbuf }
  | eof      { custom_error "Unexpected end of input" v lexbuf }

and buffer_colon v = parse
    ':'      { Buffer.add_char v.buf ':' }
  | _        { long_error "Expected ':' but found" v lexbuf }
  | eof      { custom_error "Unexpected end of input" v lexbuf }

and buffer_gt v = parse
    '>'  { Buffer.add_char v.buf '>' }
  | _    { long_error "Expected '>' but found" v lexbuf }
  | eof  { custom_error "Unexpected end of input" v lexbuf }

and finish_buffer_comment v = parse
  | "*/" { Buffer.add_string v.buf "*/" }
  | eof  { long_error "Unterminated comment" v lexbuf }
  | '\n' { Buffer.add_char v.buf '\n';
           newline v lexbuf;
           finish_buffer_comment v lexbuf }
  | _    { add_lexeme v.buf lexbuf; finish_buffer_comment v lexbuf }

{
  let _ = (read_json : lexer_state -> Lexing.lexbuf -> t)

  let read_t = read_json

  let read_int8 v lexbuf =
    let n = read_int v lexbuf in
    if n < 0 || n > 255 then
      lexer_error "Int8 overflow" v lexbuf
    else
      char_of_int n

  let read_list read_cell v lexbuf =
    List.rev (read_list_rev read_cell v lexbuf)

  let array_of_rev_list l =
    match l with
        [] -> [| |]
      | x :: tl ->
          let len = List.length l in
          let a = Array.make len x in
          let r = ref tl in
          for i = len - 2 downto 0 do
            a.(i) <- List.hd !r;
            r := List.tl !r
          done;
          a

  let read_array read_cell v lexbuf =
    let l = read_list_rev read_cell v lexbuf in
    array_of_rev_list l

  (* Read a JSON object, reading the keys into OCaml strings
     (provided for backward compatibility) *)
  let read_fields read_field init_acc v =
    read_abstract_fields read_ident read_field init_acc v

  let finish v lexbuf =
    read_space v lexbuf;
    if not (read_eof lexbuf) then
      long_error "Junk after end of JSON value:" v lexbuf

  let init_lexer = Common.init_lexer

  let from_lexbuf v ?(stream = false) lexbuf =
    read_space v lexbuf;

    let x =
      if read_eof lexbuf then
        raise Common.End_of_input
      else
        read_json v lexbuf
    in

    if not stream then
      finish v lexbuf;

    x


  let from_string ?buf ?fname ?lnum s =
    try
      let lexbuf = Lexing.from_string s in
      let v = init_lexer ?buf ?fname ?lnum () in
      from_lexbuf v lexbuf
    with Common.End_of_input ->
      Common.json_error "Blank input data"

  let from_channel ?buf ?fname ?lnum ic =
    try
      let lexbuf = Lexing.from_channel ic in
      let v = init_lexer ?buf ?fname ?lnum () in
      from_lexbuf v lexbuf
    with Common.End_of_input ->
      Common.json_error "Blank input data"

  let from_file ?buf ?fname ?lnum file =
    let ic = open_in file in
    try
      let x = from_channel ?buf ?fname ?lnum ic in
      close_in ic;
      x
    with e ->
      close_in_noerr ic;
      raise e

  exception Finally of exn * exn

  let seq_from_lexbuf v ?(fin = fun () -> ()) lexbuf =
    let stream = Some true in
    let rec f () =
      try Seq.Cons (from_lexbuf v ?stream lexbuf, f)
      with
          Common.End_of_input ->
            fin ();
            Seq.Nil
        | e ->
            (try fin () with fin_e -> raise (Finally (e, fin_e)));
            raise e
    in
    f

  let seq_from_string ?buf ?fname ?lnum s =
    let v = init_lexer ?buf ?fname ?lnum () in
    seq_from_lexbuf v (Lexing.from_string s)

  let seq_from_channel ?buf ?fin ?fname ?lnum ic =
    let lexbuf = Lexing.from_channel ic in
    let v = init_lexer ?buf ?fname ?lnum () in
    seq_from_lexbuf v ?fin lexbuf

  let seq_from_file ?buf ?fname ?lnum file =
    let ic = open_in file in
    let fin () = close_in ic in
    let fname =
      match fname with
          None -> Some file
        | x -> x
    in
    let lexbuf = Lexing.from_channel ic in
    let v = init_lexer ?buf ?fname ?lnum () in
    seq_from_lexbuf v ~fin lexbuf

  type json_line = [ `Json of t | `Exn of exn ]

  let lineseq_from_channel
      ?buf ?(fin = fun () -> ()) ?fname ?lnum:(lnum0 = 1) ic =
    let buf =
      match buf with
          None -> Some (Buffer.create 256)
        | Some _ -> buf
    in
    let rec f lnum = fun () ->
      try
        let line = input_line ic in
        Seq.Cons (`Json (from_string ?buf ?fname ~lnum line), f (lnum + 1))
      with
          End_of_file -> fin (); Seq.Nil
        | e -> Seq.Cons (`Exn e, f (lnum + 1))
    in
    f lnum0

  let lineseq_from_file ?buf ?fname ?lnum file =
    let ic = open_in file in
    let fin () = close_in ic in
    let fname =
      match fname with
          None -> Some file
        | x -> x
    in
    lineseq_from_channel ?buf ~fin ?fname ?lnum ic

  let prettify ?std s =
    pretty_to_string ?std (from_string s)

  let compact ?std:_ s =
    to_string (from_string s)
}