Prepare Open vSwitch 1.1.2 release.
[sliver-openvswitch.git] / lib / json.c
1 /*
2  * Copyright (c) 2009, 2010 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     json_destroy(shash_replace(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     struct json_token token;
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     if (*cp == '0') {
624         cp++;
625         if (isdigit(*cp)) {
626             json_error(p, "leading zeros not allowed");
627             return;
628         }
629     } else if (isdigit(*cp)) {
630         do {
631             if (significand <= ULLONG_MAX / 10) {
632                 significand = significand * 10 + (*cp - '0');
633             } else {
634                 pow10++;
635                 if (*cp != '0') {
636                     imprecise = true;
637                 }
638             }
639             cp++;
640         } while (isdigit(*cp));
641     } else {
642         json_error(p, "'-' must be followed by digit");
643         return;
644     }
645
646     /* Optional fraction. */
647     if (*cp == '.') {
648         cp++;
649         if (!isdigit(*cp)) {
650             json_error(p, "decimal point must be followed by digit");
651             return;
652         }
653         do {
654             if (significand <= ULLONG_MAX / 10) {
655                 significand = significand * 10 + (*cp - '0');
656                 pow10--;
657             } else if (*cp != '0') {
658                 imprecise = true;
659             }
660             cp++;
661         } while (isdigit(*cp));
662     }
663
664     /* Optional exponent. */
665     if (*cp == 'e' || *cp == 'E') {
666         bool negative_exponent = false;
667         int exponent;
668
669         cp++;
670         if (*cp == '+') {
671             cp++;
672         } else if (*cp == '-') {
673             negative_exponent = true;
674             cp++;
675         }
676
677         if (!isdigit(*cp)) {
678             json_error(p, "exponent must contain at least one digit");
679             return;
680         }
681
682         exponent = 0;
683         do {
684             if (exponent >= INT_MAX / 10) {
685                 json_error(p, "exponent outside valid range");
686                 return;
687             }
688             exponent = exponent * 10 + (*cp - '0');
689             cp++;
690         } while (isdigit(*cp));
691
692         if (negative_exponent) {
693             pow10 -= exponent;
694         } else {
695             pow10 += exponent;
696         }
697     }
698
699     if (*cp != '\0') {
700         json_error(p, "syntax error in number");
701         return;
702     }
703
704     /* Figure out number.
705      *
706      * We suppress negative zeros as a matter of policy. */
707     if (!significand) {
708         token.type = T_INTEGER;
709         token.u.integer = 0;
710         json_parser_input(p, &token);
711         return;
712     }
713
714     if (!imprecise) {
715         while (pow10 > 0 && significand < ULLONG_MAX / 10) {
716             significand *= 10;
717             pow10--;
718         }
719         while (pow10 < 0 && significand % 10 == 0) {
720             significand /= 10;
721             pow10++;
722         }
723         if (pow10 == 0
724             && significand <= (negative
725                                ? (unsigned long long int) LLONG_MAX + 1
726                                : LLONG_MAX)) {
727             token.type = T_INTEGER;
728             token.u.integer = negative ? -significand : significand;
729             json_parser_input(p, &token);
730             return;
731         }
732     }
733
734     token.type = T_REAL;
735     if (!str_to_double(ds_cstr(&p->buffer), &token.u.real)) {
736         json_error(p, "number outside valid range");
737         return;
738     }
739     /* Suppress negative zero. */
740     if (token.u.real == 0) {
741         token.u.real = 0;
742     }
743     json_parser_input(p, &token);
744 }
745
746 static const char *
747 json_lex_4hex(const char *cp, const char *end, int *valuep)
748 {
749     unsigned int value;
750
751     if (cp + 4 > end) {
752         return "quoted string ends within \\u escape";
753     }
754
755     value = hexits_value(cp, 4, NULL);
756     if (value == UINT_MAX) {
757         return "malformed \\u escape";
758     }
759     if (!value) {
760         return "null bytes not supported in quoted strings";
761     }
762     *valuep = value;
763     return NULL;
764 }
765
766 static const char *
767 json_lex_unicode(const char *cp, const char *end, struct ds *out)
768 {
769     const char *error;
770     int c0, c1;
771
772     error = json_lex_4hex(cp, end, &c0);
773     if (error) {
774         ds_clear(out);
775         ds_put_cstr(out, error);
776         return NULL;
777     }
778     cp += 4;
779     if (!uc_is_leading_surrogate(c0)) {
780         ds_put_utf8(out, c0);
781         return cp;
782     }
783
784     if (cp + 2 > end || *cp++ != '\\' || *cp++ != 'u') {
785         ds_clear(out);
786         ds_put_cstr(out, "malformed escaped surrogate pair");
787         return NULL;
788     }
789
790     error = json_lex_4hex(cp, end, &c1);
791     if (error) {
792         ds_clear(out);
793         ds_put_cstr(out, error);
794         return NULL;
795     }
796     cp += 4;
797     if (!uc_is_trailing_surrogate(c1)) {
798         ds_clear(out);
799         ds_put_cstr(out, "second half of escaped surrogate pair is not "
800                     "trailing surrogate");
801         return NULL;
802     }
803
804     ds_put_utf8(out, utf16_decode_surrogate_pair(c0, c1));
805     return cp;
806 }
807
808 bool
809 json_string_unescape(const char *in, size_t in_len, char **outp)
810 {
811     const char *end = in + in_len;
812     bool ok = false;
813     struct ds out;
814
815     ds_init(&out);
816     ds_reserve(&out, in_len);
817     if (in_len > 0 && in[in_len - 1] == '\\') {
818         ds_put_cstr(&out, "quoted string may not end with backslash");
819         goto exit;
820     }
821     while (in < end) {
822         if (*in == '"') {
823             ds_clear(&out);
824             ds_put_cstr(&out, "quoted string may not include unescaped \"");
825             goto exit;
826         }
827         if (*in != '\\') {
828             ds_put_char(&out, *in++);
829             continue;
830         }
831
832         in++;
833         switch (*in++) {
834         case '"': case '\\': case '/':
835             ds_put_char(&out, in[-1]);
836             break;
837
838         case 'b':
839             ds_put_char(&out, '\b');
840             break;
841
842         case 'f':
843             ds_put_char(&out, '\f');
844             break;
845
846         case 'n':
847             ds_put_char(&out, '\n');
848             break;
849
850         case 'r':
851             ds_put_char(&out, '\r');
852             break;
853
854         case 't':
855             ds_put_char(&out, '\t');
856             break;
857
858         case 'u':
859             in = json_lex_unicode(in, end, &out);
860             if (!in) {
861                 goto exit;
862             }
863             break;
864
865         default:
866             ds_clear(&out);
867             ds_put_format(&out, "bad escape \\%c", in[-1]);
868             goto exit;
869         }
870     }
871     ok = true;
872
873 exit:
874     *outp = ds_cstr(&out);
875     return ok;
876 }
877
878 static void
879 json_parser_input_string(struct json_parser *p, const char *s)
880 {
881     struct json_token token;
882
883     token.type = T_STRING;
884     token.u.string = s;
885     json_parser_input(p, &token);
886 }
887
888 static void
889 json_lex_string(struct json_parser *p)
890 {
891     const char *raw = ds_cstr(&p->buffer);
892     if (!strchr(raw, '\\')) {
893         json_parser_input_string(p, raw);
894     } else {
895         char *cooked;
896
897         if (json_string_unescape(raw, strlen(raw), &cooked)) {
898             json_parser_input_string(p, cooked);
899         } else {
900             json_error(p, "%s", cooked);
901         }
902
903         free(cooked);
904     }
905 }
906
907 static bool
908 json_lex_input(struct json_parser *p, unsigned char c)
909 {
910     struct json_token token;
911
912     p->byte_number++;
913     if (c == '\n') {
914         p->column_number = 0;
915         p->line_number++;
916     } else {
917         p->column_number++;
918     }
919
920     switch (p->lex_state) {
921     case JSON_LEX_START:
922         switch (c) {
923         case ' ': case '\t': case '\n': case '\r':
924             /* Nothing to do. */
925             return true;
926
927         case 'a': case 'b': case 'c': case 'd': case 'e':
928         case 'f': case 'g': case 'h': case 'i': case 'j':
929         case 'k': case 'l': case 'm': case 'n': case 'o':
930         case 'p': case 'q': case 'r': case 's': case 't':
931         case 'u': case 'v': case 'w': case 'x': case 'y':
932         case 'z':
933             p->lex_state = JSON_LEX_KEYWORD;
934             break;
935
936         case '[': case '{': case ']': case '}': case ':': case ',':
937             token.type = c;
938             json_parser_input(p, &token);
939             return true;
940
941         case '-':
942         case '0': case '1': case '2': case '3': case '4':
943         case '5': case '6': case '7': case '8': case '9':
944             p->lex_state = JSON_LEX_NUMBER;
945             break;
946
947         case '"':
948             p->lex_state = JSON_LEX_STRING;
949             return true;
950
951         default:
952             if (isprint(c)) {
953                 json_error(p, "invalid character '%c'", c);
954             } else {
955                 json_error(p, "invalid character U+%04x", c);
956             }
957             return true;
958         }
959         break;
960
961     case JSON_LEX_KEYWORD:
962         if (!isalpha((unsigned char) c)) {
963             json_lex_keyword(p);
964             return false;
965         }
966         break;
967
968     case JSON_LEX_NUMBER:
969         if (!strchr(".0123456789eE-+", c)) {
970             json_lex_number(p);
971             return false;
972         }
973         break;
974
975     case JSON_LEX_STRING:
976         if (c == '\\') {
977             p->lex_state = JSON_LEX_ESCAPE;
978         } else if (c == '"') {
979             json_lex_string(p);
980             return true;
981         } else if (c < 0x20) {
982             json_error(p, "U+%04X must be escaped in quoted string", c);
983             return true;
984         }
985         break;
986
987     case JSON_LEX_ESCAPE:
988         p->lex_state = JSON_LEX_STRING;
989         break;
990
991     default:
992         abort();
993     }
994     ds_put_char(&p->buffer, c);
995     return true;
996 }
997 \f
998 /* Parsing. */
999
1000 /* Parses 'string' as a JSON object or array and returns a newly allocated
1001  * 'struct json'.  The caller must free the returned structure with
1002  * json_destroy() when it is no longer needed.
1003  *
1004  * 'string' must be encoded in UTF-8.
1005  *
1006  * If 'string' is valid JSON, then the returned 'struct json' will be either an
1007  * object (JSON_OBJECT) or an array (JSON_ARRAY).
1008  *
1009  * If 'string' is not valid JSON, then the returned 'struct json' will be a
1010  * string (JSON_STRING) that describes the particular error encountered during
1011  * parsing.  (This is an acceptable means of error reporting because at its top
1012  * level JSON must be either an object or an array; a bare string is not
1013  * valid.) */
1014 struct json *
1015 json_from_string(const char *string)
1016 {
1017     struct json_parser *p = json_parser_create(JSPF_TRAILER);
1018     json_parser_feed(p, string, strlen(string));
1019     return json_parser_finish(p);
1020 }
1021
1022 /* Reads the file named 'file_name', parses its contents as a JSON object or
1023  * array, and returns a newly allocated 'struct json'.  The caller must free
1024  * the returned structure with json_destroy() when it is no longer needed.
1025  *
1026  * The file must be encoded in UTF-8.
1027  *
1028  * See json_from_string() for return value semantics.
1029  */
1030 struct json *
1031 json_from_file(const char *file_name)
1032 {
1033     struct json *json;
1034     FILE *stream;
1035
1036     stream = fopen(file_name, "r");
1037     if (!stream) {
1038         return json_string_create_nocopy(
1039             xasprintf("error opening \"%s\": %s", file_name, strerror(errno)));
1040     }
1041     json = json_from_stream(stream);
1042     fclose(stream);
1043
1044     return json;
1045 }
1046
1047 /* Parses the contents of 'stream' as a JSON object or array, and returns a
1048  * newly allocated 'struct json'.  The caller must free the returned structure
1049  * with json_destroy() when it is no longer needed.
1050  *
1051  * The file must be encoded in UTF-8.
1052  *
1053  * See json_from_string() for return value semantics.
1054  */
1055 struct json *
1056 json_from_stream(FILE *stream)
1057 {
1058     struct json_parser *p;
1059     struct json *json;
1060
1061     p = json_parser_create(JSPF_TRAILER);
1062     for (;;) {
1063         char buffer[BUFSIZ];
1064         size_t n;
1065
1066         n = fread(buffer, 1, sizeof buffer, stream);
1067         if (!n || json_parser_feed(p, buffer, n) != n) {
1068             break;
1069         }
1070     }
1071     json = json_parser_finish(p);
1072
1073     if (ferror(stream)) {
1074         json_destroy(json);
1075         json = json_string_create_nocopy(
1076             xasprintf("error reading JSON stream: %s", strerror(errno)));
1077     }
1078
1079     return json;
1080 }
1081
1082 struct json_parser *
1083 json_parser_create(int flags)
1084 {
1085     struct json_parser *p = xzalloc(sizeof *p);
1086     p->flags = flags;
1087     return p;
1088 }
1089
1090 size_t
1091 json_parser_feed(struct json_parser *p, const char *input, size_t n)
1092 {
1093     size_t i;
1094     for (i = 0; !p->done && i < n; ) {
1095         if (json_lex_input(p, input[i])) {
1096             i++;
1097         }
1098     }
1099     return i;
1100 }
1101
1102 bool
1103 json_parser_is_done(const struct json_parser *p)
1104 {
1105     return p->done;
1106 }
1107
1108 struct json *
1109 json_parser_finish(struct json_parser *p)
1110 {
1111     struct json *json;
1112
1113     switch (p->lex_state) {
1114     case JSON_LEX_START:
1115         break;
1116
1117     case JSON_LEX_STRING:
1118     case JSON_LEX_ESCAPE:
1119         json_error(p, "unexpected end of input in quoted string");
1120         break;
1121
1122     case JSON_LEX_NUMBER:
1123     case JSON_LEX_KEYWORD:
1124         json_lex_input(p, ' ');
1125         break;
1126     }
1127
1128     if (p->parse_state == JSON_PARSE_START) {
1129         json_error(p, "empty input stream");
1130     } else if (p->parse_state != JSON_PARSE_END) {
1131         json_error(p, "unexpected end of input");
1132     }
1133
1134     if (!p->error) {
1135         assert(p->height == 1);
1136         assert(p->stack[0].json != NULL);
1137         json = p->stack[--p->height].json;
1138     } else {
1139         json = json_string_create_nocopy(p->error);
1140         p->error = NULL;
1141     }
1142
1143     json_parser_abort(p);
1144
1145     return json;
1146 }
1147
1148 void
1149 json_parser_abort(struct json_parser *p)
1150 {
1151     if (p) {
1152         ds_destroy(&p->buffer);
1153         if (p->height) {
1154             json_destroy(p->stack[0].json);
1155         }
1156         free(p->stack);
1157         free(p->member_name);
1158         free(p->error);
1159         free(p);
1160     }
1161 }
1162
1163 static struct json_parser_node *
1164 json_parser_top(struct json_parser *p)
1165 {
1166     return &p->stack[p->height - 1];
1167 }
1168
1169 static void
1170 json_parser_put_value(struct json_parser *p, struct json *value)
1171 {
1172     struct json_parser_node *node = json_parser_top(p);
1173     if (node->json->type == JSON_OBJECT) {
1174         json_object_put(node->json, p->member_name, value);
1175         free(p->member_name);
1176         p->member_name = NULL;
1177     } else if (node->json->type == JSON_ARRAY) {
1178         json_array_add(node->json, value);
1179     } else {
1180         NOT_REACHED();
1181     }
1182 }
1183
1184 static void
1185 json_parser_push(struct json_parser *p,
1186                  struct json *new_json, enum json_parse_state new_state)
1187 {
1188     if (p->height < JSON_MAX_HEIGHT) {
1189         struct json_parser_node *node;
1190
1191         if (p->height >= p->allocated_height) {
1192             p->stack = x2nrealloc(p->stack, &p->allocated_height,
1193                                   sizeof *p->stack);
1194         }
1195
1196         if (p->height > 0) {
1197             json_parser_put_value(p, new_json);
1198         }
1199
1200         node = &p->stack[p->height++];
1201         node->json = new_json;
1202         p->parse_state = new_state;
1203     } else {
1204         json_destroy(new_json);
1205         json_error(p, "input exceeds maximum nesting depth %d",
1206                    JSON_MAX_HEIGHT);
1207     }
1208 }
1209
1210 static void
1211 json_parser_push_object(struct json_parser *p)
1212 {
1213     json_parser_push(p, json_object_create(), JSON_PARSE_OBJECT_INIT);
1214 }
1215
1216 static void
1217 json_parser_push_array(struct json_parser *p)
1218 {
1219     json_parser_push(p, json_array_create_empty(), JSON_PARSE_ARRAY_INIT);
1220 }
1221
1222 static void
1223 json_parse_value(struct json_parser *p, struct json_token *token,
1224                  enum json_parse_state next_state)
1225 {
1226     struct json *value;
1227
1228     switch (token->type) {
1229     case T_FALSE:
1230         value = json_boolean_create(false);
1231         break;
1232
1233     case T_NULL:
1234         value = json_null_create();
1235         break;
1236
1237     case T_TRUE:
1238         value = json_boolean_create(true);
1239         break;
1240
1241     case '{':
1242         json_parser_push_object(p);
1243         return;
1244
1245     case '[':
1246         json_parser_push_array(p);
1247         return;
1248
1249     case T_INTEGER:
1250         value = json_integer_create(token->u.integer);
1251         break;
1252
1253     case T_REAL:
1254         value = json_real_create(token->u.real);
1255         break;
1256
1257     case T_STRING:
1258         value = json_string_create(token->u.string);
1259         break;
1260
1261     case T_EOF:
1262     case '}':
1263     case ']':
1264     case ':':
1265     case ',':
1266     default:
1267         json_error(p, "syntax error expecting value");
1268         return;
1269     }
1270
1271     json_parser_put_value(p, value);
1272     p->parse_state = next_state;
1273 }
1274
1275 static void
1276 json_parser_pop(struct json_parser *p)
1277 {
1278     struct json_parser_node *node;
1279
1280     /* Conserve memory. */
1281     node = json_parser_top(p);
1282     if (node->json->type == JSON_ARRAY) {
1283         json_array_trim(node->json);
1284     }
1285
1286     /* Pop off the top-of-stack. */
1287     if (p->height == 1) {
1288         p->parse_state = JSON_PARSE_END;
1289         if (!(p->flags & JSPF_TRAILER)) {
1290             p->done = true;
1291         }
1292     } else {
1293         p->height--;
1294         node = json_parser_top(p);
1295         if (node->json->type == JSON_ARRAY) {
1296             p->parse_state = JSON_PARSE_ARRAY_NEXT;
1297         } else if (node->json->type == JSON_OBJECT) {
1298             p->parse_state = JSON_PARSE_OBJECT_NEXT;
1299         } else {
1300             NOT_REACHED();
1301         }
1302     }
1303 }
1304
1305 static void
1306 json_parser_input(struct json_parser *p, struct json_token *token)
1307 {
1308     switch (p->parse_state) {
1309     case JSON_PARSE_START:
1310         if (token->type == '{') {
1311             json_parser_push_object(p);
1312         } else if (token->type == '[') {
1313             json_parser_push_array(p);
1314         } else {
1315             json_error(p, "syntax error at beginning of input");
1316         }
1317         break;
1318
1319     case JSON_PARSE_END:
1320         json_error(p, "trailing garbage at end of input");
1321         break;
1322
1323     case JSON_PARSE_OBJECT_INIT:
1324         if (token->type == '}') {
1325             json_parser_pop(p);
1326             break;
1327         }
1328         /* Fall through. */
1329     case JSON_PARSE_OBJECT_NAME:
1330         if (token->type == T_STRING) {
1331             p->member_name = xstrdup(token->u.string);
1332             p->parse_state = JSON_PARSE_OBJECT_COLON;
1333         } else {
1334             json_error(p, "syntax error parsing object expecting string");
1335         }
1336         break;
1337
1338     case JSON_PARSE_OBJECT_COLON:
1339         if (token->type == ':') {
1340             p->parse_state = JSON_PARSE_OBJECT_VALUE;
1341         } else {
1342             json_error(p, "syntax error parsing object expecting ':'");
1343         }
1344         break;
1345
1346     case JSON_PARSE_OBJECT_VALUE:
1347         json_parse_value(p, token, JSON_PARSE_OBJECT_NEXT);
1348         break;
1349
1350     case JSON_PARSE_OBJECT_NEXT:
1351         if (token->type == ',') {
1352             p->parse_state = JSON_PARSE_OBJECT_NAME;
1353         } else if (token->type == '}') {
1354             json_parser_pop(p);
1355         } else {
1356             json_error(p, "syntax error expecting '}' or ','");
1357         }
1358         break;
1359
1360     case JSON_PARSE_ARRAY_INIT:
1361         if (token->type == ']') {
1362             json_parser_pop(p);
1363             break;
1364         }
1365         /* Fall through. */
1366     case JSON_PARSE_ARRAY_VALUE:
1367         json_parse_value(p, token, JSON_PARSE_ARRAY_NEXT);
1368         break;
1369
1370     case JSON_PARSE_ARRAY_NEXT:
1371         if (token->type == ',') {
1372             p->parse_state = JSON_PARSE_ARRAY_VALUE;
1373         } else if (token->type == ']') {
1374             json_parser_pop(p);
1375         } else {
1376             json_error(p, "syntax error expecting ']' or ','");
1377         }
1378         break;
1379
1380     default:
1381         abort();
1382     }
1383
1384     p->lex_state = JSON_LEX_START;
1385     ds_clear(&p->buffer);
1386 }
1387
1388 static struct json *
1389 json_create(enum json_type type)
1390 {
1391     struct json *json = xmalloc(sizeof *json);
1392     json->type = type;
1393     return json;
1394 }
1395
1396 static void
1397 json_error(struct json_parser *p, const char *format, ...)
1398 {
1399     if (!p->error) {
1400         struct ds msg;
1401         va_list args;
1402
1403         ds_init(&msg);
1404         ds_put_format(&msg, "line %d, column %d, byte %d: ",
1405                       p->line_number, p->column_number, p->byte_number);
1406         va_start(args, format);
1407         ds_put_format_valist(&msg, format, args);
1408         va_end(args);
1409
1410         p->error = ds_steal_cstr(&msg);
1411
1412         p->done = true;
1413     }
1414 }
1415 \f
1416 #define SPACES_PER_LEVEL 2
1417
1418 struct json_serializer {
1419     struct ds *ds;
1420     int depth;
1421     int flags;
1422 };
1423
1424 static void json_serialize(const struct json *, struct json_serializer *);
1425 static void json_serialize_object(const struct shash *object,
1426                                   struct json_serializer *);
1427 static void json_serialize_array(const struct json_array *,
1428                                  struct json_serializer *);
1429 static void json_serialize_string(const char *, struct ds *);
1430
1431 /* Converts 'json' to a string in JSON format, encoded in UTF-8, and returns
1432  * that string.  The caller is responsible for freeing the returned string,
1433  * with free(), when it is no longer needed.
1434  *
1435  * If 'flags' contains JSSF_PRETTY, the output is pretty-printed with each
1436  * nesting level introducing an additional indentation.  Otherwise, the
1437  * returned string does not contain any new-line characters.
1438  *
1439  * If 'flags' contains JSSF_SORT, members of objects in the output are sorted
1440  * in bytewise lexicographic order for reproducibility.  Otherwise, members of
1441  * objects are output in an indeterminate order.
1442  *
1443  * The returned string is valid JSON only if 'json' represents an array or an
1444  * object, since a bare literal does not satisfy the JSON grammar. */
1445 char *
1446 json_to_string(const struct json *json, int flags)
1447 {
1448     struct ds ds;
1449
1450     ds_init(&ds);
1451     json_to_ds(json, flags, &ds);
1452     return ds_steal_cstr(&ds);
1453 }
1454
1455 /* Same as json_to_string(), but the output is appended to 'ds'. */
1456 void
1457 json_to_ds(const struct json *json, int flags, struct ds *ds)
1458 {
1459     struct json_serializer s;
1460
1461     s.ds = ds;
1462     s.depth = 0;
1463     s.flags = flags;
1464     json_serialize(json, &s);
1465 }
1466
1467 static void
1468 json_serialize(const struct json *json, struct json_serializer *s)
1469 {
1470     struct ds *ds = s->ds;
1471
1472     switch (json->type) {
1473     case JSON_NULL:
1474         ds_put_cstr(ds, "null");
1475         break;
1476
1477     case JSON_FALSE:
1478         ds_put_cstr(ds, "false");
1479         break;
1480
1481     case JSON_TRUE:
1482         ds_put_cstr(ds, "true");
1483         break;
1484
1485     case JSON_OBJECT:
1486         json_serialize_object(json->u.object, s);
1487         break;
1488
1489     case JSON_ARRAY:
1490         json_serialize_array(&json->u.array, s);
1491         break;
1492
1493     case JSON_INTEGER:
1494         ds_put_format(ds, "%lld", json->u.integer);
1495         break;
1496
1497     case JSON_REAL:
1498         ds_put_format(ds, "%.*g", DBL_DIG, json->u.real);
1499         break;
1500
1501     case JSON_STRING:
1502         json_serialize_string(json->u.string, ds);
1503         break;
1504
1505     case JSON_N_TYPES:
1506     default:
1507         NOT_REACHED();
1508     }
1509 }
1510
1511 static void
1512 indent_line(struct json_serializer *s)
1513 {
1514     if (s->flags & JSSF_PRETTY) {
1515         ds_put_char(s->ds, '\n');
1516         ds_put_char_multiple(s->ds, ' ', SPACES_PER_LEVEL * s->depth);
1517     }
1518 }
1519
1520 static void
1521 json_serialize_object_member(size_t i, const struct shash_node *node,
1522                              struct json_serializer *s)
1523 {
1524     struct ds *ds = s->ds;
1525
1526     if (i) {
1527         ds_put_char(ds, ',');
1528         indent_line(s);
1529     }
1530
1531     json_serialize_string(node->name, ds);
1532     ds_put_char(ds, ':');
1533     if (s->flags & JSSF_PRETTY) {
1534         ds_put_char(ds, ' ');
1535     }
1536     json_serialize(node->data, s);
1537 }
1538
1539 static void
1540 json_serialize_object(const struct shash *object, struct json_serializer *s)
1541 {
1542     struct ds *ds = s->ds;
1543
1544     ds_put_char(ds, '{');
1545
1546     s->depth++;
1547     indent_line(s);
1548
1549     if (s->flags & JSSF_SORT) {
1550         const struct shash_node **nodes;
1551         size_t n, i;
1552
1553         nodes = shash_sort(object);
1554         n = shash_count(object);
1555         for (i = 0; i < n; i++) {
1556             json_serialize_object_member(i, nodes[i], s);
1557         }
1558         free(nodes);
1559     } else {
1560         struct shash_node *node;
1561         size_t i;
1562
1563         i = 0;
1564         SHASH_FOR_EACH (node, object) {
1565             json_serialize_object_member(i++, node, s);
1566         }
1567     }
1568
1569     ds_put_char(ds, '}');
1570     s->depth--;
1571 }
1572
1573 static void
1574 json_serialize_array(const struct json_array *array, struct json_serializer *s)
1575 {
1576     struct ds *ds = s->ds;
1577     size_t i;
1578
1579     ds_put_char(ds, '[');
1580     s->depth++;
1581
1582     if (array->n > 0) {
1583         indent_line(s);
1584
1585         for (i = 0; i < array->n; i++) {
1586             if (i) {
1587                 ds_put_char(ds, ',');
1588                 indent_line(s);
1589             }
1590             json_serialize(array->elems[i], s);
1591         }
1592     }
1593
1594     s->depth--;
1595     ds_put_char(ds, ']');
1596 }
1597
1598 static void
1599 json_serialize_string(const char *string, struct ds *ds)
1600 {
1601     uint8_t c;
1602
1603     ds_put_char(ds, '"');
1604     while ((c = *string++) != '\0') {
1605         switch (c) {
1606         case '"':
1607             ds_put_cstr(ds, "\\\"");
1608             break;
1609
1610         case '\\':
1611             ds_put_cstr(ds, "\\\\");
1612             break;
1613
1614         case '\b':
1615             ds_put_cstr(ds, "\\b");
1616             break;
1617
1618         case '\f':
1619             ds_put_cstr(ds, "\\f");
1620             break;
1621
1622         case '\n':
1623             ds_put_cstr(ds, "\\n");
1624             break;
1625
1626         case '\r':
1627             ds_put_cstr(ds, "\\r");
1628             break;
1629
1630         case '\t':
1631             ds_put_cstr(ds, "\\t");
1632             break;
1633
1634         default:
1635             if (c >= 32) {
1636                 ds_put_char(ds, c);
1637             } else {
1638                 ds_put_format(ds, "\\u%04x", c);
1639             }
1640             break;
1641         }
1642     }
1643     ds_put_char(ds, '"');
1644 }