aboutsummaryrefslogtreecommitdiff
path: root/libbutl/json/pdjson.c
blob: ae10c9543c6ae63393f76a908e2406734c112fb3 (plain)
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
#ifndef _POSIX_C_SOURCE
#  define _POSIX_C_SOURCE 200112L
#elif _POSIX_C_SOURCE < 200112L
#  error incompatible _POSIX_C_SOURCE level
#endif

#include <stdlib.h>
#include <string.h>
#include <ctype.h>

#ifndef PDJSON_H
#  include "pdjson.h"
#endif

#define JSON_FLAG_ERROR      (1u << 0)
#define JSON_FLAG_STREAMING  (1u << 1)

#if defined(_MSC_VER) && (_MSC_VER < 1900)

#define json_error(json, format, ...)                             \
    if (!(json->flags & JSON_FLAG_ERROR)) {                       \
        json->flags |= JSON_FLAG_ERROR;                           \
        _snprintf_s(json->errmsg, sizeof(json->errmsg),           \
                 _TRUNCATE,                                       \
                 format,                                          \
                 __VA_ARGS__);                                    \
    }                                                             \

#else

#define json_error(json, format, ...)                             \
    if (!(json->flags & JSON_FLAG_ERROR)) {                       \
        json->flags |= JSON_FLAG_ERROR;                           \
        snprintf(json->errmsg, sizeof(json->errmsg),              \
                 format,                                          \
                 __VA_ARGS__);                                    \
    }                                                             \

#endif /* _MSC_VER */

/* See also PDJSON_STACK_MAX below. */
#ifndef PDJSON_STACK_INC
#  define PDJSON_STACK_INC 4
#endif

struct json_stack {
    enum json_type type;
    long count;
};

static enum json_type
push(json_stream *json, enum json_type type)
{
    json->stack_top++;

#ifdef PDJSON_STACK_MAX
    if (json->stack_top > PDJSON_STACK_MAX) {
        json_error(json, "%s", "maximum depth of nesting reached");
        return JSON_ERROR;
    }
#endif

    if (json->stack_top >= json->stack_size) {
        struct json_stack *stack;
        size_t size = (json->stack_size + PDJSON_STACK_INC) * sizeof(*json->stack);
        stack = (struct json_stack *)json->alloc.realloc(json->stack, size);
        if (stack == NULL) {
            json_error(json, "%s", "out of memory");
            return JSON_ERROR;
        }

        json->stack_size += PDJSON_STACK_INC;
        json->stack = stack;
    }

    json->stack[json->stack_top].type = type;
    json->stack[json->stack_top].count = 0;

    return type;
}

/* Note: c is assumed not to be EOF. */
static enum json_type
pop(json_stream *json, int c, enum json_type expected)
{
    if (json->stack == NULL || json->stack[json->stack_top].type != expected) {
        json_error(json, "unexpected byte '%c'", c);
        return JSON_ERROR;
    }
    json->stack_top--;
    return expected == JSON_ARRAY ? JSON_ARRAY_END : JSON_OBJECT_END;
}

static int buffer_peek(struct json_source *source)
{
    if (source->position < source->source.buffer.length)
        return source->source.buffer.buffer[source->position];
    else
        return EOF;
}

static int buffer_get(struct json_source *source)
{
    int c = source->peek(source);
    if (c != EOF)
        source->position++;
    return c;
}

static int stream_get(struct json_source *source)
{
    int c = fgetc(source->source.stream.stream);
    if (c != EOF)
        source->position++;
    return c;
}

static int stream_peek(struct json_source *source)
{
    int c = fgetc(source->source.stream.stream);
    ungetc(c, source->source.stream.stream);
    return c;
}

