-
Notifications
You must be signed in to change notification settings - Fork 5
/
json.c
1676 lines (1471 loc) · 43.6 KB
/
json.c
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
/*
* JSON Parser and serializer.
*
* * [www.json.org][json.org]
* * [RFC 7159][rfc7159]
* * [RFC 4627][rfc4627]
*
* See `json.h` for more info
*
* [json.org]: https://www.json.org/json-en.html
* [rfc7159]: https://tools.ietf.org/html/rfc7159
* [rfc4627]: https://tools.ietf.org/id/draft-ietf-json-rfc4627bis-09.html
*
*
* This is free and unencumbered software released into the public domain.
* https://unlicense.org/
*
* TODO: I came across this test suite for JSON parsers:
* [Parsing JSON is a Minefield](https://seriot.ch/parsing_json.php);
* I should maybe try running this parser through it one day.
*
* Here's some other examples why JSON parsing is a minefield:
* [Unintuitive JSON Parsing](https://nullprogram.com/blog/2019/12/28/)
*
* TODO: I'm not against extending this to [JSON5](https://json5.org/)
* in principle (See my comments about why I allow comments below).
* I'm thinking I should parse JSON5 and only emit strict JSON, or
* perhaps have separate `json_parse()` and `json_parse5()` functions
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdarg.h>
#include <stdint.h>
#include <assert.h>
#include <math.h>
#include "json.h"
typedef struct HashTable HashTable;
typedef struct Array Array;
/*
* I am aware of the reasons for [the JSON spec not supporting comments][no-comments],
* but I also subscribe to [Postel's Law][postel], so the parser has support for
* comments by default.
*
* The parser can be forced to be strict about not allowing comments by defining
* `JSON_COMMENTS` as 0.
*
* Serialization does not ever emit comments, though.
*
* [no-comments]: https://stackoverflow.com/a/10976934/115589
* [postel]: https://en.wikipedia.org/wiki/Robustness_principle
*/
#ifndef JSON_COMMENTS
# define JSON_COMMENTS 1
#endif
/*
* If `JSON_REENTRANT` is defined as 1 then each call to the
* functions `json_null()`, `json_true()` and `json_false()`
* returns a newly allocated object on the heap, making them
* reentrant (or at least as reentrant as your system's `malloc()`
* implementation).
*
* If it is defined as 0 then those functions return a reference
* to a global object of the value.
*
* The former is reentrant and thus thread safe. The latter
* saves memory and avoids some of the overheads of allocating
* the objects.
*
* Since the first call to one of the functions initialises the global
* variables and they are never modified thereafter,
* it is sufficient to call `json_release(json_null());` before
* spawning any threads to still have thread safety in the
* non-reentrant use case.
*/
#ifndef JSON_REENTRANT
# define JSON_REENTRANT 1
#endif
/*
* If you have a lot of duplicate strings in the JSON, then
* interning those strings may save memory and eliminate
* unnecessary allocations, though interning itself has some
* overheads.
*
* With string interning enabled, parsing this JSON example
* `[{"x":1,"y":2},{"x":3,"y":4},...]`
* will cause only a single `"x"` and a single `"y"` string
* object to be allocated.
*/
#ifndef JSON_INTERN_STRINGS
# define JSON_INTERN_STRINGS 1
#endif
/*
* The string interning functionality can use a red-black
* tree to keep the binary tree where the strings are stored
* for lookup balanced. A balanced tree may speed up lookup of
* strings a bit, but keeping the tree balanced introduces
* some other overheads.
*/
#ifndef JSON_USE_RED_BLACK
# define JSON_USE_RED_BLACK 1
#endif
/*
* Per section 6 of [rfc4627][]:
* _"Numeric values that cannot be represented in the grammar below
* (such as Infinity and NaN) are not permitted"_
*
* If `JSON_BAD_NUMBERS_AS_STRINGS` is zero then NaN, Infinity and
* -Infinity will be emitted as `null` by the serializer. This seems
* to correspond to how other JSON libraries handle the situation
* and is the default.
*
* If `JSON_BAD_NUMBERS_AS_STRINGS` is non-zero then NaN, Infinity and
* -Infinity will be emitted as the string values "NaN", "Infinity"
* and "-Infinity" respectively by the serializer.
*/
#ifndef JSON_BAD_NUMBERS_AS_STRINGS
# define JSON_BAD_NUMBERS_AS_STRINGS 0
#endif
/* =========================================================== */
struct json {
JSON_Type type;
union {
double number;
char *string;
HashTable *object;
Array *array;
} value;
size_t refcount;
};
/* =========================================================== */
#if JSON_INTERN_STRINGS
typedef struct internTreeNode ITNode;
typedef struct internTreeNodes TreeNodes;
static char *str_intern(TreeNodes *nodes, int *n, const char *str);
static char *str_make(const char *str);
static char *str_retain(char *str);
static void str_release(char *str);
#else
# define str_make(str) strdup(str)
# define str_release(str) free(str)
#endif
static char *_json_readfile(const char *fname);
static int _json_error(const char *fmt, ...);
int (*json_error)(const char *fmt, ...) = _json_error;
char *(*json_readfile)(const char *fname) = _json_readfile;
/* =============================================================
Hash Table
============================================================= */
#define HASH_SIZE 8
typedef struct HashElement {
char *name;
JSON *value;
} HashElement;
struct HashTable {
unsigned int allocated, count;
HashElement *table;
};
static HashTable *ht_create() {
HashTable *ht = malloc(sizeof *ht);
if(!ht)
return NULL;
ht->allocated = HASH_SIZE;
ht->table = calloc(ht->allocated, sizeof *ht->table);
if(!ht->table) {
free(ht);
return NULL;
}
ht->count = 0;
return ht;
}
static void ht_destroy(HashTable *ht) {
int i;
for(i = 0; i < ht->allocated; i++) {
if(ht->table[i].name) {
HashElement* v = &ht->table[i];
str_release(v->name);
json_release(v->value);
}
}
free(ht->table);
free(ht);
}
/*
FNV-1a hash, 32-bit version
https://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function
*/
static unsigned int hash(const char *s) {
unsigned int h = 0x811c9dc5;
for(;s[0];s++) {
h ^= (unsigned char)s[0];
h *= 0x01000193;
}
return h;
}
static HashElement *find_entry(HashElement *elements, unsigned int mask, const char *name) {
unsigned int h = hash(name) & mask;
for(;;) {
if(!elements[h].name || !strcmp(elements[h].name, name))
return &elements[h];
h = (h + 1) & mask;
}
return NULL;
}
static JSON *ht_put(HashTable *ht, char *name, JSON *j) {
assert(ht);
HashElement *f = find_entry(ht->table, ht->allocated - 1, name);
if(f->name) {
/* Replacing an existing entry */
str_release(f->name);
json_release(f->value);
} else {
/* new entry */
if(ht->count >= ht->allocated * 3 / 4) {
/* grow the table */
int new_size = (ht->allocated) << 1;
HashElement *new_table = calloc(new_size, sizeof *new_table);
if(!new_table)
return NULL;
unsigned int i;
for(i = 0; i <= ht->allocated - 1; i++) {
HashElement *from = &ht->table[i];
if(from->name) {
HashElement *to = find_entry(new_table, new_size-1, from->name);
to->name = from->name;
to->value = from->value;
}
}
free(ht->table);
ht->table = new_table;
ht->allocated = new_size;
f = find_entry(ht->table, ht->allocated - 1, name);
}
ht->count++;
}
f->name = name;
f->value = j;
return j;
}
static JSON *ht_get(HashTable *ht, const char *name) {
HashElement *v = find_entry(ht->table, ht->allocated - 1, name);
if(v->name)
return v->value;
return NULL;
}
static const char *ht_next(HashTable *ht, const char *name) {
unsigned int h = 0;
assert(ht->count < ht->allocated);
if(name) {
int oh;
oh = hash(name) & (ht->allocated - 1);
h = oh;
while(strcmp(ht->table[h].name, name)) {
if(!ht->table[h].name)
return NULL;
h = (h + 1) & (ht->allocated - 1);
}
if(++h >= ht->allocated)
return NULL;
}
while(!ht->table[h].name) {
if(++h >= ht->allocated)
return NULL;
}
return ht->table[h].name;
}
/* =============================================================
Arrays
============================================================= */
#define ARRAY_INITIAL_SIZE 8
struct Array {
JSON **elements;
size_t n, a;
};
static Array *ar_create() {
Array *a = malloc(sizeof *a);
if(!a)
return NULL;
a->n = 0;
a->a = ARRAY_INITIAL_SIZE;
a->elements = calloc(ARRAY_INITIAL_SIZE, sizeof *a->elements);
if(!a->elements) {
free(a);
return NULL;
}
return a;
}
static void ar_destroy(Array *a) {
int i;
for(i = 0; i < a->n; i++)
json_release(a->elements[i]);
free(a->elements);
free(a);
}
static JSON *ar_append(Array *a, JSON *v) {
if(a->n == a->a) {
a->a += a->a >> 1;
JSON **old = a->elements;
a->elements = realloc(a->elements, a->a * sizeof *a->elements);
if(!a->elements) {
a->elements = old;
return NULL;
}
}
a->elements[a->n++] = v;
return v;
}
/* =============================================================
String Interning
`str_intern()` returns a reference counted copy of its parameter. It looks up
the string in the collection of strings it has seen before. If it hasn't seen
the string before, it creates a copy with a reference count initialised to 1
and adds it to the collection, otherwise it increments the reference count of
the string in the collection and returns it.
The collection the strings are kept in is a Red-Black tree. The implementation
is just a straight forward adaption of the one in the [Wikipedia article][red-black].
The first parameter to `str_intern()` is a pointer to an `ITNode*` that forms
the root of this tree.
The reference counting works by storing an `unsigned int` in the bytes before
the `char*` returned by `str_intern()`. The `char*` can therefore be used like
a regular null-terminated C string.
Call `str_release()` to decrement the reference count. If the reference count
drops to zero, the memory is freed.
TODO: You might want to look into an [AA-Tree][aa-tree], but I'm not doing
that right now.
[red-black]: https://en.wikipedia.org/wiki/Red%E2%80%93black_tree#Insertion
[aa-tree]: https://en.wikipedia.org/wiki/AA_tree
============================================================= */
#if JSON_INTERN_STRINGS
static char *str_make(const char *str) {
size_t len = strlen(str);
unsigned int *rc = malloc((sizeof *rc) + len + 1);
char *data = (char*)rc + sizeof *rc;
*rc = 1;
memcpy(data, str, len);
data[len] = '\0';
return data;
}
static void str_release(char *str) {
unsigned int *rc = (unsigned int *)(str - sizeof *rc);
if(--(*rc) == 0)
free(rc);
}
static char *str_retain(char *str) {
unsigned int *rc = (unsigned int *)(str - sizeof *rc);
(*rc)++;
return str;
}
#define BLACK 0
#define RED 1
struct internTreeNode {
char *value;
#if JSON_USE_RED_BLACK
int color;
int parent;
#endif
int left, right;
};
struct internTreeNodes {
int a, n;
ITNode *array;
};
static int make_intern_node(TreeNodes *nodes, int parent, const char *str) {
if(nodes->n == nodes->a) {
nodes->a = nodes->a << 1;
ITNode *old = nodes->array;
nodes->array = realloc(nodes->array, nodes->a * sizeof *nodes->array);
if(!nodes->array) {
nodes->array = old;
return -1;
}
}
int n = nodes->n++;
ITNode *node = &nodes->array[n];
node->value = str_make(str);
#if JSON_USE_RED_BLACK
node->parent = parent;
node->color = RED;
#endif
node->left = -1;
node->right = -1;
return n;
}
static int do_str_intern(TreeNodes *nodes, int n, const char *str) {
assert(n >= 0 && n < nodes->n);
ITNode *array = nodes->array;
int i = strcmp(array[n].value, str);
if(i == 0) {
str_retain(array[n].value);
return n;
} else if(i > 0) {
int l = array[n].left;
if(l >= 0) {
return do_str_intern(nodes, l, str);
} else {
l = make_intern_node(nodes, n, str);
return (nodes->array[n].left = l);
}
} else { /* i < 0 */
int r = array[n].right;
if(r >= 0) {
return do_str_intern(nodes, r, str);
} else {
r = make_intern_node(nodes, n, str);
return (nodes->array[n].right = r);
}
}
}
#if JSON_USE_RED_BLACK
static void repair_tree(TreeNodes *nodes, int n);
#endif
static char *str_intern(TreeNodes *nodes, int *rootIndex, const char *str) {
int n;
if(*rootIndex < 0) {
n = make_intern_node(nodes, -1, str);
} else {
n = do_str_intern(nodes, *rootIndex, str);
}
if(n < 0)
return NULL;
#if JSON_USE_RED_BLACK
repair_tree(nodes, n);
/* FIXME: This way of finding the tree's root is
more complicated than it needs to be, because the only
time the root changes is in the line `array[nnew].parent = p;`
at the end of rotate_left() and rotate_right() if p < 0 */
int i = n;
while(nodes->array[i].parent >= 0) {
assert(i < nodes->n && i >= 0);
i = nodes->array[i].parent;
}
*rootIndex = i;
#else
if(*rootIndex < 0)
*rootIndex = n;
#endif
return nodes->array[n].value;
}
#if JSON_USE_RED_BLACK
/* Red-Black Tree */
static int uncle(TreeNodes *nodes, int n) {
assert(n >= 0 && n < nodes->n);
ITNode *array = nodes->array;
int p = array[n].parent;
if(p >= 0) {
int g = array[p].parent;
if(g >= 0)
return p == array[g].left ? array[g].right : array[g].left;
}
return -1;
}
/* FIXME: rotate_left and rotate_right can be simplified by
combining them into one function */
static void rotate_left(TreeNodes *nodes, int n) {
assert(n >= 0 && n < nodes->n);
ITNode *array = nodes->array;
int nnew = array[n].right;
int p = array[n].parent;
assert(nnew >= 0);
array[n].right = array[nnew].left;
array[nnew].left = n;
array[n].parent = nnew;
if(array[n].right >= 0) {
int r = array[n].right;
array[r].parent = n;
}
if(p >= 0) {
if(n == array[p].left)
array[p].left = nnew;
else
array[p].right = nnew;
}
array[nnew].parent = p;
}
static void rotate_right(TreeNodes *nodes, int n) {
assert(n >= 0 && n < nodes->n);
ITNode *array = nodes->array;
int nnew = array[n].left;
int p = array[n].parent;
assert(nnew >= 0);
array[n].left = array[nnew].right;
array[nnew].right = n;
array[n].parent = nnew;
if(array[n].left >= 0) {
int l = array[n].left;
array[l].parent = n;
}
if(p >= 0) {
if(n == array[p].left)
array[p].left = nnew;
else
array[p].right = nnew;
}
array[nnew].parent = p;
}
static void repair_tree(TreeNodes *nodes, int n) {
assert(n >= 0 && n < nodes->n);
ITNode *array = nodes->array;
int p = array[n].parent;
if(p < 0) {
/* case 1 */
array[n].color = BLACK;
} else if(array[p].color == BLACK) {
/* case 2 */
return;
} else {
int u = uncle(nodes, n);
int g = array[p].parent;
assert(g >= 0);
if(u >= 0 && array[u].color == RED) {
/* case 3 */
array[p].color = BLACK;
array[u].color = BLACK;
array[g].color = RED;
repair_tree(nodes, g);
} else {
/* case 4 */
if(n == array[p].right && p == array[g].left) {
rotate_left(nodes, p);
n = array[n].left;
p = array[n].parent;
g = array[p].parent;
} else if(n == array[p].left && p == array[g].right) {
rotate_right(nodes, p);
n = array[n].right;
p = array[n].parent;
g = array[p].parent;
}
/* case 4 step 2 */
assert(p >= 0 && g >= 0);
if(n == array[p].left)
rotate_right(nodes, g);
else
rotate_left(nodes, g);
array[p].color = BLACK;
array[g].color = RED;
}
}
}
#endif /* JSON_USE_RED_BLACK */
#endif /* JSON_INTERN_STRINGS */
/* =============================================================
Character buffer
============================================================= */
typedef struct {
size_t n, a;
char *buffer;
} Emitter;
static int emit(Emitter *e, char c) {
if(e->n + 1 == e->a) {
assert(e->a > 1);
e->a += e->a >> 1;
char *old = e->buffer;
e->buffer = realloc(e->buffer, e->a);
if(!e->buffer) {
e->buffer = old;
return 0;
}
}
e->buffer[e->n++] = c;
e->buffer[e->n] = '\0';
assert(e->n < e->a);
return 1;
}
static int emit_text(Emitter *e, const char *t) {
size_t len = strlen(t);
if(e->a < e->n + len + 1) {
assert(e->a > 1);
while(e->a < e->n + len + 1)
e->a += e->a >> 1;
char *old = e->buffer;
e->buffer = realloc(e->buffer, e->a);
if(!e->buffer) {
e->buffer = old;
return 0;
}
}
memcpy(e->buffer + e->n, t, len);
e->n += len;
e->buffer[e->n] = '\0';
assert(e->n < e->a);
return 1;
}
static int init_emitter(Emitter *e, size_t initial_size) {
e->a = initial_size;
e->n = 0;
e->buffer = malloc(e->a);
if(!e->buffer) {
json_error("out of memory");
return 0;
}
e->buffer[0] = '\0';
return 1;
}
/* =============================================================
Lexical Analyzer
============================================================= */
#define P_ERROR -1
#define P_END 0
#define P_NUMBER 1
#define P_STRING 2
#define P_NULL 3
#define P_TRUE 4
#define P_FALSE 5
#define P_BOM 99
typedef struct {
const char *in;
int sym;
int lineno;
Emitter e;
#if JSON_INTERN_STRINGS
TreeNodes internNodes;
int rootIndex;
#endif
} ParserContext;
static int getsym(ParserContext *pc);
static int init_parser(ParserContext *pc, const char *text) {
pc->in = text;
pc->sym = 0;
pc->lineno = 1;
if(!init_emitter(&pc->e, 32))
return 0;
#if JSON_INTERN_STRINGS
pc->internNodes.a = 32;
pc->internNodes.array = malloc(pc->internNodes.a * sizeof *pc->internNodes.array);
if(!pc->internNodes.array) {
json_error("out of memory");
free(pc->e.buffer);
return 0;
}
pc->internNodes.n = 0;
pc->rootIndex = -1;
#endif
/* load the first symbol */
if(getsym(pc) == P_ERROR) {
json_error("line %d: %s", pc->lineno, pc->e.buffer);
free(pc->e.buffer);
return 0;
}
return 1;
}
static void start_text(ParserContext *pc) {
pc->e.n = 0;
pc->e.buffer[0] = '\0';
}
static int append_char(ParserContext *pc, char c) {
return emit(&pc->e, c);
}
static void set_textf(ParserContext *pc, const char *fmt, ...) {
va_list arg;
va_start(arg, fmt);
char buffer[64];
vsnprintf(buffer, sizeof buffer, fmt, arg);
va_end(arg);
pc->e.n = 0;
pc->e.buffer[0] = '\0';
emit_text(&pc->e, buffer);
}
static void destroy_parser(ParserContext *pc) {
#if JSON_INTERN_STRINGS
if(pc->internNodes.array)
free(pc->internNodes.array);
#endif
if(pc->e.buffer)
free(pc->e.buffer);
}
static void codepoint_to_utf8(ParserContext *pc, uint32_t cp) {
if(cp <= 0x7F) {
append_char(pc, cp);
} else if(cp <= 0x07FF) {
append_char(pc, 0xC0 | (cp >> 6));
append_char(pc, 0x80 | (cp & 0x3F));
} else if(cp <= 0xFFFF) {
append_char(pc, 0xE0 | (cp >> 12));
append_char(pc, 0x80 | ((cp >> 6) & 0x3F));
append_char(pc, 0x80 | (cp & 0x3F));
} else if(cp <= 0x10FFFF) {
append_char(pc, 0xF0 | (cp >> 18));
append_char(pc, 0x80 | ((cp >> 12) & 0x3F));
append_char(pc, 0x80 | ((cp >> 6) & 0x3F));
append_char(pc, 0x80 | (cp & 0x3F));
} else {
append_char(pc, '?');
}
}
static int check_4_hex_digits(ParserContext *pc) {
return isxdigit(pc->in[0]) && isxdigit(pc->in[1]) && isxdigit(pc->in[2]) && isxdigit(pc->in[3]);
}
static uint32_t read_4_hex_digits(ParserContext *pc) {
uint32_t u = 0, i;
for(i = 0; i < 4; i++) {
if(pc->in[0] <= '9')
u = (u << 4) + pc->in[0] - '0';
else
u = (u << 4) + tolower(pc->in[0]) - 'a' + 0x0A;
pc->in++;
}
return u;
}
static int getsym(ParserContext *pc) {
#if JSON_COMMENTS
start:
#endif
/* if(pc->sym == P_ERROR) return P_ERROR; */
if(pc->in[0] == '\0') {
return (pc->sym = P_END);
}
while(isspace(pc->in[0])) {
if(pc->in[0] == '\n')
pc->lineno++;
pc->in++;
}
#if JSON_COMMENTS
if(pc->in[0] == '/' && pc->in[1] == '/') {
pc->in += 2;
while(pc->in[0] != '\n' && pc->in[0] != '\0')
pc->in++;
goto start;
} else if(pc->in[0] == '/' && pc->in[1] == '*') {
pc->in += 2;
while(pc->in[0] != '*' && pc->in[1] != '/') {
if(pc->in[0] == '\0') {
set_textf(pc, "unexpected end of file");
return (pc->sym = P_ERROR);
} else if(pc->in[0] == '\n')
pc->lineno++;
pc->in++;
}
pc->in+=2;
goto start;
}
#else
if(pc->in[0] == '/' && (pc->in[1] == '/' || pc->in[1] == '*')) {
set_textf(pc, "comments are not supported");
return (pc->sym = P_ERROR);
}
#endif
start_text(pc);
if(isalpha(pc->in[0])) {
while(isalpha(pc->in[0]))
append_char(pc, *(pc->in++));
if(!strcmp(pc->e.buffer, "null"))
return (pc->sym = P_NULL);
else if(!strcmp(pc->e.buffer, "true"))
return (pc->sym = P_TRUE);
else if(!strcmp(pc->e.buffer, "false"))
return (pc->sym = P_FALSE);
set_textf(pc, "unknown keyword '%s'", pc->e.buffer);
return (pc->sym = P_ERROR);
} else if(isdigit(pc->in[0]) || pc->in[0] == '-') {
pc->sym = P_NUMBER;
if(pc->in[0] == '-')
append_char(pc, *(pc->in++));
while(isdigit(pc->in[0]))
append_char(pc, *(pc->in++));
if(pc->in[0] == '.') {
append_char(pc, *(pc->in++));
while(isdigit(pc->in[0]))
append_char(pc, *(pc->in++));
}
if(tolower(pc->in[0]) == 'e') {
append_char(pc, *(pc->in++));
if(strchr("+-", pc->in[0]))
append_char(pc, *(pc->in++));
while(isdigit(pc->in[0]))
append_char(pc, *(pc->in++));
}
return (pc->sym = P_NUMBER);
} else if(pc->in[0] == '"') {
pc->in++;
while(pc->in[0] != '"') {
switch(pc->in[0]) {
case '\0' :
case '\n' : {
set_textf(pc, "unterminated string literal");
return (pc->sym = P_ERROR);
}
case '\\' : {
pc->in++;
switch(pc->in[0]) {
case '\0' : {
set_textf(pc, "unterminated string literal");
return (pc->sym = P_ERROR);
}
case '"' : append_char(pc, '"'); pc->in++; break;
case '\\' : append_char(pc, '\\'); pc->in++; break;
case '/' : append_char(pc, '/'); pc->in++; break;
case 'b' : append_char(pc, '\b'); pc->in++; break;
case 'f' : append_char(pc, '\f'); pc->in++; break;
case 'n' : append_char(pc, '\n'); pc->in++; break;
case 'r' : append_char(pc, '\r'); pc->in++; break;
case 't' : append_char(pc, '\t'); pc->in++; break;
case 'u' : {
pc->in++;
if(check_4_hex_digits(pc)) {
uint32_t u = read_4_hex_digits(pc);
if(u >= 0xD800 && u <= 0xDFFF) {
/* surrogate pair */
if(pc->in[0] != '\\' && pc->in[1]!='u') {
set_textf(pc, "expected a surrogate pair with \\u%04X", u);
return (pc->sym = P_ERROR);
}
pc->in += 2;
if(!check_4_hex_digits(pc)) {
set_textf(pc, "bad '\\uXXXX' sequence");
return (pc->sym = P_ERROR);
}
uint32_t hs = u, ls = read_4_hex_digits(pc);
u = (hs - 0xD800) * 0x400 + (ls - 0xDC00) + 0x10000;
}
codepoint_to_utf8(pc, u);
} else {
set_textf(pc, "bad '\\uXXXX' sequence");
return (pc->sym = P_ERROR);
}
} break;
default: {
set_textf(pc, "bad escape sequence '\\%c'", pc->in[0]);
return (pc->sym = P_ERROR);
}
}
} break;
default : {
append_char(pc, *(pc->in++));
} break;
}
}
pc->in++;
return (pc->sym = P_STRING);
} else if(strchr("{}[]:,", pc->in[0])) {
return (pc->sym = *(pc->in++));
} else {
set_textf(pc, "Unexpected token '%c'", pc->in[0]);
}
return (pc->sym = P_ERROR);
}
/* =============================================================
Parser
============================================================= */
JSON *json_retain(JSON *j) {
j->refcount++;
return j;
}
void json_release(JSON *j) {
if(!j)
return;
if(--j->refcount == 0) {
switch(j->type) {
case j_string: str_release(j->value.string); break;
case j_object: ht_destroy(j->value.object); break;
case j_array : ar_destroy(j->value.array); break;
default: break;
}
free(j);
}
}
static int accept(ParserContext *pc, int sym) {
if(pc->sym == sym) {
getsym(pc);
if(pc->sym == P_ERROR) {
json_error("line %d: %s", pc->lineno, pc->e.buffer);
return 0;
}
return 1;
}
return 0;
}
static JSON *json_parse_object(ParserContext *pc);
static JSON *json_parse_array(ParserContext *pc);
static JSON *json_parse_value(ParserContext *pc);
static JSON *json_parse_object(ParserContext *pc) {
JSON *v = json_new_object();
if(!v) {
json_error("out of memory");
return NULL;
}
accept(pc, '{');
if(pc->sym != '}') {
do {