2 * Copyright (c) 2009 Petri Lehtinen <petri@digip.org>
4 * Jansson is free software; you can redistribute it and/or modify
5 * it under the terms of the MIT license. See LICENSE for details.
20 #include "jansson_private.h"
21 #include "strbuffer.h"
24 #define TOKEN_INVALID -1
26 #define TOKEN_STRING 256
27 #define TOKEN_INTEGER 257
28 #define TOKEN_REAL 258
29 #define TOKEN_TRUE 259
30 #define TOKEN_FALSE 260
31 #define TOKEN_NULL 261
33 /* read one byte from stream, return EOF on end of file */
34 typedef int (*get_func)(void *data);
36 /* return non-zero if end of file has been reached */
37 typedef int (*eof_func)(void *data);
51 strbuffer_t saved_text;
62 /*** error reporting ***/
64 static void error_init(json_error_t *error)
68 error->text[0] = '\0';
73 static void error_set(json_error_t *error, const lex_t *lex,
77 char text[JSON_ERROR_TEXT_LENGTH];
79 if(!error || error->text[0] != '\0') {
80 /* error already set */
85 vsnprintf(text, JSON_ERROR_TEXT_LENGTH, msg, ap);
90 const char *saved_text = strbuffer_value(&lex->saved_text);
91 error->line = lex->line;
92 if(saved_text && saved_text[0])
94 if(lex->saved_text.length <= 20) {
95 snprintf(error->text, JSON_ERROR_TEXT_LENGTH,
96 "%s near '%s'", text, saved_text);
99 snprintf(error->text, JSON_ERROR_TEXT_LENGTH, "%s", text);
103 snprintf(error->text, JSON_ERROR_TEXT_LENGTH,
104 "%s near end of file", text);
110 snprintf(error->text, JSON_ERROR_TEXT_LENGTH, "%s", text);
115 /*** lexical analyzer ***/
117 void stream_init(stream_t *stream, get_func get, eof_func eof, void *data)
122 stream->stream_pos = 0;
123 stream->buffer[0] = '\0';
124 stream->buffer_pos = 0;
127 static char stream_get(stream_t *stream, json_error_t *error)
131 if(!stream->buffer[stream->buffer_pos])
133 stream->buffer[0] = stream->get(stream->data);
134 stream->buffer_pos = 0;
136 c = stream->buffer[0];
138 if((unsigned char)c >= 0x80 && c != (char)EOF)
140 /* multi-byte UTF-8 sequence */
143 count = utf8_check_first(c);
149 for(i = 1; i < count; i++)
150 stream->buffer[i] = stream->get(stream->data);
152 if(!utf8_check_full(stream->buffer, count))
155 stream->stream_pos += count;
156 stream->buffer[count] = '\0';
159 stream->buffer[1] = '\0';
160 stream->stream_pos++;
164 return stream->buffer[stream->buffer_pos++];
167 error_set(error, NULL, "unable to decode byte 0x%x at position %d",
168 (unsigned char)c, stream->stream_pos);
170 stream->buffer[0] = EOF;
171 stream->buffer[1] = '\0';
172 stream->buffer_pos = 1;
177 static void stream_unget(stream_t *stream, char c)
179 assert(stream->buffer_pos > 0);
180 stream->buffer_pos--;
181 assert(stream->buffer[stream->buffer_pos] == c);
185 static int lex_get(lex_t *lex, json_error_t *error)
187 return stream_get(&lex->stream, error);
190 static int lex_eof(lex_t *lex)
192 return lex->stream.eof(lex->stream.data);
195 static void lex_save(lex_t *lex, char c)
197 strbuffer_append_byte(&lex->saved_text, c);
200 static int lex_get_save(lex_t *lex, json_error_t *error)
202 char c = stream_get(&lex->stream, error);
207 static void lex_unget_unsave(lex_t *lex, char c)
210 stream_unget(&lex->stream, c);
211 d = strbuffer_pop(&lex->saved_text);
215 static void lex_save_cached(lex_t *lex)
217 while(lex->stream.buffer[lex->stream.buffer_pos] != '\0')
219 lex_save(lex, lex->stream.buffer[lex->stream.buffer_pos]);
220 lex->stream.buffer_pos++;
224 /* assumes that str points to 'u' plus at least 4 valid hex digits */
225 static int decode_unicode_escape(const char *str)
230 assert(str[0] == 'u');
232 for(i = 1; i <= 4; i++) {
238 value += c - 'a' + 10;
240 value += c - 'A' + 10;
248 static void lex_scan_string(lex_t *lex, json_error_t *error)
255 lex->value.string = NULL;
256 lex->token = TOKEN_INVALID;
258 c = lex_get_save(lex, error);
262 lex_unget_unsave(lex, c);
264 error_set(error, lex, "premature end of input");
268 else if((unsigned char)c <= 0x1F) {
269 /* control character */
270 lex_unget_unsave(lex, c);
272 error_set(error, lex, "unexpected newline", c);
274 error_set(error, lex, "control character 0x%x", c);
279 c = lex_get_save(lex, error);
281 c = lex_get_save(lex, error);
282 for(i = 0; i < 4; i++) {
284 lex_unget_unsave(lex, c);
285 error_set(error, lex, "invalid escape");
288 c = lex_get_save(lex, error);
291 else if(c == '"' || c == '\\' || c == '/' || c == 'b' ||
292 c == 'f' || c == 'n' || c == 'r' || c == 't')
293 c = lex_get_save(lex, error);
295 lex_unget_unsave(lex, c);
296 error_set(error, lex, "invalid escape");
301 c = lex_get_save(lex, error);
304 /* the actual value is at most of the same length as the source
306 - shortcut escapes (e.g. "\t") (length 2) are converted to 1 byte
307 - a single \uXXXX escape (length 6) is converted to at most 3 bytes
308 - two \uXXXX escapes (length 12) forming an UTF-16 surrogate pair
309 are converted to 4 bytes
311 lex->value.string = malloc(lex->saved_text.length + 1);
312 if(!lex->value.string) {
313 /* this is not very nice, since TOKEN_INVALID is returned */
318 t = lex->value.string;
320 /* + 1 to skip the " */
321 p = strbuffer_value(&lex->saved_text) + 1;
331 value = decode_unicode_escape(p);
334 if(0xD800 <= value && value <= 0xDBFF) {
336 if(*p == '\\' && *(p + 1) == 'u') {
337 int value2 = decode_unicode_escape(++p);
340 if(0xDC00 <= value2 && value2 <= 0xDFFF) {
341 /* valid second surrogate */
342 value = ((value - 0xD800) << 10) +
347 /* invalid second surrogate */
348 error_set(error, lex,
349 "invalid Unicode '\\u%04X\\u%04X'",
355 /* no second surrogate */
356 error_set(error, lex, "invalid Unicode '\\u%04X'",
361 else if(0xDC00 <= value && value <= 0xDFFF) {
362 error_set(error, lex, "invalid Unicode '\\u%04X'", value);
367 error_set(error, lex, "\\u0000 is not allowed");
371 if(utf8_encode(value, buffer, &length))
374 memcpy(t, buffer, length);
379 case '"': case '\\': case '/':
381 case 'b': *t = '\b'; break;
382 case 'f': *t = '\f'; break;
383 case 'n': *t = '\n'; break;
384 case 'r': *t = '\r'; break;
385 case 't': *t = '\t'; break;
396 lex->token = TOKEN_STRING;
400 free(lex->value.string);
403 static int lex_scan_number(lex_t *lex, char c, json_error_t *error)
405 const char *saved_text;
409 lex->token = TOKEN_INVALID;
412 c = lex_get_save(lex, error);
415 c = lex_get_save(lex, error);
417 lex_unget_unsave(lex, c);
421 else /* c != '0' */ {
422 c = lex_get_save(lex, error);
424 c = lex_get_save(lex, error);
427 if(c != '.' && c != 'E' && c != 'e') {
430 lex_unget_unsave(lex, c);
432 saved_text = strbuffer_value(&lex->saved_text);
433 value = strtol(saved_text, &end, 10);
434 assert(end == saved_text + lex->saved_text.length);
436 if((value == LONG_MAX && errno == ERANGE) || value > INT_MAX) {
437 error_set(error, lex, "too big integer");
440 else if((value == LONG_MIN && errno == ERANGE) || value < INT_MIN) {
441 error_set(error, lex, "too big negative integer");
445 lex->token = TOKEN_INTEGER;
446 lex->value.integer = (int)value;
451 c = lex_get(lex, error);
456 c = lex_get_save(lex, error);
458 c = lex_get_save(lex, error);
461 if(c == 'E' || c == 'e') {
462 c = lex_get_save(lex, error);
463 if(c == '+' || c == '-')
464 c = lex_get_save(lex, error);
467 lex_unget_unsave(lex, c);
471 c = lex_get_save(lex, error);
473 c = lex_get_save(lex, error);
476 lex_unget_unsave(lex, c);
478 saved_text = strbuffer_value(&lex->saved_text);
479 value = strtod(saved_text, &end);
480 assert(end == saved_text + lex->saved_text.length);
482 if(value == 0 && errno == ERANGE) {
483 error_set(error, lex, "real number underflow");
487 /* Cannot test for +/-HUGE_VAL because the HUGE_VAL constant is
488 only defined in C99 mode. So let's trust in sole errno. */
489 else if(errno == ERANGE) {
490 error_set(error, lex, "real number overflow");
494 lex->token = TOKEN_REAL;
495 lex->value.real = value;
502 static int lex_scan(lex_t *lex, json_error_t *error)
506 strbuffer_clear(&lex->saved_text);
508 if(lex->token == TOKEN_STRING) {
509 free(lex->value.string);
510 lex->value.string = NULL;
513 c = lex_get(lex, error);
514 while(c == ' ' || c == '\t' || c == '\n' || c == '\r')
519 c = lex_get(lex, error);
524 lex->token = TOKEN_EOF;
526 lex->token = TOKEN_INVALID;
532 if(c == '{' || c == '}' || c == '[' || c == ']' || c == ':' || c == ',')
536 lex_scan_string(lex, error);
538 else if(isdigit(c) || c == '-') {
539 if(lex_scan_number(lex, c, error))
543 else if(isupper(c) || islower(c)) {
544 /* eat up the whole identifier for clearer error messages */
545 const char *saved_text;
547 c = lex_get_save(lex, error);
548 while(isupper(c) || islower(c))
549 c = lex_get_save(lex, error);
550 lex_unget_unsave(lex, c);
552 saved_text = strbuffer_value(&lex->saved_text);
554 if(strcmp(saved_text, "true") == 0)
555 lex->token = TOKEN_TRUE;
556 else if(strcmp(saved_text, "false") == 0)
557 lex->token = TOKEN_FALSE;
558 else if(strcmp(saved_text, "null") == 0)
559 lex->token = TOKEN_NULL;
561 lex->token = TOKEN_INVALID;
565 /* save the rest of the input UTF-8 sequence to get an error
566 message of valid UTF-8 */
567 lex_save_cached(lex);
568 lex->token = TOKEN_INVALID;
575 static int lex_init(lex_t *lex, get_func get, eof_func eof, void *data)
577 stream_init(&lex->stream, get, eof, data);
578 if(strbuffer_init(&lex->saved_text))
581 lex->token = TOKEN_INVALID;
587 static void lex_close(lex_t *lex)
589 if(lex->token == TOKEN_STRING)
590 free(lex->value.string);
591 strbuffer_close(&lex->saved_text);
597 static json_t *parse_value(lex_t *lex, json_error_t *error);
599 static json_t *parse_object(lex_t *lex, json_error_t *error)
601 json_t *object = json_object();
605 lex_scan(lex, error);
606 if(lex->token == '}')
613 if(lex->token != TOKEN_STRING) {
614 error_set(error, lex, "string or '}' expected");
618 key = strdup(lex->value.string);
622 lex_scan(lex, error);
623 if(lex->token != ':') {
625 error_set(error, lex, "':' expected");
629 lex_scan(lex, error);
630 value = parse_value(lex, error);
636 if(json_object_set_nocheck(object, key, value)) {
645 lex_scan(lex, error);
646 if(lex->token != ',')
649 lex_scan(lex, error);
652 if(lex->token != '}') {
653 error_set(error, lex, "'}' expected");
664 static json_t *parse_array(lex_t *lex, json_error_t *error)
666 json_t *array = json_array();
670 lex_scan(lex, error);
671 if(lex->token == ']')
675 json_t *elem = parse_value(lex, error);
679 if(json_array_append(array, elem)) {
685 lex_scan(lex, error);
686 if(lex->token != ',')
689 lex_scan(lex, error);
692 if(lex->token != ']') {
693 error_set(error, lex, "']' expected");
704 static json_t *parse_value(lex_t *lex, json_error_t *error)
710 json = json_string_nocheck(lex->value.string);
714 case TOKEN_INTEGER: {
715 json = json_integer(lex->value.integer);
720 json = json_real(lex->value.real);
737 json = parse_object(lex, error);
741 json = parse_array(lex, error);
745 error_set(error, lex, "invalid token");
749 error_set(error, lex, "unexpected token");
759 json_t *parse_json(lex_t *lex, json_error_t *error)
763 lex_scan(lex, error);
764 if(lex->token != '[' && lex->token != '{') {
765 error_set(error, lex, "'[' or '{' expected");
769 return parse_value(lex, error);
778 static int string_get(void *data)
781 string_data_t *stream = (string_data_t *)data;
782 c = stream->data[stream->pos];
792 static int string_eof(void *data)
794 string_data_t *stream = (string_data_t *)data;
795 return (stream->data[stream->pos] == '\0');
798 json_t *json_loads(const char *string, json_error_t *error)
803 string_data_t stream_data = {
808 if(lex_init(&lex, string_get, string_eof, (void *)&stream_data))
811 result = parse_json(&lex, error);
815 lex_scan(&lex, error);
816 if(lex.token != TOKEN_EOF) {
817 error_set(error, &lex, "end of file expected");
827 json_t *json_loadf(FILE *input, json_error_t *error)
832 if(lex_init(&lex, (get_func)fgetc, (eof_func)feof, input))
835 result = parse_json(&lex, error);
839 lex_scan(&lex, error);
840 if(lex.token != TOKEN_EOF) {
841 error_set(error, &lex, "end of file expected");
851 json_t *json_load_file(const char *path, json_error_t *error)
856 fp = fopen(path, "r");
859 error_set(error, NULL, "unable to open %s: %s",
860 path, strerror(errno));
864 result = json_loadf(fp, error);