static void init(json_stream *json)
{
    json->lineno = 1;
    json->linepos = 0;
    json->lineadj = 0;
    json->linecon = 0;
    json->colno = 0;
    json->flags = JSON_FLAG_STREAMING;
    json->errmsg[0] = '\0';
    json->ntokens = 0;
    json->next = (enum json_type)0;

    json->stack = NULL;
    json->stack_top = -1;
    json->stack_size = 0;

    json->data.string = NULL;
    json->data.string_size = 0;
    json->data.string_fill = 0;
    json->source.position = 0;

    json->alloc.malloc = malloc;
    json->alloc.realloc = realloc;
    json->alloc.free = free;
}

static enum json_type
is_match(json_stream *json, const char *pattern, enum json_type type)
{
    int c;
    for (const char *p = pattern; *p; p++) {
        if (*p != (c = json->source.get(&json->source))) {
            if (c != EOF) {
                json_error(json, "expected '%c' instead of byte '%c'", *p, c);
            } else {
                json_error(json, "expected '%c' instead of end of text", *p);
            }
            return JSON_ERROR;
        }
    }
    return type;
}

static int pushchar(json_stream *json, int c)
{
    if (json->data.string_fill == json->data.string_size) {
        size_t size = json->data.string_size * 2;
        char *buffer = (char *)json->alloc.realloc(json->data.string, size);
        if (buffer == NULL) {
            json_error(json, "%s", "out of memory");
            return -1;
        } else {
            json->data.string_size = size;
            json->data.string = buffer;
        }
    }
    json->data.string[json->data.string_fill++] = c;
    return 0;
}

static int init_string(json_stream *json)
{
    json->data.string_fill = 0;
    if (json->data.string == NULL) {
        json->data.string_size = 1024;
        json->data.string = (char *)json->alloc.malloc(json->data.string_size);
        if (json->data.string == NULL) {
            json_error(json, "%s", "out of memory");
            return -1;
        }
    }
    json->data.string[0] = '\0';
    return 0;
}

static int encode_utf8(json_stream *json, unsigned long c)
{
    if (c < 0x80UL) {
        return pushchar(json, c);
    } else if (c < 0x0800UL) {
        return !((pushchar(json, (c >> 6 & 0x1F) | 0xC0) == 0) &&
                 (pushchar(json, (c >> 0 & 0x3F) | 0x80) == 0));
    } else if (c < 0x010000UL) {
        if (c >= 0xd800 && c <= 0xdfff) {
            json_error(json, "invalid codepoint %06lx", c);
            return -1;
        }
        return !((pushchar(json, (c >> 12 & 0x0F) | 0xE0) == 0) &&
                 (pushchar(json, (c >>  6 & 0x3F) | 0x80) == 0) &&
                 (pushchar(json, (c >>  0 & 0x3F) | 0x80) == 0));
    } else if (c < 0x110000UL) {
        return !((pushchar(json, (c >> 18 & 0x07) | 0xF0) == 0) &&
                (pushchar(json, (c >> 12 & 0x3F) | 0x80) == 0) &&
                (pushchar(json, (c >> 6  & 0x3F) | 0x80) == 0) &&
                (pushchar(json, (c >> 0  & 0x3F) | 0x80) == 0));
    } else {
        json_error(json, "unable to encode %06lx as UTF-8", c);
        return -1;
    }
}

static int hexchar(int c)
{
    switch (c) {
    case '0': return 0;
    case '1': return 1;
    case '2': return 2;
    case '3': return 3;
    case '4': return 4;
    case '5': return 5;
    case '6': return 6;
    case '7': return 7;
    case '8': return 8;
    case '9': return 9;
    case 'a':
    case 'A': return 10;
    case 'b':
    case 'B': return 11;
    case 'c':
    case 'C': return 12;
    case 'd':
    case 'D': return 13;
    case 'e':
    case 'E': return 14;
    case 'f':
    case 'F': return 15;
    default:
        return -1;
    }
}

static long
read_unicode_cp(json_stream *json)
{
    long cp = 0;
    int shift = 12;

    for (size_t i = 0; i < 4; i++) {
        int c = json->source.get(&json->source);
        int hc;

        if (c == EOF) {
            json_error(json, "%s", "unterminated string literal in Unicode");
            return -1;
        } else if ((hc = hexchar(c)) == -1) {
            json_error(json, "invalid escape Unicode byte '%c'", c);
            return -1;
        }

        cp += hc * (1 << shift);
        shift -= 4;
    }


    return cp;
}

