e2343b600721047e81284c7973d5ae17bda2b78a
[external/libjson-glib.git] / json-glib / json-parser.c
1 /* json-parser.c - JSON streams parser
2  * 
3  * This file is part of JSON-GLib
4  *
5  * Copyright © 2007, 2008, 2009 OpenedHand Ltd
6  * Copyright © 2009, 2010 Intel Corp.
7  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with this library. If not, see <http://www.gnu.org/licenses/>.
20  *
21  * Author:
22  *   Emmanuele Bassi  <ebassi@linux.intel.com>
23  */
24
25 /**
26  * SECTION:json-parser
27  * @short_description: Parse JSON data streams
28  *
29  * #JsonParser provides an object for parsing a JSON data stream, either
30  * inside a file or inside a static buffer.
31  */
32
33 #include "config.h"
34
35 #include <string.h>
36
37 #include <glib/gi18n-lib.h>
38
39 #include "json-types-private.h"
40
41 #include "json-debug.h"
42 #include "json-marshal.h"
43 #include "json-parser.h"
44 #include "json-scanner.h"
45
46 struct _JsonParserPrivate
47 {
48   JsonNode *root;
49   JsonNode *current_node;
50
51   JsonScanner *scanner;
52
53   JsonParserError error_code;
54   GError *last_error;
55
56   gchar *variable_name;
57   gchar *filename;
58
59   guint has_assignment : 1;
60   guint is_filename    : 1;
61 };
62
63 static const gchar symbol_names[] =
64   "true\0"
65   "false\0"
66   "null\0"
67   "var\0";
68
69 static const struct
70 {
71   guint name_offset;
72   guint token;
73 } symbols[] = {
74   {  0, JSON_TOKEN_TRUE  },
75   {  5, JSON_TOKEN_FALSE },
76   { 11, JSON_TOKEN_NULL  },
77   { 16, JSON_TOKEN_VAR   }
78 };
79
80 static const guint n_symbols = G_N_ELEMENTS (symbols);
81
82 enum
83 {
84   PARSE_START,
85   OBJECT_START,
86   OBJECT_MEMBER,
87   OBJECT_END,
88   ARRAY_START,
89   ARRAY_ELEMENT,
90   ARRAY_END,
91   PARSE_END,
92   ERROR,
93
94   LAST_SIGNAL
95 };
96
97 static guint parser_signals[LAST_SIGNAL] = { 0, };
98
99 G_DEFINE_QUARK (json-parser-error-quark, json_parser_error)
100
101 G_DEFINE_TYPE_WITH_PRIVATE (JsonParser, json_parser, G_TYPE_OBJECT)
102
103 static guint json_parse_array  (JsonParser   *parser,
104                                 JsonScanner  *scanner,
105                                 JsonNode    **node);
106 static guint json_parse_object (JsonParser   *parser,
107                                 JsonScanner  *scanner,
108                                 JsonNode    **node);
109
110 static inline void
111 json_parser_clear (JsonParser *parser)
112 {
113   JsonParserPrivate *priv = parser->priv;
114
115   g_free (priv->variable_name);
116   priv->variable_name = NULL;
117
118   if (priv->last_error)
119     {
120       g_error_free (priv->last_error);
121       priv->last_error = NULL;
122     }
123
124   if (priv->root)
125     {
126       json_node_free (priv->root);
127       priv->root = NULL;
128     }
129 }
130
131 static void
132 json_parser_dispose (GObject *gobject)
133 {
134   json_parser_clear (JSON_PARSER (gobject));
135
136   G_OBJECT_CLASS (json_parser_parent_class)->dispose (gobject);
137 }
138
139 static void
140 json_parser_finalize (GObject *gobject)
141 {
142   JsonParserPrivate *priv = JSON_PARSER (gobject)->priv;
143
144   g_free (priv->variable_name);
145   g_free (priv->filename);
146
147   G_OBJECT_CLASS (json_parser_parent_class)->finalize (gobject);
148 }
149
150 static void
151 json_parser_class_init (JsonParserClass *klass)
152 {
153   GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
154
155   gobject_class->dispose = json_parser_dispose;
156   gobject_class->finalize = json_parser_finalize;
157
158   /**
159    * JsonParser::parse-start:
160    * @parser: the #JsonParser that received the signal
161    * 
162    * The ::parse-start signal is emitted when the parser began parsing
163    * a JSON data stream.
164    */
165   parser_signals[PARSE_START] =
166     g_signal_new ("parse-start",
167                   G_OBJECT_CLASS_TYPE (gobject_class),
168                   G_SIGNAL_RUN_LAST,
169                   G_STRUCT_OFFSET (JsonParserClass, parse_start),
170                   NULL, NULL,
171                   _json_marshal_VOID__VOID,
172                   G_TYPE_NONE, 0);
173   /**
174    * JsonParser::parse-end:
175    * @parser: the #JsonParser that received the signal
176    *
177    * The ::parse-end signal is emitted when the parser successfully
178    * finished parsing a JSON data stream
179    */
180   parser_signals[PARSE_END] =
181     g_signal_new ("parse-end",
182                   G_OBJECT_CLASS_TYPE (gobject_class),
183                   G_SIGNAL_RUN_LAST,
184                   G_STRUCT_OFFSET (JsonParserClass, parse_end),
185                   NULL, NULL,
186                   _json_marshal_VOID__VOID,
187                   G_TYPE_NONE, 0);
188   /**
189    * JsonParser::object-start:
190    * @parser: the #JsonParser that received the signal
191    * 
192    * The ::object-start signal is emitted each time the #JsonParser
193    * starts parsing a #JsonObject.
194    */
195   parser_signals[OBJECT_START] =
196     g_signal_new ("object-start",
197                   G_OBJECT_CLASS_TYPE (gobject_class),
198                   G_SIGNAL_RUN_LAST,
199                   G_STRUCT_OFFSET (JsonParserClass, object_start),
200                   NULL, NULL,
201                   _json_marshal_VOID__VOID,
202                   G_TYPE_NONE, 0);
203   /**
204    * JsonParser::object-member:
205    * @parser: the #JsonParser that received the signal
206    * @object: a #JsonObject
207    * @member_name: the name of the newly parsed member
208    *
209    * The ::object-member signal is emitted each time the #JsonParser
210    * has successfully parsed a single member of a #JsonObject. The
211    * object and member are passed to the signal handlers.
212    */
213   parser_signals[OBJECT_MEMBER] =
214     g_signal_new ("object-member",
215                   G_OBJECT_CLASS_TYPE (gobject_class),
216                   G_SIGNAL_RUN_LAST,
217                   G_STRUCT_OFFSET (JsonParserClass, object_member),
218                   NULL, NULL,
219                   _json_marshal_VOID__BOXED_STRING,
220                   G_TYPE_NONE, 2,
221                   JSON_TYPE_OBJECT,
222                   G_TYPE_STRING);
223   /**
224    * JsonParser::object-end:
225    * @parser: the #JsonParser that received the signal
226    * @object: the parsed #JsonObject
227    *
228    * The ::object-end signal is emitted each time the #JsonParser
229    * has successfully parsed an entire #JsonObject.
230    */
231   parser_signals[OBJECT_END] =
232     g_signal_new ("object-end",
233                   G_OBJECT_CLASS_TYPE (gobject_class),
234                   G_SIGNAL_RUN_LAST,
235                   G_STRUCT_OFFSET (JsonParserClass, object_end),
236                   NULL, NULL,
237                   _json_marshal_VOID__BOXED,
238                   G_TYPE_NONE, 1,
239                   JSON_TYPE_OBJECT);
240   /**
241    * JsonParser::array-start:
242    * @parser: the #JsonParser that received the signal
243    *
244    * The ::array-start signal is emitted each time the #JsonParser
245    * starts parsing a #JsonArray
246    */
247   parser_signals[ARRAY_START] =
248     g_signal_new ("array-start",
249                   G_OBJECT_CLASS_TYPE (gobject_class),
250                   G_SIGNAL_RUN_LAST,
251                   G_STRUCT_OFFSET (JsonParserClass, array_start),
252                   NULL, NULL,
253                   _json_marshal_VOID__VOID,
254                   G_TYPE_NONE, 0);
255   /**
256    * JsonParser::array-element:
257    * @parser: the #JsonParser that received the signal
258    * @array: a #JsonArray
259    * @index_: the index of the newly parsed element
260    *
261    * The ::array-element signal is emitted each time the #JsonParser
262    * has successfully parsed a single element of a #JsonArray. The
263    * array and element index are passed to the signal handlers.
264    */
265   parser_signals[ARRAY_ELEMENT] =
266     g_signal_new ("array-element",
267                   G_OBJECT_CLASS_TYPE (gobject_class),
268                   G_SIGNAL_RUN_LAST,
269                   G_STRUCT_OFFSET (JsonParserClass, array_element),
270                   NULL, NULL,
271                   _json_marshal_VOID__BOXED_INT,
272                   G_TYPE_NONE, 2,
273                   JSON_TYPE_ARRAY,
274                   G_TYPE_INT);
275   /**
276    * JsonParser::array-end:
277    * @parser: the #JsonParser that received the signal
278    * @array: the parsed #JsonArray
279    *
280    * The ::array-end signal is emitted each time the #JsonParser
281    * has successfully parsed an entire #JsonArray
282    */
283   parser_signals[ARRAY_END] =
284     g_signal_new ("array-end",
285                   G_OBJECT_CLASS_TYPE (gobject_class),
286                   G_SIGNAL_RUN_LAST,
287                   G_STRUCT_OFFSET (JsonParserClass, array_end),
288                   NULL, NULL,
289                   _json_marshal_VOID__BOXED,
290                   G_TYPE_NONE, 1,
291                   JSON_TYPE_ARRAY);
292   /**
293    * JsonParser::error:
294    * @parser: the parser instance that received the signal
295    * @error: a pointer to the #GError
296    *
297    * The ::error signal is emitted each time a #JsonParser encounters
298    * an error in a JSON stream.
299    */
300   parser_signals[ERROR] =
301     g_signal_new ("error",
302                   G_OBJECT_CLASS_TYPE (gobject_class),
303                   G_SIGNAL_RUN_LAST,
304                   G_STRUCT_OFFSET (JsonParserClass, error),
305                   NULL, NULL,
306                   _json_marshal_VOID__POINTER,
307                   G_TYPE_NONE, 1,
308                   G_TYPE_POINTER);
309 }
310
311 static void
312 json_parser_init (JsonParser *parser)
313 {
314   JsonParserPrivate *priv = json_parser_get_instance_private (parser);
315
316   parser->priv = priv;
317
318   priv->root = NULL;
319   priv->current_node = NULL;
320
321   priv->error_code = JSON_PARSER_ERROR_PARSE;
322   priv->last_error = NULL;
323
324   priv->has_assignment = FALSE;
325   priv->variable_name = NULL;
326
327   priv->is_filename = FALSE;
328   priv->filename = FALSE;
329 }
330
331 static guint
332 json_parse_value (JsonParser   *parser,
333                   JsonScanner  *scanner,
334                   guint         token,
335                   JsonNode    **node)
336 {
337   JsonParserPrivate *priv = parser->priv;
338   JsonNode *current_node = priv->current_node;
339   gboolean is_negative = FALSE;
340
341   if (token == '-')
342     {
343       guint next_token = json_scanner_peek_next_token (scanner);
344
345       if (next_token == G_TOKEN_INT ||
346           next_token == G_TOKEN_FLOAT)
347         {
348            is_negative = TRUE;
349            token = json_scanner_get_next_token (scanner);
350         }
351       else
352         return G_TOKEN_INT;
353     }
354
355   switch (token)
356     {
357     case G_TOKEN_INT:
358       JSON_NOTE (PARSER, "abs(node): %" G_GINT64_FORMAT " (sign: %s)",
359                  scanner->value.v_int64,
360                  is_negative ? "negative" : "positive");
361       *node = json_node_init_int (json_node_alloc (),
362                                   is_negative ? scanner->value.v_int64 * -1
363                                               : scanner->value.v_int64);
364       break;
365
366     case G_TOKEN_FLOAT:
367       JSON_NOTE (PARSER, "abs(node): %.6f (sign: %s)",
368                  scanner->value.v_float,
369                  is_negative ? "negative" : "positive");
370       *node = json_node_init_double (json_node_alloc (),
371                                      is_negative ? scanner->value.v_float * -1.0
372                                                  : scanner->value.v_float);
373       break;
374
375     case G_TOKEN_STRING:
376       JSON_NOTE (PARSER, "node: '%s'",
377                  scanner->value.v_string);
378       *node = json_node_init_string (json_node_alloc (), scanner->value.v_string);
379       break;
380
381     case JSON_TOKEN_TRUE:
382     case JSON_TOKEN_FALSE:
383       JSON_NOTE (PARSER, "node: '%s'",
384                  JSON_TOKEN_TRUE ? "<true>" : "<false>");
385       *node = json_node_init_boolean (json_node_alloc (), token == JSON_TOKEN_TRUE ? TRUE : FALSE);
386       break;
387
388     case JSON_TOKEN_NULL:
389       JSON_NOTE (PARSER, "node: <null>");
390       *node = json_node_init_null (json_node_alloc ());
391       break;
392
393     case G_TOKEN_IDENTIFIER:
394       JSON_NOTE (PARSER, "node: identifier '%s'", scanner->value.v_identifier);
395       priv->error_code = JSON_PARSER_ERROR_INVALID_BAREWORD;
396       *node = NULL;
397       return G_TOKEN_SYMBOL;
398
399     default:
400       {
401         JsonNodeType cur_type;
402
403         *node = NULL;
404
405         JSON_NOTE (PARSER, "node: invalid token");
406
407         cur_type = json_node_get_node_type (current_node);
408         if (cur_type == JSON_NODE_ARRAY)
409           {
410             priv->error_code = JSON_PARSER_ERROR_PARSE;
411             return G_TOKEN_RIGHT_BRACE;
412           }
413         else if (cur_type == JSON_NODE_OBJECT)
414           {
415             priv->error_code = JSON_PARSER_ERROR_PARSE;
416             return G_TOKEN_RIGHT_CURLY;
417           }
418         else
419           {
420             priv->error_code = JSON_PARSER_ERROR_INVALID_BAREWORD;
421             return G_TOKEN_SYMBOL;
422           }
423       }
424       break;
425     }
426
427   return G_TOKEN_NONE;
428 }
429
430 static guint
431 json_parse_array (JsonParser   *parser,
432                   JsonScanner  *scanner,
433                   JsonNode    **node)
434 {
435   JsonParserPrivate *priv = parser->priv;
436   JsonNode *old_current;
437   JsonArray *array;
438   guint token;
439   gint idx;
440
441   old_current = priv->current_node;
442   priv->current_node = json_node_init_array (json_node_alloc (), NULL);
443
444   array = json_array_new ();
445
446   token = json_scanner_get_next_token (scanner);
447   g_assert (token == G_TOKEN_LEFT_BRACE);
448
449   g_signal_emit (parser, parser_signals[ARRAY_START], 0);
450
451   idx = 0;
452   while (token != G_TOKEN_RIGHT_BRACE)
453     {
454       guint next_token = json_scanner_peek_next_token (scanner);
455       JsonNode *element = NULL;
456
457       /* parse the element */
458       switch (next_token)
459         {
460         case G_TOKEN_LEFT_BRACE:
461           JSON_NOTE (PARSER, "Nested array at index %d", idx);
462           token = json_parse_array (parser, scanner, &element);
463           break;
464
465         case G_TOKEN_LEFT_CURLY:
466           JSON_NOTE (PARSER, "Nested object at index %d", idx);
467           token = json_parse_object (parser, scanner, &element);
468           break;
469
470         case G_TOKEN_RIGHT_BRACE:
471           goto array_done;
472
473         default:
474           token = json_scanner_get_next_token (scanner);
475           token = json_parse_value (parser, scanner, token, &element);
476           break;
477         }
478
479       if (token != G_TOKEN_NONE || element == NULL)
480         {
481           /* the json_parse_* functions will have set the error code */
482           json_array_unref (array);
483           json_node_free (priv->current_node);
484           priv->current_node = old_current;
485
486           return token;
487         }
488
489       next_token = json_scanner_peek_next_token (scanner);
490
491       if (next_token == G_TOKEN_COMMA)
492         {
493           token = json_scanner_get_next_token (scanner);
494           next_token = json_scanner_peek_next_token (scanner);
495
496           /* look for trailing commas */
497           if (next_token == G_TOKEN_RIGHT_BRACE)
498             {
499               priv->error_code = JSON_PARSER_ERROR_TRAILING_COMMA;
500
501               json_array_unref (array);
502               json_node_free (priv->current_node);
503               json_node_free (element);
504               priv->current_node = old_current;
505
506               return G_TOKEN_RIGHT_BRACE;
507             }
508         }
509
510       JSON_NOTE (PARSER, "Array element %d completed", idx + 1);
511       json_node_set_parent (element, priv->current_node);
512       json_array_add_element (array, element);
513
514       g_signal_emit (parser, parser_signals[ARRAY_ELEMENT], 0,
515                      array,
516                      idx);
517
518       token = next_token;
519     }
520
521 array_done:
522   json_scanner_get_next_token (scanner);
523
524   json_node_take_array (priv->current_node, array);
525   json_node_set_parent (priv->current_node, old_current);
526
527   g_signal_emit (parser, parser_signals[ARRAY_END], 0, array);
528
529   if (node != NULL && *node == NULL)
530     *node = priv->current_node;
531
532   priv->current_node = old_current;
533
534   return G_TOKEN_NONE;
535 }
536
537 static guint
538 json_parse_object (JsonParser   *parser,
539                    JsonScanner  *scanner,
540                    JsonNode    **node)
541 {
542   JsonParserPrivate *priv = parser->priv;
543   JsonObject *object;
544   JsonNode *old_current;
545   guint token;
546
547   old_current = priv->current_node;
548   priv->current_node = json_node_init_object (json_node_alloc (), NULL);
549
550   object = json_object_new ();
551
552   token = json_scanner_get_next_token (scanner);
553   g_assert (token == G_TOKEN_LEFT_CURLY);
554
555   g_signal_emit (parser, parser_signals[OBJECT_START], 0);
556
557   while (token != G_TOKEN_RIGHT_CURLY)
558     {
559       guint next_token = json_scanner_peek_next_token (scanner);
560       JsonNode *member = NULL;
561       gchar *name;
562
563       /* we need to abort here because empty objects do not
564        * have member names
565        */
566       if (next_token == G_TOKEN_RIGHT_CURLY)
567         break;
568
569       /* parse the member's name */
570       if (next_token != G_TOKEN_STRING)
571         {
572           JSON_NOTE (PARSER, "Missing object member name");
573
574           priv->error_code = JSON_PARSER_ERROR_INVALID_BAREWORD;
575
576           json_object_unref (object);
577           json_node_free (priv->current_node);
578           priv->current_node = old_current;
579
580           return G_TOKEN_STRING;
581         }
582
583       /* member name */
584       token = json_scanner_get_next_token (scanner);
585       name = g_strdup (scanner->value.v_string);
586       if (name == NULL || *name == '\0')
587         {
588           JSON_NOTE (PARSER, "Empty object member name");
589
590           priv->error_code = JSON_PARSER_ERROR_EMPTY_MEMBER_NAME;
591
592           json_object_unref (object);
593           json_node_free (priv->current_node);
594           priv->current_node = old_current;
595
596           return G_TOKEN_STRING;
597         }
598
599       JSON_NOTE (PARSER, "Object member '%s'", name);
600
601       /* a colon separates names from values */
602       next_token = json_scanner_peek_next_token (scanner);
603       if (next_token != ':')
604         {
605           JSON_NOTE (PARSER, "Missing object member name separator");
606
607           priv->error_code = JSON_PARSER_ERROR_MISSING_COLON;
608
609           g_free (name);
610           json_object_unref (object);
611           json_node_free (priv->current_node);
612           priv->current_node = old_current;
613
614           return ':';
615         }
616
617       /* we swallow the ':' */
618       token = json_scanner_get_next_token (scanner);
619       g_assert (token == ':');
620       next_token = json_scanner_peek_next_token (scanner);
621
622       /* parse the member's value */
623       switch (next_token)
624         {
625         case G_TOKEN_LEFT_BRACE:
626           JSON_NOTE (PARSER, "Nested array at member %s", name);
627           token = json_parse_array (parser, scanner, &member);
628           break;
629
630         case G_TOKEN_LEFT_CURLY:
631           JSON_NOTE (PARSER, "Nested object at member %s", name);
632           token = json_parse_object (parser, scanner, &member);
633           break;
634
635         default:
636           /* once a member name is defined we need a value */
637           token = json_scanner_get_next_token (scanner);
638           token = json_parse_value (parser, scanner, token, &member);
639           break;
640         }
641
642       if (token != G_TOKEN_NONE || member == NULL)
643         {
644           /* the json_parse_* functions will have set the error code */
645           g_free (name);
646           json_object_unref (object);
647           json_node_free (priv->current_node);
648           priv->current_node = old_current;
649
650           return token;
651         }
652
653       next_token = json_scanner_peek_next_token (scanner);
654       if (next_token == G_TOKEN_COMMA)
655         {
656           token = json_scanner_get_next_token (scanner);
657           next_token = json_scanner_peek_next_token (scanner);
658
659           /* look for trailing commas */
660           if (next_token == G_TOKEN_RIGHT_CURLY)
661             {
662               priv->error_code = JSON_PARSER_ERROR_TRAILING_COMMA;
663
664               json_object_unref (object);
665               json_node_free (member);
666               json_node_free (priv->current_node);
667               priv->current_node = old_current;
668
669               return G_TOKEN_RIGHT_BRACE;
670             }
671         }
672       else if (next_token == G_TOKEN_STRING)
673         {
674           priv->error_code = JSON_PARSER_ERROR_MISSING_COMMA;
675
676           json_object_unref (object);
677           json_node_free (member);
678           json_node_free (priv->current_node);
679           priv->current_node = old_current;
680
681           return G_TOKEN_COMMA;
682         }
683
684       JSON_NOTE (PARSER, "Object member '%s' completed", name);
685       json_node_set_parent (member, priv->current_node);
686       json_object_set_member (object, name, member);
687
688       g_signal_emit (parser, parser_signals[OBJECT_MEMBER], 0,
689                      object,
690                      name);
691
692       g_free (name);
693
694       token = next_token;
695     }
696
697   json_scanner_get_next_token (scanner);
698
699   json_node_take_object (priv->current_node, object);
700   json_node_set_parent (priv->current_node, old_current);
701
702   g_signal_emit (parser, parser_signals[OBJECT_END], 0, object);
703
704   if (node != NULL && *node == NULL)
705     *node = priv->current_node;
706
707   priv->current_node = old_current;
708
709   return G_TOKEN_NONE;
710 }
711
712 static guint
713 json_parse_statement (JsonParser  *parser,
714                       JsonScanner *scanner)
715 {
716   JsonParserPrivate *priv = parser->priv;
717   guint token;
718
719   token = json_scanner_peek_next_token (scanner);
720   switch (token)
721     {
722     case G_TOKEN_LEFT_CURLY:
723       JSON_NOTE (PARSER, "Statement is object declaration");
724       return json_parse_object (parser, scanner, &priv->root);
725
726     case G_TOKEN_LEFT_BRACE:
727       JSON_NOTE (PARSER, "Statement is array declaration");
728       return json_parse_array (parser, scanner, &priv->root);
729
730     /* some web APIs are not only passing the data structures: they are
731      * also passing an assigment, which makes parsing horribly complicated
732      * only because web developers are lazy, and writing "var foo = " is
733      * evidently too much to request from them.
734      */
735     case JSON_TOKEN_VAR:
736       {
737         guint next_token;
738         gchar *name;
739
740         JSON_NOTE (PARSER, "Statement is an assignment");
741
742         /* swallow the 'var' token... */
743         token = json_scanner_get_next_token (scanner);
744
745         /* ... swallow the variable name... */
746         next_token = json_scanner_get_next_token (scanner);
747         if (next_token != G_TOKEN_IDENTIFIER)
748           {
749             priv->error_code = JSON_PARSER_ERROR_INVALID_BAREWORD;
750             return G_TOKEN_IDENTIFIER;
751           }
752
753         name = g_strdup (scanner->value.v_identifier);
754
755         /* ... and finally swallow the '=' */
756         next_token = json_scanner_get_next_token (scanner);
757         if (next_token != '=')
758           {
759             priv->error_code = JSON_PARSER_ERROR_INVALID_BAREWORD;
760             g_free (name);
761             return '=';
762           }
763
764         priv->has_assignment = TRUE;
765         priv->variable_name = name;
766
767         token = json_parse_statement (parser, scanner);
768
769         /* remove the trailing semi-colon */
770         next_token = json_scanner_peek_next_token (scanner);
771         if (next_token == ';')
772           {
773             token = json_scanner_get_next_token (scanner);
774             return G_TOKEN_NONE;
775           }
776
777         return token;
778       }
779       break;
780
781     case JSON_TOKEN_NULL:
782     case JSON_TOKEN_TRUE:
783     case JSON_TOKEN_FALSE:
784     case '-':
785     case G_TOKEN_INT:
786     case G_TOKEN_FLOAT:
787     case G_TOKEN_STRING:
788     case G_TOKEN_IDENTIFIER:
789       JSON_NOTE (PARSER, "Statement is a value");
790       token = json_scanner_get_next_token (scanner);
791       return json_parse_value (parser, scanner, token, &priv->root);
792
793     default:
794       JSON_NOTE (PARSER, "Unknown statement");
795       json_scanner_get_next_token (scanner);
796       priv->error_code = JSON_PARSER_ERROR_INVALID_BAREWORD;
797       return G_TOKEN_SYMBOL;
798     }
799 }
800
801 static void
802 json_scanner_msg_handler (JsonScanner *scanner,
803                           gchar       *message)
804 {
805   JsonParser *parser = scanner->user_data;
806   JsonParserPrivate *priv = parser->priv;
807   GError *error = NULL;
808
809   /* translators: %s: is the file name, the first %d is the line
810    * number, the second %d is the position on the line, and %s is
811    * the error message
812    */
813   g_set_error (&error, JSON_PARSER_ERROR,
814                priv->error_code,
815                _("%s:%d:%d: Parse error: %s"),
816                priv->is_filename ? priv->filename : "<data>",
817                scanner->line,
818                scanner->position,
819                message);
820       
821   parser->priv->last_error = error;
822   g_signal_emit (parser, parser_signals[ERROR], 0, error);
823 }
824
825 static JsonScanner *
826 json_scanner_create (JsonParser *parser)
827 {
828   JsonScanner *scanner;
829   gint i;
830
831   scanner = json_scanner_new ();
832   scanner->msg_handler = json_scanner_msg_handler;
833   scanner->user_data = parser;
834
835   /* XXX: this is eminently stupid, but we use the symbols later on, so
836    * we cannot move them into JsonScanner without moving a bunch of code
837    * as well
838    */
839   for (i = 0; i < n_symbols; i++)
840     {
841       json_scanner_scope_add_symbol (scanner, 0,
842                                      symbol_names + symbols[i].name_offset,
843                                      GINT_TO_POINTER (symbols[i].token));
844     }
845
846   return scanner;
847 }
848
849 /**
850  * json_parser_new:
851  * 
852  * Creates a new #JsonParser instance. You can use the #JsonParser to
853  * load a JSON stream from either a file or a buffer and then walk the
854  * hierarchy using the data types API.
855  *
856  * Return value: the newly created #JsonParser. Use g_object_unref()
857  *   to release all the memory it allocates.
858  */
859 JsonParser *
860 json_parser_new (void)
861 {
862   return g_object_new (JSON_TYPE_PARSER, NULL);
863 }
864
865 static gboolean
866 json_parser_load (JsonParser   *parser,
867                   const gchar  *data,
868                   gsize         length,
869                   GError      **error)
870 {
871   JsonParserPrivate *priv = parser->priv;
872   JsonScanner *scanner;
873   gboolean done;
874   gboolean retval = TRUE;
875   gint i;
876
877   json_parser_clear (parser);
878
879   if (!g_utf8_validate (data, length, NULL))
880     {
881       g_set_error_literal (error, JSON_PARSER_ERROR,
882                            JSON_PARSER_ERROR_INVALID_DATA,
883                            _("JSON data must be UTF-8 encoded"));
884       g_signal_emit (parser, parser_signals[ERROR], 0, *error);
885       return FALSE;
886     }
887
888   scanner = json_scanner_create (parser);
889   json_scanner_input_text (scanner, data, length);
890
891   priv->scanner = scanner;
892
893   g_signal_emit (parser, parser_signals[PARSE_START], 0);
894
895   done = FALSE;
896   while (!done)
897     {
898       if (json_scanner_peek_next_token (scanner) == G_TOKEN_EOF)
899         done = TRUE;
900       else
901         {
902           guint expected_token;
903           gint cur_token;
904
905           /* we try to show the expected token, if possible */
906           expected_token = json_parse_statement (parser, scanner);
907           if (expected_token != G_TOKEN_NONE)
908             {
909               const gchar *symbol_name;
910               gchar *msg;
911
912               cur_token = scanner->token;
913               msg = NULL;
914               symbol_name = NULL;
915
916               if (scanner->scope_id == 0)
917                 {
918                   if (expected_token > JSON_TOKEN_INVALID &&
919                       expected_token < JSON_TOKEN_LAST)
920                     {
921                       for (i = 0; i < n_symbols; i++)
922                         if (symbols[i].token == expected_token)
923                           symbol_name = symbol_names + symbols[i].name_offset;
924
925                       if (!msg)
926                         msg = g_strconcat ("e.g. '", symbol_name, "'", NULL);
927                     }
928
929                   if (cur_token > JSON_TOKEN_INVALID &&
930                       cur_token < JSON_TOKEN_LAST)
931                     {
932                       symbol_name = "???";
933
934                       for (i = 0; i < n_symbols; i++)
935                         if (symbols[i].token == cur_token)
936                           symbol_name = symbol_names + symbols[i].name_offset;
937                     }
938                 }
939
940               /* this will emit the ::error signal via the custom
941                * message handler we install
942                */
943               json_scanner_unexp_token (scanner, expected_token,
944                                         NULL, "value",
945                                         symbol_name, msg);
946
947               /* and this will propagate the error we create in the
948                * same message handler
949                */
950               if (priv->last_error)
951                 {
952                   g_propagate_error (error, priv->last_error);
953                   priv->last_error = NULL;
954                 }
955
956               retval = FALSE;
957
958               g_free (msg);
959               done = TRUE;
960             }
961         }
962     }
963
964   g_signal_emit (parser, parser_signals[PARSE_END], 0);
965
966   /* remove the scanner */
967   json_scanner_destroy (scanner);
968   priv->scanner = NULL;
969   priv->current_node = NULL;
970
971   return retval;
972 }
973
974 /**
975  * json_parser_load_from_file:
976  * @parser: a #JsonParser
977  * @filename: the path for the file to parse
978  * @error: return location for a #GError, or %NULL
979  *
980  * Loads a JSON stream from the content of @filename and parses it. See
981  * json_parser_load_from_data().
982  *
983  * Return value: %TRUE if the file was successfully loaded and parsed.
984  *   In case of error, @error is set accordingly and %FALSE is returned
985  */
986 gboolean
987 json_parser_load_from_file (JsonParser   *parser,
988                             const gchar  *filename,
989                             GError      **error)
990 {
991   JsonParserPrivate *priv;
992   GError *internal_error;
993   gchar *data;
994   gsize length;
995   gboolean retval = TRUE;
996
997   g_return_val_if_fail (JSON_IS_PARSER (parser), FALSE);
998   g_return_val_if_fail (filename != NULL, FALSE);
999
1000   priv = parser->priv;
1001
1002   internal_error = NULL;
1003   if (!g_file_get_contents (filename, &data, &length, &internal_error))
1004     {
1005       g_propagate_error (error, internal_error);
1006       return FALSE;
1007     }
1008
1009   g_free (priv->filename);
1010
1011   priv->is_filename = TRUE;
1012   priv->filename = g_strdup (filename);
1013
1014   if (!json_parser_load (parser, data, length, &internal_error))
1015     {
1016       g_propagate_error (error, internal_error);
1017       retval = FALSE;
1018     }
1019
1020   g_free (data);
1021
1022   return retval;
1023 }
1024
1025 /**
1026  * json_parser_load_from_data:
1027  * @parser: a #JsonParser
1028  * @data: the buffer to parse
1029  * @length: the length of the buffer, or -1
1030  * @error: return location for a #GError, or %NULL
1031  *
1032  * Loads a JSON stream from a buffer and parses it. You can call this function
1033  * multiple times with the same #JsonParser object, but the contents of the
1034  * parser will be destroyed each time.
1035  *
1036  * Return value: %TRUE if the buffer was succesfully parser. In case
1037  *   of error, @error is set accordingly and %FALSE is returned
1038  */
1039 gboolean
1040 json_parser_load_from_data (JsonParser   *parser,
1041                             const gchar  *data,
1042                             gssize        length,
1043                             GError      **error)
1044 {
1045   JsonParserPrivate *priv;
1046   GError *internal_error;
1047   gboolean retval = TRUE;
1048
1049   g_return_val_if_fail (JSON_IS_PARSER (parser), FALSE);
1050   g_return_val_if_fail (data != NULL, FALSE);
1051
1052   priv = parser->priv;
1053
1054   if (length < 0)
1055     length = strlen (data);
1056
1057   priv->is_filename = FALSE;
1058   g_free (priv->filename);
1059   priv->filename = NULL;
1060
1061   internal_error = NULL;
1062   if (!json_parser_load (parser, data, length, &internal_error))
1063     {
1064       g_propagate_error (error, internal_error);
1065       retval = FALSE;
1066     }
1067
1068   return retval;
1069 }
1070
1071 /**
1072  * json_parser_get_root:
1073  * @parser: a #JsonParser
1074  *
1075  * Retrieves the top level node from the parsed JSON stream.
1076  *
1077  * Return value: (transfer none): the root #JsonNode . The returned
1078  *   node is owned by the #JsonParser and should never be modified
1079  *   or freed.
1080  */
1081 JsonNode *
1082 json_parser_get_root (JsonParser *parser)
1083 {
1084   g_return_val_if_fail (JSON_IS_PARSER (parser), NULL);
1085
1086   return parser->priv->root;
1087 }
1088
1089 /**
1090  * json_parser_get_current_line:
1091  * @parser: a #JsonParser
1092  *
1093  * Retrieves the line currently parsed, starting from 1.
1094  *
1095  * This function has defined behaviour only while parsing; calling this
1096  * function from outside the signal handlers emitted by #JsonParser will
1097  * yield 0.
1098  *
1099  * Return value: the currently parsed line, or 0.
1100  */
1101 guint
1102 json_parser_get_current_line (JsonParser *parser)
1103 {
1104   g_return_val_if_fail (JSON_IS_PARSER (parser), 0);
1105
1106   if (parser->priv->scanner != NULL)
1107     return parser->priv->scanner->line;
1108
1109   return 0;
1110 }
1111
1112 /**
1113  * json_parser_get_current_pos:
1114  * @parser: a #JsonParser
1115  *
1116  * Retrieves the current position inside the current line, starting
1117  * from 0.
1118  *
1119  * This function has defined behaviour only while parsing; calling this
1120  * function from outside the signal handlers emitted by #JsonParser will
1121  * yield 0.
1122  *
1123  * Return value: the position in the current line, or 0.
1124  */
1125 guint
1126 json_parser_get_current_pos (JsonParser *parser)
1127 {
1128   g_return_val_if_fail (JSON_IS_PARSER (parser), 0);
1129
1130   if (parser->priv->scanner != NULL)
1131     return parser->priv->scanner->position;
1132
1133   return 0;
1134 }
1135
1136 /**
1137  * json_parser_has_assignment:
1138  * @parser: a #JsonParser
1139  * @variable_name: (out) (allow-none) (transfer none): Return location for the variable
1140  *   name, or %NULL
1141  *
1142  * A JSON data stream might sometimes contain an assignment, like:
1143  *
1144  * |[
1145  *   var _json_data = { "member_name" : [ ...
1146  * ]|
1147  *
1148  * even though it would technically constitute a violation of the RFC.
1149  *
1150  * #JsonParser will ignore the left hand identifier and parse the right
1151  * hand value of the assignment. #JsonParser will record, though, the
1152  * existence of the assignment in the data stream and the variable name
1153  * used.
1154  *
1155  * Return value: %TRUE if there was an assignment, %FALSE otherwise. If
1156  *   @variable_name is not %NULL it will be set to the name of the variable
1157  *   used in the assignment. The string is owned by #JsonParser and should
1158  *   never be modified or freed.
1159  *
1160  * Since: 0.4
1161  */
1162 gboolean
1163 json_parser_has_assignment (JsonParser  *parser,
1164                             gchar      **variable_name)
1165 {
1166   JsonParserPrivate *priv;
1167
1168   g_return_val_if_fail (JSON_IS_PARSER (parser), FALSE);
1169
1170   priv = parser->priv;
1171
1172   if (priv->has_assignment && variable_name)
1173     *variable_name = priv->variable_name;
1174
1175   return priv->has_assignment;
1176 }
1177
1178 #define GET_DATA_BLOCK_SIZE     8192
1179
1180 /**
1181  * json_parser_load_from_stream:
1182  * @parser: a #JsonParser
1183  * @stream: an open #GInputStream
1184  * @cancellable: (allow-none): a #GCancellable, or %NULL
1185  * @error: the return location for a #GError, or %NULL
1186  *
1187  * Loads the contents of an input stream and parses them.
1188  *
1189  * If @cancellable is not %NULL, then the operation can be cancelled by
1190  * triggering the @cancellable object from another thread. If the
1191  * operation was cancelled, the error %G_IO_ERROR_CANCELLED will be set
1192  * on the passed @error.
1193  *
1194  * Return value: %TRUE if the data stream was successfully read and
1195  *   parsed, and %FALSE otherwise
1196  *
1197  * Since: 0.12
1198  */
1199 gboolean
1200 json_parser_load_from_stream (JsonParser    *parser,
1201                               GInputStream  *stream,
1202                               GCancellable  *cancellable,
1203                               GError       **error)
1204 {
1205   GByteArray *content;
1206   gsize pos;
1207   gssize res;
1208   gboolean retval = FALSE;
1209   GError *internal_error;
1210
1211   g_return_val_if_fail (JSON_IS_PARSER (parser), FALSE);
1212   g_return_val_if_fail (G_IS_INPUT_STREAM (stream), FALSE);
1213   g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), FALSE);
1214
1215   if (g_cancellable_set_error_if_cancelled (cancellable, error))
1216     return FALSE;
1217
1218   content = g_byte_array_new ();
1219   pos = 0;
1220
1221   g_byte_array_set_size (content, pos + GET_DATA_BLOCK_SIZE + 1);
1222   while ((res = g_input_stream_read (stream, content->data + pos,
1223                                      GET_DATA_BLOCK_SIZE,
1224                                      cancellable, error)) > 0)
1225     {
1226       pos += res;
1227       g_byte_array_set_size (content, pos + GET_DATA_BLOCK_SIZE + 1);
1228     }
1229
1230   if (res < 0)
1231     {
1232       /* error has already been set */
1233       retval = FALSE;
1234       goto out;
1235     }
1236
1237   /* zero-terminate the content; we allocated an extra byte for this */
1238   content->data[pos] = 0;
1239
1240   internal_error = NULL;
1241   retval = json_parser_load (parser, (const gchar *) content->data, pos, &internal_error);
1242
1243   if (internal_error != NULL)
1244     g_propagate_error (error, internal_error);
1245
1246 out:
1247   g_byte_array_free (content, TRUE);
1248
1249   return retval;
1250 }
1251
1252 typedef struct _LoadStreamData
1253 {
1254   JsonParser *parser;
1255   GError *error;
1256   GCancellable *cancellable;
1257   GAsyncReadyCallback callback;
1258   gpointer user_data;
1259   GByteArray *content;
1260   gsize pos;
1261 } LoadStreamData;
1262
1263 static void
1264 load_stream_data_free (gpointer data)
1265 {
1266   LoadStreamData *closure;
1267
1268   if (G_UNLIKELY (data == NULL))
1269     return;
1270
1271   closure = data;
1272
1273   if (closure->error)
1274     g_error_free (closure->error);
1275
1276   if (closure->cancellable)
1277     g_object_unref (closure->cancellable);
1278
1279   if (closure->content)
1280     g_byte_array_free (closure->content, TRUE);
1281
1282   g_object_unref (closure->parser);
1283
1284   g_free (closure);
1285 }
1286
1287 static void
1288 load_stream_data_read_callback (GObject      *object,
1289                                 GAsyncResult *read_res,
1290                                 gpointer      user_data)
1291 {
1292   GInputStream *stream = G_INPUT_STREAM (object);
1293   LoadStreamData *data = user_data;
1294   GError *error = NULL;
1295   gssize read_size;
1296
1297   read_size = g_input_stream_read_finish (stream, read_res, &error);
1298   if (read_size < 0)
1299     {
1300       if (error != NULL)
1301         data->error = error;
1302       else
1303         {
1304           GSimpleAsyncResult *res;
1305
1306           /* EOF */
1307           res = g_simple_async_result_new (G_OBJECT (data->parser),
1308                                            data->callback,
1309                                            data->user_data,
1310                                            json_parser_load_from_stream_async);
1311           g_simple_async_result_set_op_res_gpointer (res, data, load_stream_data_free);
1312           g_simple_async_result_complete (res);
1313           g_object_unref (res);
1314         }
1315     }
1316   else if (read_size > 0)
1317     {
1318       data->pos += read_size;
1319
1320       g_byte_array_set_size (data->content, data->pos + GET_DATA_BLOCK_SIZE);
1321
1322       g_input_stream_read_async (stream, data->content->data + data->pos,
1323                                  GET_DATA_BLOCK_SIZE,
1324                                  0,
1325                                  data->cancellable,
1326                                  load_stream_data_read_callback,
1327                                  data);
1328     }
1329   else
1330     {
1331       GSimpleAsyncResult *res;
1332
1333       res = g_simple_async_result_new (G_OBJECT (data->parser),
1334                                        data->callback,
1335                                        data->user_data,
1336                                        json_parser_load_from_stream_async);
1337       g_simple_async_result_set_op_res_gpointer (res, data, load_stream_data_free);
1338       g_simple_async_result_complete (res);
1339       g_object_unref (res);
1340     }
1341 }
1342
1343 /**
1344  * json_parser_load_from_stream_finish:
1345  * @parser: a #JsonParser
1346  * @result: a #GAsyncResult
1347  * @error: the return location for a #GError or %NULL
1348  *
1349  * Finishes an asynchronous stream loading started with
1350  * json_parser_load_from_stream_async().
1351  *
1352  * Return value: %TRUE if the content of the stream was successfully retrieves
1353  *   and parsed, and %FALSE otherwise. In case of error, the #GError will be
1354  *   filled accordingly.
1355  *
1356  * Since: 0.12
1357  */
1358 gboolean
1359 json_parser_load_from_stream_finish (JsonParser    *parser,
1360                                      GAsyncResult  *result,
1361                                      GError       **error)
1362 {
1363   GSimpleAsyncResult *simple;
1364   GError *internal_error;
1365   LoadStreamData *data;
1366   gboolean res;
1367
1368   g_return_val_if_fail (JSON_IS_PARSER (parser), FALSE);
1369   g_return_val_if_fail (G_IS_SIMPLE_ASYNC_RESULT (result), FALSE);
1370
1371   simple = G_SIMPLE_ASYNC_RESULT (result);
1372
1373   if (g_simple_async_result_propagate_error (simple, error))
1374     return FALSE;
1375
1376   g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == json_parser_load_from_stream_async);
1377
1378   data = g_simple_async_result_get_op_res_gpointer (simple);
1379
1380   if (data->error)
1381     {
1382       g_propagate_error (error, data->error);
1383       data->error = NULL;
1384       return FALSE;
1385     }
1386
1387   g_byte_array_set_size (data->content, data->pos + 1);
1388   data->content->data[data->pos] = 0;
1389
1390   internal_error = NULL;
1391   res = json_parser_load (parser, (const gchar *) data->content->data, data->pos, &internal_error);
1392
1393   if (internal_error != NULL)
1394     g_propagate_error (error, internal_error);
1395
1396   return res;
1397 }
1398
1399 /**
1400  * json_parser_load_from_stream_async:
1401  * @parser: a #JsonParser
1402  * @stream: a #GInputStream
1403  * @cancellable: (allow-none): a #GCancellable, or %NULL
1404  * @callback: a #GAsyncReadyCallback to call when the request is satisfied
1405  * @user_data: the data to pass to @callback
1406  *
1407  * Asynchronously reads the contents of @stream.
1408  *
1409  * For more details, see json_parser_load_from_stream() which is the
1410  * synchronous version of this call.
1411  *
1412  * When the operation is finished, @callback will be called. You should
1413  * then call json_parser_load_from_stream_finish() to get the result
1414  * of the operation.
1415  *
1416  * Since: 0.12
1417  */
1418 void
1419 json_parser_load_from_stream_async (JsonParser          *parser,
1420                                     GInputStream        *stream,
1421                                     GCancellable        *cancellable,
1422                                     GAsyncReadyCallback  callback,
1423                                     gpointer             user_data)
1424 {
1425   LoadStreamData *data;
1426
1427   g_return_if_fail (JSON_IS_PARSER (parser));
1428   g_return_if_fail (G_IS_INPUT_STREAM (stream));
1429   g_return_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable));
1430
1431   data = g_new0 (LoadStreamData, 1);
1432
1433   if (cancellable != NULL)
1434     data->cancellable = g_object_ref (cancellable);
1435
1436   data->callback = callback;
1437   data->user_data = user_data;
1438   data->content = g_byte_array_new ();
1439   data->parser = g_object_ref (parser);
1440
1441   g_byte_array_set_size (data->content, data->pos + GET_DATA_BLOCK_SIZE);
1442   g_input_stream_read_async (stream, data->content->data + data->pos,
1443                              GET_DATA_BLOCK_SIZE, 0,
1444                              data->cancellable,
1445                              load_stream_data_read_callback,
1446                              data);
1447 }