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