static int read_unicode(json_stream *json)
{
    long cp, h, l;

    if ((cp = read_unicode_cp(json)) == -1) {
        return -1;
    }

    if (cp >= 0xd800 && cp <= 0xdbff) {
        /* This is the high portion of a surrogate pair; we need to read the
         * lower portion to get the codepoint
         */
        h = cp;

        int c = json->source.get(&json->source);
        if (c == EOF) {
            json_error(json, "%s", "unterminated string literal in Unicode");
            return -1;
        } else if (c != '\\') {
            json_error(json, "invalid continuation for surrogate pair '%c', "
                             "expected '\\'", c);
            return -1;
        }

        c = json->source.get(&json->source);
        if (c == EOF) {
            json_error(json, "%s", "unterminated string literal in Unicode");
            return -1;
        } else if (c != 'u') {
            json_error(json, "invalid continuation for surrogate pair '%c', "
                             "expected 'u'", c);
            return -1;
        }

        if ((l = read_unicode_cp(json)) == -1) {
            return -1;
        }

        if (l < 0xdc00 || l > 0xdfff) {
            json_error(json, "surrogate pair continuation \\u%04lx out "
                             "of range (dc00-dfff)", l);
            return -1;
        }

        cp = ((h - 0xd800) * 0x400) + ((l - 0xdc00) + 0x10000);
    } else if (cp >= 0xdc00 && cp <= 0xdfff) {
            json_error(json, "dangling surrogate \\u%04lx", cp);
            return -1;
    }

    return encode_utf8(json, cp);
}

static int
read_escaped(json_stream *json)
{
    int c = json->source.get(&json->source);
    if (c == EOF) {
        json_error(json, "%s", "unterminated string literal in escape");
        return -1;
    } else if (c == 'u') {
        if (read_unicode(json) != 0)
            return -1;
    } else {
        switch (c) {
        case '\\':
        case 'b':
        case 'f':
        case 'n':
        case 'r':
        case 't':
        case '/':
        case '"':
            {
                const char *codes = "\\bfnrt/\"";
                const char *p = strchr(codes, c);
                if (pushchar(json, "\\\b\f\n\r\t/\""[p - codes]) != 0)
                    return -1;
            }
            break;
        default:
            json_error(json, "invalid escaped byte '%c'", c);
            return -1;
        }
    }
    return 0;
}

static int
char_needs_escaping(int c)
{
    if ((c >= 0) && (c < 0x20 || c == 0x22 || c == 0x5c)) {
        return 1;
    }

    return 0;
}

static int
utf8_seq_length(char byte)
{
    unsigned char u = (unsigned char) byte;
    if (u < 0x80) return 1;

    if (0x80 <= u && u <= 0xBF)
    {
        // second, third or fourth byte of a multi-byte
        // sequence, i.e. a "continuation byte"
        return 0;
    }
    else if (u == 0xC0 || u == 0xC1)
    {
        // overlong encoding of an ASCII byte
        return 0;
    }
    else if (0xC2 <= u && u <= 0xDF)
    {
        // 2-byte sequence
        return 2;
    }
    else if (0xE0 <= u && u <= 0xEF)
    {
        // 3-byte sequence
        return 3;
    }
    else if (0xF0 <= u && u <= 0xF4)
    {
        // 4-byte sequence
        return 4;
    }
    else
    {
        // u >= 0xF5
        // Restricted (start of 4-, 5- or 6-byte sequence) or invalid UTF-8
        return 0;
    }
}

