json: New convenience function json_array_create_1().
[sliver-openvswitch.git] / lib / json.c
1 /*
2  * Copyright (c) 2009 Nicira Networks.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at:
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <config.h>
18
19 #include "json.h"
20
21 #include <assert.h>
22 #include <ctype.h>
23 #include <errno.h>
24 #include <float.h>
25 #include <limits.h>
26 #include <math.h>
27 #include <string.h>
28
29 #include "dynamic-string.h"
30 #include "hash.h"
31 #include "shash.h"
32 #include "unicode.h"
33 #include "util.h"
34
35 /* The type of a JSON token. */
36 enum json_token_type {
37     T_EOF = 0,
38     T_BEGIN_ARRAY = '[',
39     T_END_ARRAY = ']',
40     T_BEGIN_OBJECT = '{',
41     T_END_OBJECT = '}',
42     T_NAME_SEPARATOR = ':',
43     T_VALUE_SEPARATOR = ',',
44     T_FALSE = UCHAR_MAX + 1,
45     T_NULL,
46     T_TRUE,
47     T_INTEGER,
48     T_REAL,
49     T_STRING
50 };
51
52 /* A JSON token.
53  *
54  * RFC 4627 doesn't define a lexical structure for JSON but I believe this to
55  * be compliant with the standard.
56  */
57 struct json_token {
58     enum json_token_type type;
59     union {
60         double real;
61         long long int integer;
62         const char *string;
63     } u;
64 };
65
66 enum json_lex_state {
67     JSON_LEX_START,             /* Not inside a token. */
68     JSON_LEX_NUMBER,            /* Reading a number. */
69     JSON_LEX_KEYWORD,           /* Reading a keyword. */
70     JSON_LEX_STRING,            /* Reading a quoted string. */
71     JSON_LEX_ESCAPE             /* In a quoted string just after a "\". */
72 };
73
74 enum json_parse_state {
75     JSON_PARSE_START,           /* Beginning of input. */
76     JSON_PARSE_END,             /* End of input. */
77
78     /* Objects. */
79     JSON_PARSE_OBJECT_INIT,     /* Expecting '}' or an object name. */
80     JSON_PARSE_OBJECT_NAME,     /* Expecting an object name. */
81     JSON_PARSE_OBJECT_COLON,    /* Expecting ':'. */
82     JSON_PARSE_OBJECT_VALUE,    /* Expecting an object value. */
83     JSON_PARSE_OBJECT_NEXT,     /* Expecting ',' or '}'. */
84
85     /* Arrays. */
86     JSON_PARSE_ARRAY_INIT,      /* Expecting ']' or a value. */
87     JSON_PARSE_ARRAY_VALUE,     /* Expecting a value. */
88     JSON_PARSE_ARRAY_NEXT       /* Expecting ',' or ']'. */
89 };
90
91 struct json_parser_node {
92     struct json *json;
93 };
94
95 /* A JSON parser. */
96 struct json_parser {
97     int flags;
98
99     /* Lexical analysis. */
100     enum json_lex_state lex_state;
101     struct ds buffer;           /* Buffer for accumulating token text. */
102     int line_number;
103     int column_number;
104     int byte_number;
105
106     /* Parsing. */
107     enum json_parse_state parse_state;
108 #define JSON_MAX_HEIGHT 1000
109     struct json_parser_node *stack;
110     size_t height, allocated_height;
111     char *member_name;
112
113     /* Parse status. */
114     bool done;
115     char *error;                /* Error message, if any, null if none yet. */
116 };
117
118 static struct json *json_create(enum json_type type);
119 static void json_parser_input(struct json_parser *, struct json_token *);
120
121 static void json_error(struct json_parser *p, const char *format, ...)
122     PRINTF_FORMAT(2, 3);
123 \f
124 const char *
125 json_type_to_string(enum json_type type)
126 {
127     switch (type) {
128     case JSON_NULL:
129         return "null";
130
131     case JSON_FALSE:
132         return "false";
133
134     case JSON_TRUE:
135         return "true";
136
137     case JSON_OBJECT:
138         return "object";
139
140     case JSON_ARRAY:
141         return "array";
142
143     case JSON_INTEGER:
144     case JSON_REAL:
145         return "number";
146
147     case JSON_STRING:
148         return "string";
149
150     case JSON_N_TYPES:
151     default:
152         return "<invalid>";
153     }
154 }
155 \f
156 /* Functions for manipulating struct json. */
157
158 struct json *
159 json_null_create(void)
160 {
161     return json_create(JSON_NULL);
162 }
163
164 struct json *
165 json_boolean_create(bool b)
166 {
167     return json_create(b ? JSON_TRUE : JSON_FALSE);
168 }
169
170 struct json *
171 json_string_create_nocopy(char *s)
172 {
173     struct json *json = json_create(JSON_STRING);
174     json->u.string = s;
175     return json;
176 }
177
178 struct json *
179 json_string_create(const char *s)
180 {
181     return json_string_create_nocopy(xstrdup(s));
182 }
183
184 struct json *
185 json_array_create_empty(void)
186 {
187     struct json *json = json_create(JSON_ARRAY);
188     json->u.array.elems = NULL;
189     json->u.array.n = 0;
190     json->u.array.n_allocated = 0;
191     return json;
192 }
193
194 void
195 json_array_add(struct json *array_, struct json *element)
196 {
197     struct json_array *array = json_array(array_);
198     if (array->n >= array->n_allocated) {
199         array->elems = x2nrealloc(array->elems, &array->n_allocated,
200                                   sizeof *array->elems);
201     }
202     array->elems[array->n++] = element;
203 }
204
205 void
206 json_array_trim(struct json *array_)
207 {
208     struct json_array *array = json_array(array_);
209     if (array->n < array->n_allocated){
210         array->n_allocated = array->n;
211         array->elems = xrealloc(array->elems, array->n * sizeof *array->elems);
212     }
213 }
214
215 struct json *
216 json_array_create(struct json **elements, size_t n)
217 {
218     struct json *json = json_create(JSON_ARRAY);
219     json->u.array.elems = elements;
220     json->u.array.n = n;
221     json->u.array.n_allocated = n;
222     return json;
223 }
224
225 struct json *
226 json_array_create_1(struct json *elem0)
227 {
228     struct json **elems = xmalloc(sizeof *elems);
229     elems[0] = elem0;
230     return json_array_create(elems, 1);
231 }
232
233 struct json *
234 json_array_create_2(struct json *elem0, struct json *elem1)
235 {
236     struct json **elems = xmalloc(2 * sizeof *elems);
237     elems[0] = elem0;
238     elems[1] = elem1;
239     return json_array_create(elems, 2);
240 }
241
242 struct json *
243 json_array_create_3(struct json *elem0, struct json *elem1, struct json *elem2)
244 {
245     struct json **elems = xmalloc(3 * sizeof *elems);
246     elems[0] = elem0;
247     elems[1] = elem1;
248     elems[2] = elem2;
249     return json_array_create(elems, 3);
250 }
251
252 struct json *
253 json_object_create(void)
254 {
255     struct json *json = json_create(JSON_OBJECT);
256     json->u.object = xmalloc(sizeof *json->u.object);
257     shash_init(json->u.object);
258     return json;
259 }
260
261 struct json *
262 json_integer_create(long long int integer)
263 {
264     struct json *json = json_create(JSON_INTEGER);
265     json->u.integer = integer;
266     return json;
267 }
268
269 struct json *
270 json_real_create(double real)
271 {
272     struct json *json = json_create(JSON_REAL);
273     json->u.real = real;
274     return json;
275 }
276
277 void
278 json_object_put(struct json *json, const char *name, struct json *value)
279 {
280     shash_add(json->u.object, name, value);
281 }
282
283 void
284 json_object_put_string(struct json *json, const char *name, const char *value)
285 {
286     json_object_put(json, name, json_string_create(value));
287 }
288
289 const char *
290 json_string(const struct json *json)
291 {
292     assert(json->type == JSON_STRING);
293     return json->u.string;
294 }
295
296 struct json_array *
297 json_array(const struct json *json)
298 {
299     assert(json->type == JSON_ARRAY);
300     return (struct json_array *) &json->u.array;
301 }
302
303 struct shash *
304 json_object(const struct json *json)
305 {
306     assert(json->type == JSON_OBJECT);
307     return (struct shash *) json->u.object;
308 }
309
310 bool
311 json_boolean(const struct json *json)
312 {
313     assert(json->type == JSON_TRUE || json->type == JSON_FALSE);
314     return json->type == JSON_TRUE;
315 }
316
317 double
318 json_real(const struct json *json)
319 {
320     assert(json->type == JSON_REAL || json->type == JSON_INTEGER);
321     return json->type == JSON_REAL ? json->u.real : json->u.integer;
322 }
323
324 int64_t
325 json_integer(const struct json *json)
326 {
327     assert(json->type == JSON_INTEGER);
328     return json->u.integer;
329 }
330 \f
331 static void json_destroy_object(struct shash *object);
332 static void json_destroy_array(struct json_array *array);
333
334 /* Frees 'json' and everything it points to, recursively. */
335 void
336 json_destroy(struct json *json)
337 {
338     if (json) {
339         switch (json->type) {
340         case JSON_OBJECT:
341             json_destroy_object(json->u.object);
342             break;
343
344         case JSON_ARRAY:
345             json_destroy_array(&json->u.array);
346             break;
347
348         case JSON_STRING:
349             free(json->u.string);
350             break;
351
352         case JSON_NULL:
353         case JSON_FALSE:
354         case JSON_TRUE:
355         case JSON_INTEGER:
356         case JSON_REAL:
357             break;
358
359         case JSON_N_TYPES:
360             NOT_REACHED();
361         }
362         free(json);
363     }
364 }
365
366 static void
367 json_destroy_object(struct shash *object)
368 {
369     struct shash_node *node, *next;
370
371     SHASH_FOR_EACH_SAFE (node, next, object) {
372         struct json *value = node->data;
373
374         json_destroy(value);
375         shash_delete(object, node);
376     }
377     shash_destroy(object);
378     free(object);
379 }
380
381 static void
382 json_destroy_array(struct json_array *array)
383 {
384     size_t i;
385
386     for (i = 0; i < array->n; i++) {
387         json_destroy(array->elems[i]);
388     }
389     free(array->elems);
390 }
391 \f
392 static struct json *json_clone_object(const struct shash *object);
393 static struct json *json_clone_array(const struct json_array *array);
394
395 /* Returns a deep copy of 'json'. */
396 struct json *
397 json_clone(const struct json *json)
398 {
399     switch (json->type) {
400     case JSON_OBJECT:
401         return json_clone_object(json->u.object);
402
403     case JSON_ARRAY:
404         return json_clone_array(&json->u.array);
405
406     case JSON_STRING:
407         return json_string_create(json->u.string);
408
409     case JSON_NULL:
410     case JSON_FALSE:
411     case JSON_TRUE:
412         return json_create(json->type);
413
414     case JSON_INTEGER:
415         return json_integer_create(json->u.integer);
416
417     case JSON_REAL:
418         return json_real_create(json->u.real);
419
420     case JSON_N_TYPES:
421     default:
422         NOT_REACHED();
423     }
424 }
425
426 static struct json *
427 json_clone_object(const struct shash *object)
428 {
429     struct shash_node *node;
430     struct json *json;
431
432     json = json_object_create();
433     SHASH_FOR_EACH (node, object) {
434         struct json *value = node->data;
435         json_object_put(json, node->name, json_clone(value));
436     }
437     return json;
438 }
439
440 static struct json *
441 json_clone_array(const struct json_array *array)
442 {
443     struct json **elems;
444     size_t i;
445
446     elems = xmalloc(array->n * sizeof *elems);
447     for (i = 0; i < array->n; i++) {
448         elems[i] = json_clone(array->elems[i]);
449     }
450     return json_array_create(elems, array->n);
451 }
452 \f
453 static size_t
454 json_hash_object(const struct shash *object, size_t basis)
455 {
456     const struct shash_node **nodes;
457     size_t n, i;
458
459     nodes = shash_sort(object);
460     n = shash_count(object);
461     for (i = 0; i < n; i++) {
462         const struct shash_node *node = nodes[i];
463         basis = hash_string(node->name, basis);
464         basis = json_hash(node->data, basis);
465     }
466     return basis;
467 }
468
469 static size_t
470 json_hash_array(const struct json_array *array, size_t basis)
471 {
472     size_t i;
473
474     basis = hash_int(array->n, basis);
475     for (i = 0; i < array->n; i++) {
476         basis = json_hash(array->elems[i], basis);
477     }
478     return basis;
479 }
480
481 size_t
482 json_hash(const struct json *json, size_t basis)
483 {
484     switch (json->type) {
485     case JSON_OBJECT:
486         return json_hash_object(json->u.object, basis);
487
488     case JSON_ARRAY:
489         return json_hash_array(&json->u.array, basis);
490
491     case JSON_STRING:
492         return hash_string(json->u.string, basis);
493
494     case JSON_NULL:
495     case JSON_FALSE:
496     case JSON_TRUE:
497         return hash_int(json->type << 8, basis);
498
499     case JSON_INTEGER:
500         return hash_int(json->u.integer, basis);
501
502     case JSON_REAL:
503         return hash_double(json->u.real, basis);
504
505     case JSON_N_TYPES:
506     default:
507         NOT_REACHED();
508     }
509 }
510
511 static bool
512 json_equal_object(const struct shash *a, const struct shash *b)
513 {
514     struct shash_node *a_node;
515
516     if (shash_count(a) != shash_count(b)) {
517         return false;
518     }
519
520     SHASH_FOR_EACH (a_node, a) {
521         struct shash_node *b_node = shash_find(b, a_node->name);
522         if (!b_node || !json_equal(a_node->data, b_node->data)) {
523             return false;
524         }
525     }
526
527     return true;
528 }
529
530 static bool
531 json_equal_array(const struct json_array *a, const struct json_array *b)
532 {
533     size_t i;
534
535     if (a->n != b->n) {
536         return false;
537     }
538
539     for (i = 0; i < a->n; i++) {
540         if (!json_equal(a->elems[i], b->elems[i])) {
541             return false;
542         }
543     }
544
545     return true;
546 }
547
548 bool
549 json_equal(const struct json *a, const struct json *b)
550 {
551     if (a->type != b->type) {
552         return false;
553     }
554
555     switch (a->type) {
556     case JSON_OBJECT:
557         return json_equal_object(a->u.object, b->u.object);
558
559     case JSON_ARRAY:
560         return json_equal_array(&a->u.array, &b->u.array);
561
562     case JSON_STRING:
563         return !strcmp(a->u.string, b->u.string);
564
565     case JSON_NULL:
566     case JSON_FALSE:
567     case JSON_TRUE:
568         return true;
569
570     case JSON_INTEGER:
571         return a->u.integer == b->u.integer;
572
573     case JSON_REAL:
574         return a->u.real == b->u.real;
575
576     case JSON_N_TYPES:
577     default:
578         NOT_REACHED();
579     }
580 }
581 \f
582 /* Lexical analysis. */
583
584 static void
585 json_lex_keyword(struct json_parser *p)
586 {
587     struct json_token token;
588     const char *s;
589
590     s = ds_cstr(&p->buffer);
591     if (!strcmp(s, "false")) {
592         token.type = T_FALSE;
593     } else if (!strcmp(s, "true")) {
594         token.type = T_TRUE;
595     } else if (!strcmp(s, "null")) {
596         token.type = T_NULL;
597     } else {
598         json_error(p, "invalid keyword '%s'", s);
599         return;
600     }
601     json_parser_input(p, &token);
602 }
603
604 static void
605 json_lex_number(struct json_parser *p)
606 {
607     const char *cp = ds_cstr(&p->buffer);
608     unsigned long long int significand = 0;
609     int sig_digits = 0;
610     bool imprecise = false;
611     bool negative = false;
612     int pow10 = 0;
613
614     /* Leading minus sign. */
615     if (*cp == '-') {
616         negative = true;
617         cp++;
618     }
619
620     /* At least one integer digit, but 0 may not be used as a leading digit for
621      * a longer number. */
622     significand = 0;
623     sig_digits = 0;
624     if (*cp == '0') {
625         cp++;
626         if (isdigit(*cp)) {
627             json_error(p, "leading zeros not allowed");
628             return;
629         }
630     } else if (isdigit(*cp)) {
631         do {
632             if (significand <= ULLONG_MAX / 10) {
633                 significand = significand * 10 + (*cp - '0');
634                 sig_digits++;
635             } else {
636                 pow10++;
637                 if (*cp != '0') {
638                     imprecise = true;
639                 }
640             }
641             cp++;
642         } while (isdigit(*cp));
643     } else {
644         json_error(p, "'-' must be followed by digit");
645         return;
646     }
647
648     /* Optional fraction. */
649     if (*cp == '.') {
650         cp++;
651         if (!isdigit(*cp)) {
652             json_error(p, "decimal point must be followed by digit");
653             return;
654         }
655         do {
656             if (significand <= ULLONG_MAX / 10) {
657                 significand = significand * 10 + (*cp - '0');
658                 sig_digits++;
659                 pow10--;
660             } else if (*cp != '0') {
661                 imprecise = true;
662             }
663             cp++;
664         } while (isdigit(*cp));
665     }
666
667     /* Optional exponent. */
668     if (*cp == 'e' || *cp == 'E') {
669         bool negative_exponent = false;
670         int exponent;
671
672         cp++;
673         if (*cp == '+') {
674             cp++;
675         } else if (*cp == '-') {
676             negative_exponent = true;
677             cp++;
678         }
679
680         if (!isdigit(*cp)) {
681             json_error(p, "exponent must contain at least one digit");
682             return;
683         }
684
685         exponent = 0;
686         do {
687             if (exponent >= INT_MAX / 10) {
688                 json_error(p, "exponent outside valid range");
689                 return;
690             }
691             exponent = exponent * 10 + (*cp - '0');
692             cp++;
693         } while (isdigit(*cp));
694
695         if (negative_exponent) {
696             pow10 -= exponent;
697         } else {
698             pow10 += exponent;
699         }
700     }
701
702     if (*cp != '\0') {
703         json_error(p, "syntax error in number");
704         return;
705     }
706
707     /* Figure out number.
708      *
709      * We suppress negative zeros as a matter of policy. */
710     if (!significand) {
711         struct json_token token;
712         token.type = T_INTEGER;
713         token.u.integer = 0;
714         json_parser_input(p, &token);
715         return;
716     }
717
718     if (!imprecise) {
719         while (pow10 > 0 && significand < ULLONG_MAX / 10) {
720             significand *= 10;
721             sig_digits++;
722             pow10--;
723         }
724         while (pow10 < 0 && significand % 10 == 0) {
725             significand /= 10;
726             sig_digits--;
727             pow10++;
728         }
729         if (pow10 == 0
730             && significand <= (negative
731                                ? (unsigned long long int) LLONG_MAX + 1
732                                : LLONG_MAX)) {
733             struct json_token token;
734             token.type = T_INTEGER;
735             token.u.integer = negative ? -significand : significand;
736             json_parser_input(p, &token);
737             return;
738         }
739     }
740
741     if (pow10 + sig_digits <= DBL_MAX_10_EXP) {
742         struct json_token token;
743         token.type = T_REAL;
744         token.u.real = significand * pow(10.0, pow10);
745         if (token.u.real <= DBL_MAX) {
746             if (negative && token.u.real) {
747                 token.u.real = -token.u.real;
748             }
749             json_parser_input(p, &token);
750             return;
751         }
752     }
753     json_error(p, "number outside valid range");
754 }
755
756 static bool
757 json_lex_4hex(struct json_parser *p, const char *cp, int *valuep)
758 {
759     int value, i;
760
761     value = 0;
762     for (i = 0; i < 4; i++) {
763         unsigned char c = *cp++;
764         if (!isxdigit(c)) {
765             json_error(p, "malformed \\u escape");
766             return false;
767         }
768         value = (value << 4) | hexit_value(c);
769     }
770     if (!value) {
771         json_error(p, "null bytes not supported in quoted strings");
772         return false;
773     }
774     *valuep = value;
775     return true;
776 }
777
778 static const char *
779 json_lex_unicode(struct json_parser *p, const char *cp, struct ds *s)
780 {
781     int c0, c1;
782
783     if (!json_lex_4hex(p, cp, &c0)) {
784         return NULL;
785     }
786     cp += 4;
787     if (!uc_is_leading_surrogate(c0)) {
788         ds_put_utf8(s, c0);
789         return cp;
790     }
791
792     if (*cp++ != '\\' || *cp++ != 'u') {
793         json_error(p, "malformed escaped surrogate pair");
794         return NULL;
795     }
796
797     if (!json_lex_4hex(p, cp, &c1)) {
798         return NULL;
799     }
800     cp += 4;
801     if (!uc_is_trailing_surrogate(c1)) {
802         json_error(p, "second half of escaped surrogate pair is not "
803                    "trailing surrogate");
804         return NULL;
805     }
806
807     ds_put_utf8(s, utf16_decode_surrogate_pair(c0, c1));
808     return cp;
809 }
810
811 static void
812 json_lex_string(struct json_parser *p)
813 {
814     struct json_token token;
815     const char *cp;
816     struct ds s;
817
818     cp = ds_cstr(&p->buffer);
819     if (!strchr(cp, '\\')) {
820         token.type = T_STRING;
821         token.u.string = cp;
822         json_parser_input(p, &token);
823         return;
824     }
825
826     ds_init(&s);
827     ds_reserve(&s, strlen(cp));
828     while (*cp != '\0') {
829         if (*cp != '\\') {
830             ds_put_char(&s, *cp++);
831             continue;
832         }
833
834         cp++;
835         switch (*cp++) {
836         case '"': case '\\': case '/':
837             ds_put_char(&s, cp[-1]);
838             break;
839
840         case 'b':
841             ds_put_char(&s, '\b');
842             break;
843
844         case 'f':
845             ds_put_char(&s, '\f');
846             break;
847
848         case 'n':
849             ds_put_char(&s, '\n');
850             break;
851
852         case 'r':
853             ds_put_char(&s, '\r');
854             break;
855
856         case 't':
857             ds_put_char(&s, '\t');
858             break;
859
860         case 'u':
861             cp = json_lex_unicode(p, cp, &s);
862             if (!cp) {
863                 goto exit;
864             }
865             break;
866
867         default:
868             json_error(p, "bad escape \\%c", cp[-1]);
869             goto exit;
870         }
871     }
872
873     token.type = T_STRING;
874     token.u.string = ds_cstr(&s);
875     json_parser_input(p, &token);
876
877 exit:
878     ds_destroy(&s);
879     return;
880 }
881
882 static bool
883 json_lex_input(struct json_parser *p, unsigned char c)
884 {
885     struct json_token token;
886
887     p->byte_number++;
888     if (c == '\n') {
889         p->column_number = 0;
890         p->line_number++;
891     } else {
892         p->column_number++;
893     }
894
895     switch (p->lex_state) {
896     case JSON_LEX_START:
897         switch (c) {
898         case ' ': case '\t': case '\n': case '\r':
899             /* Nothing to do. */
900             return true;
901
902         case 'a': case 'b': case 'c': case 'd': case 'e':
903         case 'f': case 'g': case 'h': case 'i': case 'j':
904         case 'k': case 'l': case 'm': case 'n': case 'o':
905         case 'p': case 'q': case 'r': case 's': case 't':
906         case 'u': case 'v': case 'w': case 'x': case 'y':
907         case 'z':
908             p->lex_state = JSON_LEX_KEYWORD;
909             break;
910
911         case '[': case '{': case ']': case '}': case ':': case ',':
912             token.type = c;
913             json_parser_input(p, &token);
914             return true;
915
916         case '-':
917         case '0': case '1': case '2': case '3': case '4':
918         case '5': case '6': case '7': case '8': case '9':
919             p->lex_state = JSON_LEX_NUMBER;
920             break;
921
922         case '"':
923             p->lex_state = JSON_LEX_STRING;
924             return true;
925
926         default:
927             if (isprint(c)) {
928                 json_error(p, "invalid character '%c'", c);
929             } else {
930                 json_error(p, "invalid character U+%04x", c);
931             }
932             return true;
933         }
934         break;
935
936     case JSON_LEX_KEYWORD:
937         if (!isalpha((unsigned char) c)) {
938             json_lex_keyword(p);
939             return false;
940         }
941         break;
942
943     case JSON_LEX_NUMBER:
944         if (!strchr(".0123456789eE-+", c)) {
945             json_lex_number(p);
946             return false;
947         }
948         break;
949
950     case JSON_LEX_STRING:
951         if (c == '\\') {
952             p->lex_state = JSON_LEX_ESCAPE;
953         } else if (c == '"') {
954             json_lex_string(p);
955             return true;
956         } else if (c < 0x20) {
957             json_error(p, "U+%04X must be escaped in quoted string", c);
958             return true;
959         }
960         break;
961
962     case JSON_LEX_ESCAPE:
963         p->lex_state = JSON_LEX_STRING;
964         break;
965
966     default:
967         abort();
968     }
969     ds_put_char(&p->buffer, c);
970     return true;
971 }
972 \f
973 /* Parsing. */
974
975 /* Parses 'string' as a JSON object or array and returns a newly allocated
976  * 'struct json'.  The caller must free the returned structure with
977  * json_destroy() when it is no longer needed.
978  *
979  * 'string' must be encoded in UTF-8.
980  *
981  * If 'string' is valid JSON, then the returned 'struct json' will be either an
982  * object (JSON_OBJECT) or an array (JSON_ARRAY).
983  *
984  * If 'string' is not valid JSON, then the returned 'struct json' will be a
985  * string (JSON_STRING) that describes the particular error encountered during
986  * parsing.  (This is an acceptable means of error reporting because at its top
987  * level JSON must be either an object or an array; a bare string is not
988  * valid.) */
989 struct json *
990 json_from_string(const char *string)
991 {
992     struct json_parser *p = json_parser_create(JSPF_TRAILER);
993     json_parser_feed(p, string, strlen(string));
994     return json_parser_finish(p);
995 }
996
997 /* Reads the file named 'file_name', parses its contents as a JSON object or
998  * array, and returns a newly allocated 'struct json'.  The caller must free
999  * the returned structure with json_destroy() when it is no longer needed.
1000  *
1001  * The file must be encoded in UTF-8.
1002  *
1003  * See json_from_string() for return value semantics.
1004  */
1005 struct json *
1006 json_from_file(const char *file_name)
1007 {
1008     struct json_parser *p;
1009     struct json *json;
1010     FILE *stream;
1011
1012     /* Open file. */
1013     stream = fopen(file_name, "r");
1014     if (!stream) {
1015         return json_string_create_nocopy(
1016             xasprintf("error opening \"%s\": %s", file_name, strerror(errno)));
1017     }
1018
1019     /* Read and parse file. */
1020     p = json_parser_create(JSPF_TRAILER);
1021     for (;;) {
1022         char buffer[BUFSIZ];
1023         size_t n;
1024
1025         n = fread(buffer, 1, sizeof buffer, stream);
1026         if (!n || json_parser_feed(p, buffer, n) != n) {
1027             break;
1028         }
1029     }
1030     json = json_parser_finish(p);
1031
1032     /* Close file and check for I/O errors. */
1033     if (ferror(stream)) {
1034         json_destroy(json);
1035         json = json_string_create_nocopy(
1036             xasprintf("error reading \"%s\": %s", file_name, strerror(errno)));
1037     }
1038     fclose(stream);
1039
1040     return json;
1041 }
1042
1043 struct json_parser *
1044 json_parser_create(int flags)
1045 {
1046     struct json_parser *p = xzalloc(sizeof *p);
1047     p->flags = flags;
1048     return p;
1049 }
1050
1051 size_t
1052 json_parser_feed(struct json_parser *p, const char *input, size_t n)
1053 {
1054     size_t i;
1055     for (i = 0; !p->done && i < n; ) {
1056         if (json_lex_input(p, input[i])) {
1057             i++;
1058         }
1059     }
1060     return i;
1061 }
1062
1063 bool
1064 json_parser_is_done(const struct json_parser *p)
1065 {
1066     return p->done;
1067 }
1068
1069 struct json *
1070 json_parser_finish(struct json_parser *p)
1071 {
1072     struct json *json;
1073
1074     switch (p->lex_state) {
1075     case JSON_LEX_START:
1076         break;
1077
1078     case JSON_LEX_STRING:
1079     case JSON_LEX_ESCAPE:
1080         json_error(p, "unexpected end of input in quoted string");
1081         break;
1082
1083     case JSON_LEX_NUMBER:
1084     case JSON_LEX_KEYWORD:
1085         json_lex_input(p, ' ');
1086         break;
1087     }
1088
1089     if (p->parse_state == JSON_PARSE_START) {
1090         json_error(p, "empty input stream");
1091     } else if (p->parse_state != JSON_PARSE_END) {
1092         json_error(p, "unexpected end of input");
1093     }
1094
1095     if (!p->error) {
1096         assert(p->height == 1);
1097         assert(p->stack[0].json != NULL);
1098         json = p->stack[--p->height].json;
1099     } else {
1100         json = json_string_create_nocopy(p->error);
1101         p->error = NULL;
1102     }
1103
1104     json_parser_abort(p);
1105
1106     return json;
1107 }
1108
1109 void
1110 json_parser_abort(struct json_parser *p)
1111 {
1112     if (p) {
1113         ds_destroy(&p->buffer);
1114         if (p->height) {
1115             json_destroy(p->stack[0].json);
1116         }
1117         free(p->stack);
1118         free(p->member_name);
1119         free(p->error);
1120         free(p);
1121     }
1122 }
1123
1124 static struct json_parser_node *
1125 json_parser_top(struct json_parser *p)
1126 {
1127     return &p->stack[p->height - 1];
1128 }
1129
1130 static void
1131 json_parser_put_value(struct json_parser *p, struct json *value)
1132 {
1133     struct json_parser_node *node = json_parser_top(p);
1134     if (node->json->type == JSON_OBJECT) {
1135         json_object_put(node->json, p->member_name, value);
1136         free(p->member_name);
1137         p->member_name = NULL;
1138     } else if (node->json->type == JSON_ARRAY) {
1139         json_array_add(node->json, value);
1140     } else {
1141         NOT_REACHED();
1142     }
1143 }
1144
1145 static struct json_parser_node *
1146 json_parser_push(struct json_parser *p,
1147                  struct json *new_json, enum json_parse_state new_state)
1148 {
1149     if (p->height < JSON_MAX_HEIGHT) {
1150         struct json_parser_node *node;
1151
1152         if (p->height >= p->allocated_height) {
1153             p->stack = x2nrealloc(p->stack, &p->allocated_height,
1154                                   sizeof *p->stack);
1155         }
1156
1157         if (p->height > 0) {
1158             json_parser_put_value(p, new_json);
1159         }
1160
1161         node = &p->stack[p->height++];
1162         node->json = new_json;
1163         p->parse_state = new_state;
1164         return node;
1165     } else {
1166         json_error(p, "input exceeds maximum nesting depth %d",
1167                    JSON_MAX_HEIGHT);
1168         return NULL;
1169     }
1170 }
1171
1172 static void
1173 json_parser_push_object(struct json_parser *p)
1174 {
1175     json_parser_push(p, json_object_create(), JSON_PARSE_OBJECT_INIT);
1176 }
1177
1178 static void
1179 json_parser_push_array(struct json_parser *p)
1180 {
1181     json_parser_push(p, json_array_create_empty(), JSON_PARSE_ARRAY_INIT);
1182 }
1183
1184 static void
1185 json_parse_value(struct json_parser *p, struct json_token *token,
1186                  enum json_parse_state next_state)
1187 {
1188     struct json *value;
1189
1190     switch (token->type) {
1191     case T_FALSE:
1192         value = json_boolean_create(false);
1193         break;
1194
1195     case T_NULL:
1196         value = json_null_create();
1197         break;
1198
1199     case T_TRUE:
1200         value = json_boolean_create(true);
1201         break;
1202
1203     case '{':
1204         json_parser_push_object(p);
1205         return;
1206
1207     case '[':
1208         json_parser_push_array(p);
1209         return;
1210
1211     case T_INTEGER:
1212         value = json_integer_create(token->u.integer);
1213         break;
1214
1215     case T_REAL:
1216         value = json_real_create(token->u.real);
1217         break;
1218
1219     case T_STRING:
1220         value = json_string_create(token->u.string);
1221         break;
1222
1223     case T_EOF:
1224     case '}':
1225     case ']':
1226     case ':':
1227     case ',':
1228     default:
1229         json_error(p, "syntax error expecting value");
1230         return;
1231     }
1232
1233     json_parser_put_value(p, value);
1234     p->parse_state = next_state;
1235 }
1236
1237 static void
1238 json_parser_pop(struct json_parser *p)
1239 {
1240     struct json_parser_node *node;
1241
1242     /* Conserve memory. */
1243     node = json_parser_top(p);
1244     if (node->json->type == JSON_ARRAY) {
1245         json_array_trim(node->json);
1246     }
1247
1248     /* Pop off the top-of-stack. */
1249     if (p->height == 1) {
1250         p->parse_state = JSON_PARSE_END;
1251         if (!(p->flags & JSPF_TRAILER)) {
1252             p->done = true;
1253         }
1254     } else {
1255         p->height--;
1256         node = json_parser_top(p);
1257         if (node->json->type == JSON_ARRAY) {
1258             p->parse_state = JSON_PARSE_ARRAY_NEXT;
1259         } else if (node->json->type == JSON_OBJECT) {
1260             p->parse_state = JSON_PARSE_OBJECT_NEXT;
1261         } else {
1262             NOT_REACHED();
1263         }
1264     }
1265 }
1266
1267 static void
1268 json_parser_input(struct json_parser *p, struct json_token *token)
1269 {
1270     switch (p->parse_state) {
1271     case JSON_PARSE_START:
1272         if (token->type == '{') {
1273             json_parser_push_object(p);
1274         } else if (token->type == '[') {
1275             json_parser_push_array(p);
1276         } else {
1277             json_error(p, "syntax error at beginning of input");
1278         }
1279         break;
1280
1281     case JSON_PARSE_END:
1282         json_error(p, "trailing garbage at end of input");
1283         break;
1284
1285     case JSON_PARSE_OBJECT_INIT:
1286         if (token->type == '}') {
1287             json_parser_pop(p);
1288             break;
1289         }
1290         /* Fall through. */
1291     case JSON_PARSE_OBJECT_NAME:
1292         if (token->type == T_STRING) {
1293             p->member_name = xstrdup(token->u.string);
1294             p->parse_state = JSON_PARSE_OBJECT_COLON;
1295         } else {
1296             json_error(p, "syntax error parsing object expecting string");
1297         }
1298         break;
1299
1300     case JSON_PARSE_OBJECT_COLON:
1301         if (token->type == ':') {
1302             p->parse_state = JSON_PARSE_OBJECT_VALUE;
1303         } else {
1304             json_error(p, "syntax error parsing object expecting ':'");
1305         }
1306         break;
1307
1308     case JSON_PARSE_OBJECT_VALUE:
1309         json_parse_value(p, token, JSON_PARSE_OBJECT_NEXT);
1310         break;
1311
1312     case JSON_PARSE_OBJECT_NEXT:
1313         if (token->type == ',') {
1314             p->parse_state = JSON_PARSE_OBJECT_NAME;
1315         } else if (token->type == '}') {
1316             json_parser_pop(p);
1317         } else {
1318             json_error(p, "syntax error expecting '}' or ','");
1319         }
1320         break;
1321
1322     case JSON_PARSE_ARRAY_INIT:
1323         if (token->type == ']') {
1324             json_parser_pop(p);
1325             break;
1326         }
1327         /* Fall through. */
1328     case JSON_PARSE_ARRAY_VALUE:
1329         json_parse_value(p, token, JSON_PARSE_ARRAY_NEXT);
1330         break;
1331
1332     case JSON_PARSE_ARRAY_NEXT:
1333         if (token->type == ',') {
1334             p->parse_state = JSON_PARSE_ARRAY_VALUE;
1335         } else if (token->type == ']') {
1336             json_parser_pop(p);
1337         } else {
1338             json_error(p, "syntax error expecting ']' or ','");
1339         }
1340         break;
1341
1342     default:
1343         abort();
1344     }
1345
1346     p->lex_state = JSON_LEX_START;
1347     ds_clear(&p->buffer);
1348 }
1349
1350 static struct json *
1351 json_create(enum json_type type)
1352 {
1353     struct json *json = xmalloc(sizeof *json);
1354     json->type = type;
1355     return json;
1356 }
1357
1358 static void
1359 json_error(struct json_parser *p, const char *format, ...)
1360 {
1361     if (!p->error) {
1362         struct ds msg;
1363         va_list args;
1364
1365         ds_init(&msg);
1366         ds_put_format(&msg, "line %d, column %d, byte %d: ",
1367                       p->line_number, p->column_number, p->byte_number);
1368         va_start(args, format);
1369         ds_put_format_valist(&msg, format, args);
1370         va_end(args);
1371
1372         p->error = ds_steal_cstr(&msg);
1373
1374         p->done = true;
1375     }
1376 }
1377 \f
1378 #define SPACES_PER_LEVEL 2
1379
1380 struct json_serializer {
1381     struct ds ds;
1382     int depth;
1383     int flags;
1384 };
1385
1386 static void json_to_ds(const struct json *, struct json_serializer *);
1387 static void json_object_to_ds(const struct shash *object,
1388                               struct json_serializer *);
1389 static void json_array_to_ds(const struct json_array *,
1390                              struct json_serializer *);
1391 static void json_string_to_ds(const char *string, struct ds *);
1392
1393 /* Converts 'json' to a string in JSON format, encoded in UTF-8, and returns
1394  * that string.  The caller is responsible for freeing the returned string,
1395  * with free(), when it is no longer needed.
1396  *
1397  * If 'flags' contains JSSF_PRETTY, the output is pretty-printed with each
1398  * nesting level introducing an additional indentation.  Otherwise, the
1399  * returned string does not contain any new-line characters.
1400  *
1401  * If 'flags' contains JSSF_SORT, members of objects in the output are sorted
1402  * in bytewise lexicographic order for reproducibility.  Otherwise, members of
1403  * objects are output in an indeterminate order.
1404  *
1405  * The returned string is valid JSON only if 'json' represents an array or an
1406  * object, since a bare literal does not satisfy the JSON grammar. */
1407 char *
1408 json_to_string(const struct json *json, int flags)
1409 {
1410     struct json_serializer s;
1411     ds_init(&s.ds);
1412     s.depth = 0;
1413     s.flags = flags;
1414     json_to_ds(json, &s);
1415     return ds_steal_cstr(&s.ds);
1416 }
1417
1418 static void
1419 json_to_ds(const struct json *json, struct json_serializer *s)
1420 {
1421     struct ds *ds = &s->ds;
1422
1423     switch (json->type) {
1424     case JSON_NULL:
1425         ds_put_cstr(ds, "null");
1426         break;
1427
1428     case JSON_FALSE:
1429         ds_put_cstr(ds, "false");
1430         break;
1431
1432     case JSON_TRUE:
1433         ds_put_cstr(ds, "true");
1434         break;
1435
1436     case JSON_OBJECT:
1437         json_object_to_ds(json->u.object, s);
1438         break;
1439
1440     case JSON_ARRAY:
1441         json_array_to_ds(&json->u.array, s);
1442         break;
1443
1444     case JSON_INTEGER:
1445         ds_put_format(ds, "%lld", json->u.integer);
1446         break;
1447
1448     case JSON_REAL:
1449         ds_put_format(ds, "%.*g", DBL_DIG, json->u.real);
1450         break;
1451
1452     case JSON_STRING:
1453         json_string_to_ds(json->u.string, ds);
1454         break;
1455
1456     case JSON_N_TYPES:
1457     default:
1458         NOT_REACHED();
1459     }
1460 }
1461
1462 static void
1463 indent_line(struct json_serializer *s)
1464 {
1465     if (s->flags & JSSF_PRETTY) {
1466         ds_put_char(&s->ds, '\n');
1467         ds_put_char_multiple(&s->ds, ' ', SPACES_PER_LEVEL * s->depth);
1468     }
1469 }
1470
1471 static void
1472 json_object_member_to_ds(size_t i, const struct shash_node *node,
1473                          struct json_serializer *s)
1474 {
1475     struct ds *ds = &s->ds;
1476
1477     if (i) {
1478         ds_put_char(ds, ',');
1479         indent_line(s);
1480     }
1481
1482     json_string_to_ds(node->name, ds);
1483     ds_put_char(ds, ':');
1484     if (s->flags & JSSF_PRETTY) {
1485         ds_put_char(ds, ' ');
1486     }
1487     json_to_ds(node->data, s);
1488 }
1489
1490 static void
1491 json_object_to_ds(const struct shash *object, struct json_serializer *s)
1492 {
1493     struct ds *ds = &s->ds;
1494
1495     ds_put_char(ds, '{');
1496
1497     s->depth++;
1498     indent_line(s);
1499
1500     if (s->flags & JSSF_SORT) {
1501         const struct shash_node **nodes;
1502         size_t n, i;
1503
1504         nodes = shash_sort(object);
1505         n = shash_count(object);
1506         for (i = 0; i < n; i++) {
1507             json_object_member_to_ds(i, nodes[i], s);
1508         }
1509         free(nodes);
1510     } else {
1511         struct shash_node *node;
1512         size_t i;
1513
1514         i = 0;
1515         SHASH_FOR_EACH (node, object) {
1516             json_object_member_to_ds(i++, node, s);
1517         }
1518     }
1519
1520     ds_put_char(ds, '}');
1521     s->depth--;
1522 }
1523
1524 static void
1525 json_array_to_ds(const struct json_array *array, struct json_serializer *s)
1526 {
1527     struct ds *ds = &s->ds;
1528     size_t i;
1529
1530     ds_put_char(ds, '[');
1531     s->depth++;
1532
1533     if (array->n > 0) {
1534         indent_line(s);
1535
1536         for (i = 0; i < array->n; i++) {
1537             if (i) {
1538                 ds_put_char(ds, ',');
1539                 indent_line(s);
1540             }
1541             json_to_ds(array->elems[i], s);
1542         }
1543     }
1544
1545     s->depth--;
1546     ds_put_char(ds, ']');
1547 }
1548
1549 static void
1550 json_string_to_ds(const char *string, struct ds *ds)
1551 {
1552     uint8_t c;
1553
1554     ds_put_char(ds, '"');
1555     while ((c = *string++) != '\0') {
1556         switch (c) {
1557         case '"':
1558             ds_put_cstr(ds, "\\\"");
1559             break;
1560
1561         case '\\':
1562             ds_put_cstr(ds, "\\\\");
1563             break;
1564
1565         case '\b':
1566             ds_put_cstr(ds, "\\b");
1567             break;
1568
1569         case '\f':
1570             ds_put_cstr(ds, "\\f");
1571             break;
1572
1573         case '\n':
1574             ds_put_cstr(ds, "\\n");
1575             break;
1576
1577         case '\r':
1578             ds_put_cstr(ds, "\\r");
1579             break;
1580
1581         case '\t':
1582             ds_put_cstr(ds, "\\t");
1583             break;
1584
1585         default:
1586             if (c >= 32) {
1587                 ds_put_char(ds, c);
1588             } else {
1589                 ds_put_format(ds, "\\u%04x", c);
1590             }
1591             break;
1592         }
1593     }
1594     ds_put_char(ds, '"');
1595 }