static int
is_legal_utf8(const unsigned char *bytes, int length)
{
    if (0 == bytes || 0 == length) return 0;

    unsigned char a;
    const unsigned char* srcptr = bytes + length;
    switch (length)
    {
    default:
        return 0;
        // Everything else falls through when true.
    case 4:
        if ((a = (*--srcptr)) < 0x80 || a > 0xBF) return 0;
        /* FALLTHRU */
    case 3:
        if ((a = (*--srcptr)) < 0x80 || a > 0xBF) return 0;
        /* FALLTHRU */
    case 2:
        a = (*--srcptr);
        switch (*bytes)
        {
        case 0xE0:
            if (a < 0xA0 || a > 0xBF) return 0;
            break;
        case 0xED:
            if (a < 0x80 || a > 0x9F) return 0;
            break;
        case 0xF0:
            if (a < 0x90 || a > 0xBF) return 0;
            break;
        case 0xF4:
            if (a < 0x80 || a > 0x8F) return 0;
            break;
        default:
            if (a < 0x80 || a > 0xBF) return 0;
            break;
        }
        /* FALLTHRU */
    case 1:
        if (*bytes >= 0x80 && *bytes < 0xC2) return 0;
    }
    return *bytes <= 0xF4;
}

static int
read_utf8(json_stream* json, int next_char)
{
    int count = utf8_seq_length(next_char);
    if (!count)
    {
        json_error(json, "%s", "invalid UTF-8 character");
        return -1;
    }

    char buffer[4];
    buffer[0] = next_char;
    int i;
    for (i = 1; i < count; ++i)
    {
        if ((next_char = json->source.get(&json->source)) == EOF)
            break;

        buffer[i] = next_char;
        json->lineadj++;
    }

    if (i != count || !is_legal_utf8((unsigned char*) buffer, count))
    {
        json_error(json, "%s", "invalid UTF-8 text");
        return -1;
    }

    for (i = 0; i < count; ++i)
    {
        if (pushchar(json, buffer[i]) != 0)
            return -1;
    }
    return 0;
}

static enum json_type
read_string(json_stream *json)
{
    if (init_string(json) != 0)
        return JSON_ERROR;
    while (1) {
        int c = json->source.get(&json->source);
        if (c == EOF) {
            json_error(json, "%s", "unterminated string literal");
            return JSON_ERROR;
        } else if (c == '"') {
            if (pushchar(json, '\0') == 0)
                return JSON_STRING;
            else
                return JSON_ERROR;
        } else if (c == '\\') {
            if (read_escaped(json) != 0)
                return JSON_ERROR;
        } else if ((unsigned) c >= 0x80) {
            if (read_utf8(json, c) != 0)
                return JSON_ERROR;
        } else {
            if (char_needs_escaping(c)) {
                json_error(json, "%s", "unescaped control character in string");
                return JSON_ERROR;
            }

            if (pushchar(json, c) != 0)
                return JSON_ERROR;
        }
    }
    return JSON_ERROR;
}

static int
is_digit(int c)
{
    return c >= 48 /*0*/ && c <= 57 /*9*/;
}

static int
read_digits(json_stream *json)
{
    int c;
    unsigned nread = 0;
    while (is_digit(c = json->source.peek(&json->source))) {
        if (pushchar(json, json->source.get(&json->source)) != 0)
            return -1;

        nread++;
    }

    if (nread == 0) {
        if (c != EOF) {
            json_error(json, "expected digit instead of byte '%c'", c);
        } else {
            json_error(json, "%s", "expected digit instead of end of text");
        }
        return -1;
    }

    return 0;
}

static enum json_type
read_number(json_stream *json, int c)
{
    if (pushchar(json, c) != 0)
        return JSON_ERROR;
    if (c == '-') {
        c = json->source.get(&json->source);
        if (is_digit(c)) {
            return read_number(json, c);
        } else {
            if (c != EOF) {
                json_error(json, "unexpected byte '%c' in number", c);
            } else {
                json_error(json, "%s", "unexpected end of text in number");
            }
            return JSON_ERROR;
        }
    } else if (strchr("123456789", c) != NULL) {
        c = json->source.peek(&json->source);
        if (is_digit(c)) {
            if (read_digits(json) != 0)
                return JSON_ERROR;
        }
    }
    /* Up to decimal or exponent has been read. */
    c = json->source.peek(&json->source);
    if (strchr(".eE", c) == NULL) {
        if (pushchar(json, '\0') != 0)
            return JSON_ERROR;
        else
            return JSON_NUMBER;
    }
    if (c == '.') {
        json->source.get(&json->source); // consume .
        if (pushchar(json, c) != 0)
            return JSON_ERROR;
        if (read_digits(json) != 0)
            return JSON_ERROR;
    }
    /* Check for exponent. */
    c = json->source.peek(&json->source);
    if (c == 'e' || c == 'E') {
        json->source.get(&json->source); // consume e/E
        if (pushchar(json, c) != 0)
            return JSON_ERROR;
        c = json->source.peek(&json->source);
        if (c == '+' || c == '-') {
            json->source.get(&json->source); // consume
            if (pushchar(json, c) != 0)
                return JSON_ERROR;
            if (read_digits(json) != 0)
                return JSON_ERROR;
        } else if (is_digit(c)) {
            if (read_digits(json) != 0)
                return JSON_ERROR;
        } else {
            json->source.get(&json->source); // consume (for column)
            if (c != EOF) {
                json_error(json, "unexpected byte '%c' in number", c);
            } else {
                json_error(json, "%s", "unexpected end of text in number");
            }
            return JSON_ERROR;
        }
    }
    if (pushchar(json, '\0') != 0)
        return JSON_ERROR;
    else
        return JSON_NUMBER;
}

bool
json_isspace(int c)
{
    switch (c) {
    case 0x09:
    case 0x0a:
    case 0x0d:
    case 0x20:
        return true;
    }

    return false;
}

static void newline(json_stream *json)
{
    json->lineno++;
    json->linepos = json->source.position;
    json->lineadj = 0;
    json->linecon = 0;
}

/* Returns the next non-whitespace character in the stream.
 *
 * Note that this is the only function (besides user-facing json_source_get())
 * that needs to worry about newline housekeeping.
 */
static int next(json_stream *json)
{
   int c;
   while (json_isspace(c = json->source.get(&json->source)))
       if (c == '\n')
           newline(json);
   return c;
}

static enum json_type
read_value(json_stream *json, int c)
{
    enum json_type type;
    size_t colno = json_get_column(json);

    json->ntokens++;

    switch (c) {
    case EOF:
        json_error(json, "%s", "unexpected end of text");
        type = JSON_ERROR;
        break;
    case '{':
        type = push(json, JSON_OBJECT);
        break;
    case '[':
        type = push(json, JSON_ARRAY);
        break;
    case '"':
        type = read_string(json);
        break;
    case 'n':
        type = is_match(json, "ull", JSON_NULL);
        break;
    case 'f':
        type = is_match(json, "alse", JSON_FALSE);
        break;
    case 't':
        type = is_match(json, "rue", JSON_TRUE);
        break;
    case '0':
    case '1':
    case '2':
    case '3':
    case '4':
    case '5':
    case '6':
    case '7':
    case '8':
    case '9':
    case '-':
        type = init_string(json) == 0 ? read_number(json, c) : JSON_ERROR;
        break;
    default:
        type = JSON_ERROR;
        json_error(json, "unexpected byte '%c' in value", c);
        break;
    }

    if (type != JSON_ERROR)
        json->colno = colno;

    return type;
}

enum json_type json_peek(json_stream *json)
{
    enum json_type next;
    if (json->next)
        next = json->next;
    else
        next = json->next = json_next(json);
    return next;
}

enum json_type json_next(json_stream *json)
{
    if (json->flags & JSON_FLAG_ERROR)
        return JSON_ERROR;
    if (json->next != 0) {
        enum json_type next = json->next;
        json->next = (enum json_type)0;
        return next;
    }

    json->colno = 0;

    if (json->ntokens > 0 && json->stack_top == (size_t)-1) {

        /* In the streaming mode leave any trailing whitespaces in the stream.
         * This allows the user to validate any desired separation between
         * values (such as newlines) using json_source_get/peek() with any
         * remaining whitespaces ignored as leading when we parse the next
         * value. */
        if (!(json->flags & JSON_FLAG_STREAMING)) {
            int c = next(json);
            if (c != EOF) {
                json_error(json, "expected end of text instead of byte '%c'", c);
                return JSON_ERROR;
            }
        }

        return JSON_DONE;
    }
    int c = next(json);
    if (json->stack_top == (size_t)-1) {
        if (c == EOF && (json->flags & JSON_FLAG_STREAMING))
            return JSON_DONE;

        return read_value(json, c);
    }
    if (json->stack[json->stack_top].type == JSON_ARRAY) {
        if (json->stack[json->stack_top].count == 0) {
            if (c == ']') {
                return pop(json, c, JSON_ARRAY);
            }
            json->stack[json->stack_top].count++;
            return read_value(json, c);
        } else if (c == ',') {
            json->stack[json->stack_top].count++;
            return read_value(json, next(json));
        } else if (c == ']') {
            return pop(json, c, JSON_ARRAY);
        } else {
            if (c != EOF) {
                json_error(json, "unexpected byte '%c'", c);
            } else {
                json_error(json, "%s", "unexpected end of text");
            }
            return JSON_ERROR;
        }
    } else if (json->stack[json->stack_top].type == JSON_OBJECT) {
        if (json->stack[json->stack_top].count == 0) {
            if (c == '}') {
                return pop(json, c, JSON_OBJECT);
            }

            /* No member name/value pairs yet. */
            enum json_type value = read_value(json, c);
            if (value != JSON_STRING) {
                if (value != JSON_ERROR)
                    json_error(json, "%s", "expected member name or '}'");
                return JSON_ERROR;
            } else {
                json->stack[json->stack_top].count++;
                return value;
            }
        } else if ((json->stack[json->stack_top].count % 2) == 0) {
            /* Expecting comma followed by member name. */
            if (c != ',' && c != '}') {
                json_error(json, "%s", "expected ',' or '}' after member value");
                return JSON_ERROR;
            } else if (c == '}') {
                return pop(json, c, JSON_OBJECT);
            } else {
                enum json_type value = read_value(json, next(json));
                if (value != JSON_STRING) {
                    if (value != JSON_ERROR)
                        json_error(json, "%s", "expected member name");
                    return JSON_ERROR;
                } else {
                    json->stack[json->stack_top].count++;
                    return value;
                }
            }
        } else if ((json->stack[json->stack_top].count % 2) == 1) {
            /* Expecting colon followed by value. */
            if (c != ':') {
                json_error(json, "%s", "expected ':' after member name");
                return JSON_ERROR;
            } else {
                json->stack[json->stack_top].count++;
                return read_value(json, next(json));
            }
        }
    }
    json_error(json, "%s", "invalid parser state");
    return JSON_ERROR;
}

void json_reset(json_stream *json)
{
    json->stack_top = -1;
    json->ntokens = 0;
    json->flags &= ~JSON_FLAG_ERROR;
    json->errmsg[0] = '\0';
}

enum json_type json_skip(json_stream *json)
{
    enum json_type type = json_next(json);
    size_t cnt_arr = 0;
    size_t cnt_obj = 0;

    for (enum json_type skip = type; ; skip = json_next(json)) {
        if (skip == JSON_ERROR || skip == JSON_DONE)
            return skip;

        if (skip == JSON_ARRAY) {
            ++cnt_arr;
        } else if (skip == JSON_ARRAY_END && cnt_arr > 0) {
            --cnt_arr;
        } else if (skip == JSON_OBJECT) {
            ++cnt_obj;
        } else if (skip == JSON_OBJECT_END && cnt_obj > 0) {
            --cnt_obj;
        }

        if (!cnt_arr && !cnt_obj)
            break;
    }

    return type;
}

enum json_type json_skip_until(json_stream *json, enum json_type type)
{
    while (1) {
        enum json_type skip = json_skip(json);

        if (skip == JSON_ERROR || skip == JSON_DONE)
            return skip;

        if (skip == type)
            break;
    }

    return type;
}

const char *json_get_string(json_stream *json, size_t *length)
{
    if (length != NULL)
        *length = json->data.string_fill;
    if (json->data.string == NULL)
        return "";
    else
        return json->data.string;
}

double json_get_number(json_stream *json)
{
    char *p = json->data.string;
    return p == NULL ? 0 : strtod(p, NULL);
}

const char *json_get_error(json_stream *json)
{
    return json->flags & JSON_FLAG_ERROR ? json->errmsg : NULL;
}

size_t json_get_lineno(json_stream *json)
{
    return json->lineno;
}

size_t json_get_position(json_stream *json)
{
    return json->source.position;
}

size_t json_get_column(json_stream *json)
{
    return json->colno == 0
               ? json->source.position == 0 ? 1 : json->source.position - json->linepos - json->lineadj
               : json->colno;
}

size_t json_get_depth(json_stream *json)
{
    return json->stack_top + 1;
}

/* Return the current parsing context, that is, JSON_OBJECT if we are inside
   an object, JSON_ARRAY if we are inside an array, and JSON_DONE if we are
   not yet/anymore in either.

   Additionally, for the first two cases, also return the number of parsing
   events that have already been observed at this level with json_next/peek().
   In particular, inside an object, an odd number would indicate that the just
   observed JSON_STRING event is a member name.
*/
enum json_type json_get_context(json_stream *json, size_t *count)
{
    if (json->stack_top == (size_t)-1)
        return JSON_DONE;

    if (count != NULL)
        *count = json->stack[json->stack_top].count;

    return json->stack[json->stack_top].type;
}

int json_source_get(json_stream *json)
{
    /* If the caller reads a multi-byte UTF-8 sequence, we expect them to read
     * it in its entirety. We also assume that any invalid bytes within such a
     * sequence belong to the same column (as opposed to starting a new column
     * or some such). */

    int c = json->source.get(&json->source);
    if (json->linecon > 0) {
        /* Expecting a continuation byte within a multi-byte UTF-8 sequence. */
        json->linecon--;
        if (c != EOF)
            json->lineadj++;
    } else if (c == '\n')
        newline(json);
    else if (c >= 0xC2 && c <= 0xF4) /* First in multi-byte UTF-8 sequence. */
        json->linecon = utf8_seq_length(c) - 1;

    return c;
}

int json_source_peek(json_stream *json)
{
    return json->source.peek(&json->source);
}

void json_open_buffer(json_stream *json, const void *buffer, size_t size)
{
    init(json);
    json->source.get = buffer_get;
    json->source.peek = buffer_peek;
    json->source.source.buffer.buffer = (const char *)buffer;
    json->source.source.buffer.length = size;
}

void json_open_string(json_stream *json, const char *string)
{
    json_open_buffer(json, string, strlen(string));
}

void json_open_stream(json_stream *json, FILE * stream)
{
    init(json);
    json->source.get = stream_get;
    json->source.peek = stream_peek;
    json->source.source.stream.stream = stream;
}

static int user_get(struct json_source *json)
{
    int c = json->source.user.get(json->source.user.ptr);
    if (c != EOF)
        json->position++;
    return c;
}

static int user_peek(struct json_source *json)
{
    return json->source.user.peek(json->source.user.ptr);
}

void json_open_user(json_stream *json, json_user_io get, json_user_io peek, void *user)
{
    init(json);
    json->source.get = user_get;
    json->source.peek = user_peek;
    json->source.source.user.ptr = user;
    json->source.source.user.get = get;
    json->source.source.user.peek = peek;
}

void json_set_allocator(json_stream *json, json_allocator *a)
{
    json->alloc = *a;
}

void json_set_streaming(json_stream *json, bool streaming)
{
    if (streaming)
        json->flags |= JSON_FLAG_STREAMING;
    else
        json->flags &= ~JSON_FLAG_STREAMING;
}

void json_close(json_stream *json)
{
    json->alloc.free(json->stack);
    json->alloc.free(json->data.string);
}