Updated POTFILES.in
[platform/upstream/glib.git] / glib / gvariant-parser.c
1 /*
2  * Copyright © 2009, 2010 Codethink Limited
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2 of the licence, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with this library; if not, write to the
16  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17  * Boston, MA 02111-1307, USA.
18  *
19  * Author: Ryan Lortie <desrt@desrt.ca>
20  */
21
22 #include "config.h"
23
24 #include <stdlib.h>
25 #include <string.h>
26 #include <errno.h>
27
28 #include "gerror.h"
29 #include "gquark.h"
30 #include "gstring.h"
31 #include "gstrfuncs.h"
32 #include "gtestutils.h"
33 #include "gvariant.h"
34 #include "gvarianttype.h"
35 #include "gslice.h"
36 #include "gthread.h"
37
38 /*
39  * two-pass algorithm
40  * designed by ryan lortie and william hua
41  * designed in itb-229 and at ghazi's, 2009.
42  */
43
44 /**
45  * G_VARIANT_PARSE_ERROR:
46  *
47  * Error domain for GVariant text format parsing.  Specific error codes
48  * are not currently defined for this domain.  See #GError for
49  * information on error domains.
50  **/
51 /**
52  * GVariantParseError:
53  * @G_VARIANT_PARSE_ERROR_FAILED: generic error (unused)
54  * @G_VARIANT_PARSE_ERROR_BASIC_TYPE_EXPECTED: a non-basic #GVariantType was given where a basic type was expected
55  * @G_VARIANT_PARSE_ERROR_CANNOT_INFER_TYPE: cannot infer the #GVariantType
56  * @G_VARIANT_PARSE_ERROR_DEFINITE_TYPE_EXPECTED: an indefinite #GVariantType was given where a definite type was expected
57  * @G_VARIANT_PARSE_ERROR_INPUT_NOT_AT_END: extra data after parsing finished
58  * @G_VARIANT_PARSE_ERROR_INVALID_CHARACTER: invalid character in number or unicode escape
59  * @G_VARIANT_PARSE_ERROR_INVALID_FORMAT_STRING: not a valid #GVariant format string
60  * @G_VARIANT_PARSE_ERROR_INVALID_OBJECT_PATH: not a valid object path
61  * @G_VARIANT_PARSE_ERROR_INVALID_SIGNATURE: not a valid type signature
62  * @G_VARIANT_PARSE_ERROR_INVALID_TYPE_STRING: not a valid #GVariant type string
63  * @G_VARIANT_PARSE_ERROR_NO_COMMON_TYPE: could not find a common type for array entries
64  * @G_VARIANT_PARSE_ERROR_NUMBER_OUT_OF_RANGE: the numerical value is out of range of the given type
65  * @G_VARIANT_PARSE_ERROR_NUMBER_TOO_BIG: the numerical value is out of range for any type
66  * @G_VARIANT_PARSE_ERROR_TYPE_ERROR: cannot parse as variant of the specified type
67  * @G_VARIANT_PARSE_ERROR_UNEXPECTED_TOKEN: an unexpected token was encountered
68  * @G_VARIANT_PARSE_ERROR_UNKNOWN_KEYWORD: an unknown keyword was encountered
69  * @G_VARIANT_PARSE_ERROR_UNTERMINATED_STRING_CONSTANT: unterminated string constant
70  * @G_VARIANT_PARSE_ERROR_VALUE_EXPECTED: no value given
71  *
72  * Error codes returned by parsing text-format GVariants.
73  **/
74 G_DEFINE_QUARK (g-variant-parse-error-quark, g_variant_parser_get_error)
75
76 typedef struct
77 {
78   gint start, end;
79 } SourceRef;
80
81 static void
82 parser_set_error_va (GError      **error,
83                      SourceRef    *location,
84                      SourceRef    *other,
85                      gint          code,
86                      const gchar  *format,
87                      va_list       ap)
88 {
89   GString *msg = g_string_new (NULL);
90
91   if (location->start == location->end)
92     g_string_append_printf (msg, "%d", location->start);
93   else
94     g_string_append_printf (msg, "%d-%d", location->start, location->end);
95
96   if (other != NULL)
97     {
98       g_assert (other->start != other->end);
99       g_string_append_printf (msg, ",%d-%d", other->start, other->end);
100     }
101   g_string_append_c (msg, ':');
102
103   g_string_append_vprintf (msg, format, ap);
104   g_set_error_literal (error, G_VARIANT_PARSE_ERROR, code, msg->str);
105   g_string_free (msg, TRUE);
106 }
107
108 static void
109 parser_set_error (GError      **error,
110                   SourceRef    *location,
111                   SourceRef    *other,
112                   gint          code,
113                   const gchar  *format,
114                   ...)
115 {
116   va_list ap;
117
118   va_start (ap, format);
119   parser_set_error_va (error, location, other, code, format, ap);
120   va_end (ap);
121 }
122
123 typedef struct
124 {
125   const gchar *start;
126   const gchar *stream;
127   const gchar *end;
128
129   const gchar *this;
130 } TokenStream;
131
132
133 static void
134 token_stream_set_error (TokenStream  *stream,
135                         GError      **error,
136                         gboolean      this_token,
137                         gint          code,
138                         const gchar  *format,
139                         ...)
140 {
141   SourceRef ref;
142   va_list ap;
143
144   ref.start = stream->this - stream->start;
145
146   if (this_token)
147     ref.end = stream->stream - stream->start;
148   else
149     ref.end = ref.start;
150
151   va_start (ap, format);
152   parser_set_error_va (error, &ref, NULL, code, format, ap);
153   va_end (ap);
154 }
155
156 static gboolean
157 token_stream_prepare (TokenStream *stream)
158 {
159   gint brackets = 0;
160   const gchar *end;
161
162   if (stream->this != NULL)
163     return TRUE;
164
165   while (stream->stream != stream->end && g_ascii_isspace (*stream->stream))
166     stream->stream++;
167
168   if (stream->stream == stream->end || *stream->stream == '\0')
169     {
170       stream->this = stream->stream;
171       return FALSE;
172     }
173
174   switch (stream->stream[0])
175     {
176     case '-': case '+': case '.': case '0': case '1': case '2':
177     case '3': case '4': case '5': case '6': case '7': case '8':
178     case '9':
179       for (end = stream->stream; end != stream->end; end++)
180         if (!g_ascii_isalnum (*end) &&
181             *end != '-' && *end != '+' && *end != '.')
182           break;
183       break;
184
185     case 'b':
186       if (stream->stream[1] == '\'' || stream->stream[1] == '"')
187         {
188           for (end = stream->stream + 2; end != stream->end; end++)
189             if (*end == stream->stream[1] || *end == '\0' ||
190                 (*end == '\\' && (++end == stream->end || *end == '\0')))
191               break;
192
193           if (end != stream->end && *end)
194             end++;
195           break;
196         }
197
198       else    /* ↓↓↓ */;
199
200     case 'a': /* 'b' */ case 'c': case 'd': case 'e': case 'f':
201     case 'g': case 'h': case 'i': case 'j': case 'k': case 'l':
202     case 'm': case 'n': case 'o': case 'p': case 'q': case 'r':
203     case 's': case 't': case 'u': case 'v': case 'w': case 'x':
204     case 'y': case 'z':
205       for (end = stream->stream; end != stream->end; end++)
206         if (!g_ascii_isalnum (*end))
207           break;
208       break;
209
210     case '\'': case '"':
211       for (end = stream->stream + 1; end != stream->end; end++)
212         if (*end == stream->stream[0] || *end == '\0' ||
213             (*end == '\\' && (++end == stream->end || *end == '\0')))
214           break;
215
216       if (end != stream->end && *end)
217         end++;
218       break;
219
220     case '@': case '%':
221       /* stop at the first space, comma, colon or unmatched bracket.
222        * deals nicely with cases like (%i, %i) or {%i: %i}.
223        */
224       for (end = stream->stream + 1;
225            end != stream->end && *end != ',' &&
226            *end != ':' && *end != '>' && !g_ascii_isspace (*end);
227            end++)
228
229         if (*end == '(' || *end == '{')
230           brackets++;
231
232         else if ((*end == ')' || *end == '}') && !brackets--)
233           break;
234
235       break;
236
237     default:
238       end = stream->stream + 1;
239       break;
240     }
241
242   stream->this = stream->stream;
243   stream->stream = end;
244
245   return TRUE;
246 }
247
248 static void
249 token_stream_next (TokenStream *stream)
250 {
251   stream->this = NULL;
252 }
253
254 static gboolean
255 token_stream_peek (TokenStream *stream,
256                    gchar        first_char)
257 {
258   if (!token_stream_prepare (stream))
259     return FALSE;
260
261   return stream->this[0] == first_char;
262 }
263
264 static gboolean
265 token_stream_peek2 (TokenStream *stream,
266                     gchar        first_char,
267                     gchar        second_char)
268 {
269   if (!token_stream_prepare (stream))
270     return FALSE;
271
272   return stream->this[0] == first_char &&
273          stream->this[1] == second_char;
274 }
275
276 static gboolean
277 token_stream_is_keyword (TokenStream *stream)
278 {
279   if (!token_stream_prepare (stream))
280     return FALSE;
281
282   return g_ascii_isalpha (stream->this[0]) &&
283          g_ascii_isalpha (stream->this[1]);
284 }
285
286 static gboolean
287 token_stream_is_numeric (TokenStream *stream)
288 {
289   if (!token_stream_prepare (stream))
290     return FALSE;
291
292   return (g_ascii_isdigit (stream->this[0]) ||
293           stream->this[0] == '-' ||
294           stream->this[0] == '+' ||
295           stream->this[0] == '.');
296 }
297
298 static gboolean
299 token_stream_peek_string (TokenStream *stream,
300                           const gchar *token)
301 {
302   gint length = strlen (token);
303
304   return token_stream_prepare (stream) &&
305          stream->stream - stream->this == length &&
306          memcmp (stream->this, token, length) == 0;
307 }
308
309 static gboolean
310 token_stream_consume (TokenStream *stream,
311                       const gchar *token)
312 {
313   if (!token_stream_peek_string (stream, token))
314     return FALSE;
315
316   token_stream_next (stream);
317   return TRUE;
318 }
319
320 static gboolean
321 token_stream_require (TokenStream  *stream,
322                       const gchar  *token,
323                       const gchar  *purpose,
324                       GError      **error)
325 {
326
327   if (!token_stream_consume (stream, token))
328     {
329       token_stream_set_error (stream, error, FALSE,
330                               G_VARIANT_PARSE_ERROR_UNEXPECTED_TOKEN,
331                               "expected `%s'%s", token, purpose);
332       return FALSE;
333     }
334
335   return TRUE;
336 }
337
338 static void
339 token_stream_assert (TokenStream *stream,
340                      const gchar *token)
341 {
342   gboolean correct_token;
343
344   correct_token = token_stream_consume (stream, token);
345   g_assert (correct_token);
346 }
347
348 static gchar *
349 token_stream_get (TokenStream *stream)
350 {
351   gchar *result;
352
353   if (!token_stream_prepare (stream))
354     return NULL;
355
356   result = g_strndup (stream->this, stream->stream - stream->this);
357
358   return result;
359 }
360
361 static void
362 token_stream_start_ref (TokenStream *stream,
363                         SourceRef   *ref)
364 {
365   token_stream_prepare (stream);
366   ref->start = stream->this - stream->start;
367 }
368
369 static void
370 token_stream_end_ref (TokenStream *stream,
371                       SourceRef   *ref)
372 {
373   ref->end = stream->stream - stream->start;
374 }
375
376 static void
377 pattern_copy (gchar       **out,
378               const gchar **in)
379 {
380   gint brackets = 0;
381
382   while (**in == 'a' || **in == 'm' || **in == 'M')
383     *(*out)++ = *(*in)++;
384
385   do
386     {
387       if (**in == '(' || **in == '{')
388         brackets++;
389
390       else if (**in == ')' || **in == '}')
391         brackets--;
392
393       *(*out)++ = *(*in)++;
394     }
395   while (brackets);
396 }
397
398 static gchar *
399 pattern_coalesce (const gchar *left,
400                   const gchar *right)
401 {
402   gchar *result;
403   gchar *out;
404
405   /* the length of the output is loosely bound by the sum of the input
406    * lengths, not simply the greater of the two lengths.
407    *
408    *   (*(iii)) + ((iii)*) ((iii)(iii))
409    *
410    *      8     +    8    =  12
411    */
412   out = result = g_malloc (strlen (left) + strlen (right));
413
414   while (*left && *right)
415     {
416       if (*left == *right)
417         {
418           *out++ = *left++;
419           right++;
420         }
421
422       else
423         {
424           const gchar **one = &left, **the_other = &right;
425
426          again:
427           if (**one == '*' && **the_other != ')')
428             {
429               pattern_copy (&out, the_other);
430               (*one)++;
431             }
432
433           else if (**one == 'M' && **the_other == 'm')
434             {
435               *out++ = *(*the_other)++;
436             }
437
438           else if (**one == 'M' && **the_other != 'm')
439             {
440               (*one)++;
441             }
442
443           else if (**one == 'N' && strchr ("ynqiuxthd", **the_other))
444             {
445               *out++ = *(*the_other)++;
446               (*one)++;
447             }
448
449           else if (**one == 'S' && strchr ("sog", **the_other))
450             {
451               *out++ = *(*the_other)++;
452               (*one)++;
453             }
454
455           else if (one == &left)
456             {
457               one = &right, the_other = &left;
458               goto again;
459             }
460
461           else
462             break;
463         }
464     }
465
466   if (*left || *right)
467     {
468       g_free (result);
469       result = NULL;
470     }
471   else
472     *out++ = '\0';
473
474   return result;
475 }
476
477 typedef struct _AST AST;
478 typedef gchar *    (*get_pattern_func)    (AST                 *ast,
479                                            GError             **error);
480 typedef GVariant * (*get_value_func)      (AST                 *ast,
481                                            const GVariantType  *type,
482                                            GError             **error);
483 typedef GVariant * (*get_base_value_func) (AST                 *ast,
484                                            const GVariantType  *type,
485                                            GError             **error);
486 typedef void       (*free_func)           (AST                 *ast);
487
488 typedef struct
489 {
490   gchar *    (* get_pattern)    (AST                 *ast,
491                                  GError             **error);
492   GVariant * (* get_value)      (AST                 *ast,
493                                  const GVariantType  *type,
494                                  GError             **error);
495   GVariant * (* get_base_value) (AST                 *ast,
496                                  const GVariantType  *type,
497                                  GError             **error);
498   void       (* free)           (AST                 *ast);
499 } ASTClass;
500
501 struct _AST
502 {
503   const ASTClass *class;
504   SourceRef source_ref;
505 };
506
507 static gchar *
508 ast_get_pattern (AST     *ast,
509                  GError **error)
510 {
511   return ast->class->get_pattern (ast, error);
512 }
513
514 static GVariant *
515 ast_get_value (AST                 *ast,
516                const GVariantType  *type,
517                GError             **error)
518 {
519   return ast->class->get_value (ast, type, error);
520 }
521
522 static void
523 ast_free (AST *ast)
524 {
525   ast->class->free (ast);
526 }
527
528 static void
529 ast_set_error (AST          *ast,
530                GError      **error,
531                AST          *other_ast,
532                gint          code,
533                const gchar  *format,
534                ...)
535 {
536   va_list ap;
537
538   va_start (ap, format);
539   parser_set_error_va (error, &ast->source_ref,
540                        other_ast ? & other_ast->source_ref : NULL,
541                        code,
542                        format, ap);
543   va_end (ap);
544 }
545
546 static GVariant *
547 ast_type_error (AST                 *ast,
548                 const GVariantType  *type,
549                 GError             **error)
550 {
551   gchar *typestr;
552
553   typestr = g_variant_type_dup_string (type);
554   ast_set_error (ast, error, NULL,
555                  G_VARIANT_PARSE_ERROR_TYPE_ERROR,
556                  "can not parse as value of type `%s'",
557                  typestr);
558   g_free (typestr);
559
560   return NULL;
561 }
562
563 static GVariant *
564 ast_resolve (AST     *ast,
565              GError **error)
566 {
567   GVariant *value;
568   gchar *pattern;
569   gint i, j = 0;
570
571   pattern = ast_get_pattern (ast, error);
572
573   if (pattern == NULL)
574     return NULL;
575
576   /* choose reasonable defaults
577    *
578    *   1) favour non-maybe values where possible
579    *   2) default type for strings is 's'
580    *   3) default type for integers is 'i'
581    */
582   for (i = 0; pattern[i]; i++)
583     switch (pattern[i])
584       {
585       case '*':
586         ast_set_error (ast, error, NULL,
587                        G_VARIANT_PARSE_ERROR_CANNOT_INFER_TYPE,
588                        "unable to infer type");
589         g_free (pattern);
590         return NULL;
591
592       case 'M':
593         break;
594
595       case 'S':
596         pattern[j++] = 's';
597         break;
598
599       case 'N':
600         pattern[j++] = 'i';
601         break;
602
603       default:
604         pattern[j++] = pattern[i];
605         break;
606       }
607   pattern[j++] = '\0';
608
609   value = ast_get_value (ast, G_VARIANT_TYPE (pattern), error);
610   g_free (pattern);
611
612   return value;
613 }
614
615
616 static AST *parse (TokenStream  *stream,
617                    va_list      *app,
618                    GError      **error);
619
620 static void
621 ast_array_append (AST  ***array,
622                   gint   *n_items,
623                   AST    *ast)
624 {
625   if ((*n_items & (*n_items - 1)) == 0)
626     *array = g_renew (AST *, *array, *n_items ? 2 ** n_items : 1);
627
628   (*array)[(*n_items)++] = ast;
629 }
630
631 static void
632 ast_array_free (AST  **array,
633                 gint   n_items)
634 {
635   gint i;
636
637   for (i = 0; i < n_items; i++)
638     ast_free (array[i]);
639   g_free (array);
640 }
641
642 static gchar *
643 ast_array_get_pattern (AST    **array,
644                        gint     n_items,
645                        GError **error)
646 {
647   gchar *pattern;
648   gint i;
649
650   pattern = ast_get_pattern (array[0], error);
651
652   if (pattern == NULL)
653     return NULL;
654
655   for (i = 1; i < n_items; i++)
656     {
657       gchar *tmp, *merged;
658
659       tmp = ast_get_pattern (array[i], error);
660
661       if (tmp == NULL)
662         {
663           g_free (pattern);
664           return NULL;
665         }
666
667       merged = pattern_coalesce (pattern, tmp);
668       g_free (pattern);
669       pattern = merged;
670
671       if (merged == NULL)
672         /* set coalescence implies pairwise coalescence (i think).
673          * we should therefore be able to trace the failure to a single
674          * pair of values.
675          */
676         {
677           int j = 0;
678
679           while (TRUE)
680             {
681               gchar *tmp2;
682               gchar *m;
683
684               /* if 'j' reaches 'i' then we failed to find the pair */
685               g_assert (j < i);
686
687               tmp2 = ast_get_pattern (array[j], NULL);
688               g_assert (tmp2 != NULL);
689
690               m = pattern_coalesce (tmp, tmp2);
691               g_free (tmp2);
692               g_free (m);
693
694               if (m == NULL)
695                 {
696                   /* we found a conflict between 'i' and 'j'.
697                    *
698                    * report the error.  note: 'j' is first.
699                    */
700                   ast_set_error (array[j], error, array[i],
701                                  G_VARIANT_PARSE_ERROR_NO_COMMON_TYPE,
702                                  "unable to find a common type");
703                   g_free (tmp);
704                   return NULL;
705                 }
706
707               j++;
708             }
709
710         }
711
712       g_free (tmp);
713     }
714
715   return pattern;
716 }
717
718 typedef struct
719 {
720   AST ast;
721
722   AST *child;
723 } Maybe;
724
725 static gchar *
726 maybe_get_pattern (AST     *ast,
727                    GError **error)
728 {
729   Maybe *maybe = (Maybe *) ast;
730
731   if (maybe->child != NULL)
732     {
733       gchar *child_pattern;
734       gchar *pattern;
735
736       child_pattern = ast_get_pattern (maybe->child, error);
737
738       if (child_pattern == NULL)
739         return NULL;
740
741       pattern = g_strdup_printf ("m%s", child_pattern);
742       g_free (child_pattern);
743
744       return pattern;
745     }
746
747   return g_strdup ("m*");
748 }
749
750 static GVariant *
751 maybe_get_value (AST                 *ast,
752                  const GVariantType  *type,
753                  GError             **error)
754 {
755   Maybe *maybe = (Maybe *) ast;
756   GVariant *value;
757
758   if (!g_variant_type_is_maybe (type))
759     return ast_type_error (ast, type, error);
760
761   type = g_variant_type_element (type);
762
763   if (maybe->child)
764     {
765       value = ast_get_value (maybe->child, type, error);
766
767       if (value == NULL)
768         return NULL;
769     }
770   else
771     value = NULL;
772
773   return g_variant_new_maybe (type, value);
774 }
775
776 static void
777 maybe_free (AST *ast)
778 {
779   Maybe *maybe = (Maybe *) ast;
780
781   if (maybe->child != NULL)
782     ast_free (maybe->child);
783
784   g_slice_free (Maybe, maybe);
785 }
786
787 static AST *
788 maybe_parse (TokenStream  *stream,
789              va_list      *app,
790              GError      **error)
791 {
792   static const ASTClass maybe_class = {
793     maybe_get_pattern,
794     maybe_get_value, NULL,
795     maybe_free
796   };
797   AST *child = NULL;
798   Maybe *maybe;
799
800   if (token_stream_consume (stream, "just"))
801     {
802       child = parse (stream, app, error);
803       if (child == NULL)
804         return NULL;
805     }
806
807   else if (!token_stream_consume (stream, "nothing"))
808     {
809       token_stream_set_error (stream, error, TRUE,
810                               G_VARIANT_PARSE_ERROR_UNKNOWN_KEYWORD,
811                               "unknown keyword");
812       return NULL;
813     }
814
815   maybe = g_slice_new (Maybe);
816   maybe->ast.class = &maybe_class;
817   maybe->child = child;
818
819   return (AST *) maybe;
820 }
821
822 static GVariant *
823 maybe_wrapper (AST                 *ast,
824                const GVariantType  *type,
825                GError             **error)
826 {
827   const GVariantType *t;
828   GVariant *value;
829   int depth;
830
831   for (depth = 0, t = type;
832        g_variant_type_is_maybe (t);
833        depth++, t = g_variant_type_element (t));
834
835   value = ast->class->get_base_value (ast, t, error);
836
837   if (value == NULL)
838     return NULL;
839
840   while (depth--)
841     value = g_variant_new_maybe (NULL, value);
842
843   return value;
844 }
845
846 typedef struct
847 {
848   AST ast;
849
850   AST **children;
851   gint n_children;
852 } Array;
853
854 static gchar *
855 array_get_pattern (AST     *ast,
856                    GError **error)
857 {
858   Array *array = (Array *) ast;
859   gchar *pattern;
860   gchar *result;
861
862   if (array->n_children == 0)
863     return g_strdup ("Ma*");
864
865   pattern = ast_array_get_pattern (array->children, array->n_children, error);
866
867   if (pattern == NULL)
868     return NULL;
869
870   result = g_strdup_printf ("Ma%s", pattern);
871   g_free (pattern);
872
873   return result;
874 }
875
876 static GVariant *
877 array_get_value (AST                 *ast,
878                  const GVariantType  *type,
879                  GError             **error)
880 {
881   Array *array = (Array *) ast;
882   const GVariantType *childtype;
883   GVariantBuilder builder;
884   gint i;
885
886   if (!g_variant_type_is_array (type))
887     return ast_type_error (ast, type, error);
888
889   g_variant_builder_init (&builder, type);
890   childtype = g_variant_type_element (type);
891
892   for (i = 0; i < array->n_children; i++)
893     {
894       GVariant *child;
895
896       if (!(child = ast_get_value (array->children[i], childtype, error)))
897         {
898           g_variant_builder_clear (&builder);
899           return NULL;
900         }
901
902       g_variant_builder_add_value (&builder, child);
903     }
904
905   return g_variant_builder_end (&builder);
906 }
907
908 static void
909 array_free (AST *ast)
910 {
911   Array *array = (Array *) ast;
912
913   ast_array_free (array->children, array->n_children);
914   g_slice_free (Array, array);
915 }
916
917 static AST *
918 array_parse (TokenStream  *stream,
919              va_list      *app,
920              GError      **error)
921 {
922   static const ASTClass array_class = {
923     array_get_pattern,
924     maybe_wrapper, array_get_value,
925     array_free
926   };
927   gboolean need_comma = FALSE;
928   Array *array;
929
930   array = g_slice_new (Array);
931   array->ast.class = &array_class;
932   array->children = NULL;
933   array->n_children = 0;
934
935   token_stream_assert (stream, "[");
936   while (!token_stream_consume (stream, "]"))
937     {
938       AST *child;
939
940       if (need_comma &&
941           !token_stream_require (stream, ",",
942                                  " or `]' to follow array element",
943                                  error))
944         goto error;
945
946       child = parse (stream, app, error);
947
948       if (!child)
949         goto error;
950
951       ast_array_append (&array->children, &array->n_children, child);
952       need_comma = TRUE;
953     }
954
955   return (AST *) array;
956
957  error:
958   ast_array_free (array->children, array->n_children);
959   g_slice_free (Array, array);
960
961   return NULL;
962 }
963
964 typedef struct
965 {
966   AST ast;
967
968   AST **children;
969   gint n_children;
970 } Tuple;
971
972 static gchar *
973 tuple_get_pattern (AST     *ast,
974                    GError **error)
975 {
976   Tuple *tuple = (Tuple *) ast;
977   gchar *result = NULL;
978   gchar **parts;
979   gint i;
980
981   parts = g_new (gchar *, tuple->n_children + 4);
982   parts[tuple->n_children + 1] = (gchar *) ")";
983   parts[tuple->n_children + 2] = NULL;
984   parts[0] = (gchar *) "M(";
985
986   for (i = 0; i < tuple->n_children; i++)
987     if (!(parts[i + 1] = ast_get_pattern (tuple->children[i], error)))
988       break;
989
990   if (i == tuple->n_children)
991     result = g_strjoinv ("", parts);
992
993   /* parts[0] should not be freed */
994   while (i)
995     g_free (parts[i--]);
996   g_free (parts);
997
998   return result;
999 }
1000
1001 static GVariant *
1002 tuple_get_value (AST                 *ast,
1003                  const GVariantType  *type,
1004                  GError             **error)
1005 {
1006   Tuple *tuple = (Tuple *) ast;
1007   const GVariantType *childtype;
1008   GVariantBuilder builder;
1009   gint i;
1010
1011   if (!g_variant_type_is_tuple (type))
1012     return ast_type_error (ast, type, error);
1013
1014   g_variant_builder_init (&builder, type);
1015   childtype = g_variant_type_first (type);
1016
1017   for (i = 0; i < tuple->n_children; i++)
1018     {
1019       GVariant *child;
1020
1021       if (childtype == NULL)
1022         {
1023           g_variant_builder_clear (&builder);
1024           return ast_type_error (ast, type, error);
1025         }
1026
1027       if (!(child = ast_get_value (tuple->children[i], childtype, error)))
1028         {
1029           g_variant_builder_clear (&builder);
1030           return FALSE;
1031         }
1032
1033       g_variant_builder_add_value (&builder, child);
1034       childtype = g_variant_type_next (childtype);
1035     }
1036
1037   if (childtype != NULL)
1038     {
1039       g_variant_builder_clear (&builder);
1040       return ast_type_error (ast, type, error);
1041     }
1042
1043   return g_variant_builder_end (&builder);
1044 }
1045
1046 static void
1047 tuple_free (AST *ast)
1048 {
1049   Tuple *tuple = (Tuple *) ast;
1050
1051   ast_array_free (tuple->children, tuple->n_children);
1052   g_slice_free (Tuple, tuple);
1053 }
1054
1055 static AST *
1056 tuple_parse (TokenStream  *stream,
1057              va_list      *app,
1058              GError      **error)
1059 {
1060   static const ASTClass tuple_class = {
1061     tuple_get_pattern,
1062     maybe_wrapper, tuple_get_value,
1063     tuple_free
1064   };
1065   gboolean need_comma = FALSE;
1066   gboolean first = TRUE;
1067   Tuple *tuple;
1068
1069   tuple = g_slice_new (Tuple);
1070   tuple->ast.class = &tuple_class;
1071   tuple->children = NULL;
1072   tuple->n_children = 0;
1073
1074   token_stream_assert (stream, "(");
1075   while (!token_stream_consume (stream, ")"))
1076     {
1077       AST *child;
1078
1079       if (need_comma &&
1080           !token_stream_require (stream, ",",
1081                                  " or `)' to follow tuple element",
1082                                  error))
1083         goto error;
1084
1085       child = parse (stream, app, error);
1086
1087       if (!child)
1088         goto error;
1089
1090       ast_array_append (&tuple->children, &tuple->n_children, child);
1091
1092       /* the first time, we absolutely require a comma, so grab it here
1093        * and leave need_comma = FALSE so that the code above doesn't
1094        * require a second comma.
1095        *
1096        * the second and remaining times, we set need_comma = TRUE.
1097        */
1098       if (first)
1099         {
1100           if (!token_stream_require (stream, ",",
1101                                      " after first tuple element", error))
1102             goto error;
1103
1104           first = FALSE;
1105         }
1106       else
1107         need_comma = TRUE;
1108     }
1109
1110   return (AST *) tuple;
1111
1112  error:
1113   ast_array_free (tuple->children, tuple->n_children);
1114   g_slice_free (Tuple, tuple);
1115
1116   return NULL;
1117 }
1118
1119 typedef struct
1120 {
1121   AST ast;
1122
1123   AST *value;
1124 } Variant;
1125
1126 static gchar *
1127 variant_get_pattern (AST     *ast,
1128                      GError **error)
1129 {
1130   return g_strdup ("Mv");
1131 }
1132
1133 static GVariant *
1134 variant_get_value (AST                 *ast,
1135                    const GVariantType  *type,
1136                    GError             **error)
1137 {
1138   Variant *variant = (Variant *) ast;
1139   GVariant *child;
1140
1141   g_assert (g_variant_type_equal (type, G_VARIANT_TYPE_VARIANT));
1142   child = ast_resolve (variant->value, error);
1143
1144   if (child == NULL)
1145     return NULL;
1146
1147   return g_variant_new_variant (child);
1148 }
1149
1150 static void
1151 variant_free (AST *ast)
1152 {
1153   Variant *variant = (Variant *) ast;
1154
1155   ast_free (variant->value);
1156   g_slice_free (Variant, variant);
1157 }
1158
1159 static AST *
1160 variant_parse (TokenStream  *stream,
1161                va_list      *app,
1162                GError      **error)
1163 {
1164   static const ASTClass variant_class = {
1165     variant_get_pattern,
1166     maybe_wrapper, variant_get_value,
1167     variant_free
1168   };
1169   Variant *variant;
1170   AST *value;
1171
1172   token_stream_assert (stream, "<");
1173   value = parse (stream, app, error);
1174
1175   if (!value)
1176     return NULL;
1177
1178   if (!token_stream_require (stream, ">", " to follow variant value", error))
1179     {
1180       ast_free (value);
1181       return NULL;
1182     }
1183
1184   variant = g_slice_new (Variant);
1185   variant->ast.class = &variant_class;
1186   variant->value = value;
1187
1188   return (AST *) variant;
1189 }
1190
1191 typedef struct
1192 {
1193   AST ast;
1194
1195   AST **keys;
1196   AST **values;
1197   gint n_children;
1198 } Dictionary;
1199
1200 static gchar *
1201 dictionary_get_pattern (AST     *ast,
1202                         GError **error)
1203 {
1204   Dictionary *dict = (Dictionary *) ast;
1205   gchar *value_pattern;
1206   gchar *key_pattern;
1207   gchar key_char;
1208   gchar *result;
1209
1210   if (dict->n_children == 0)
1211     return g_strdup ("Ma{**}");
1212
1213   key_pattern = ast_array_get_pattern (dict->keys,
1214                                        abs (dict->n_children),
1215                                        error);
1216
1217   if (key_pattern == NULL)
1218     return NULL;
1219
1220   /* we can not have maybe keys */
1221   if (key_pattern[0] == 'M')
1222     key_char = key_pattern[1];
1223   else
1224     key_char = key_pattern[0];
1225
1226   g_free (key_pattern);
1227
1228   /* the basic types,
1229    * plus undetermined number type and undetermined string type.
1230    */
1231   if (!strchr ("bynqiuxthdsogNS", key_char))
1232     {
1233       ast_set_error (ast, error, NULL,
1234                      G_VARIANT_PARSE_ERROR_BASIC_TYPE_EXPECTED,
1235                      "dictionary keys must have basic types");
1236       return NULL;
1237     }
1238
1239   value_pattern = ast_get_pattern (dict->values[0], error);
1240
1241   if (value_pattern == NULL)
1242     return NULL;
1243
1244   result = g_strdup_printf ("M%s{%c%s}",
1245                             dict->n_children > 0 ? "a" : "",
1246                             key_char, value_pattern);
1247   g_free (value_pattern);
1248
1249   return result;
1250 }
1251
1252 static GVariant *
1253 dictionary_get_value (AST                 *ast,
1254                       const GVariantType  *type,
1255                       GError             **error)
1256 {
1257   Dictionary *dict = (Dictionary *) ast;
1258
1259   if (dict->n_children == -1)
1260     {
1261       const GVariantType *subtype;
1262       GVariantBuilder builder;
1263       GVariant *subvalue;
1264
1265       if (!g_variant_type_is_dict_entry (type))
1266         return ast_type_error (ast, type, error);
1267
1268       g_variant_builder_init (&builder, type);
1269
1270       subtype = g_variant_type_key (type);
1271       if (!(subvalue = ast_get_value (dict->keys[0], subtype, error)))
1272         {
1273           g_variant_builder_clear (&builder);
1274           return NULL;
1275         }
1276       g_variant_builder_add_value (&builder, subvalue);
1277
1278       subtype = g_variant_type_value (type);
1279       if (!(subvalue = ast_get_value (dict->values[0], subtype, error)))
1280         {
1281           g_variant_builder_clear (&builder);
1282           return NULL;
1283         }
1284       g_variant_builder_add_value (&builder, subvalue);
1285
1286       return g_variant_builder_end (&builder);
1287     }
1288   else
1289     {
1290       const GVariantType *entry, *key, *val;
1291       GVariantBuilder builder;
1292       gint i;
1293
1294       if (!g_variant_type_is_subtype_of (type, G_VARIANT_TYPE_DICTIONARY))
1295         return ast_type_error (ast, type, error);
1296
1297       entry = g_variant_type_element (type);
1298       key = g_variant_type_key (entry);
1299       val = g_variant_type_value (entry);
1300
1301       g_variant_builder_init (&builder, type);
1302
1303       for (i = 0; i < dict->n_children; i++)
1304         {
1305           GVariant *subvalue;
1306
1307           g_variant_builder_open (&builder, entry);
1308
1309           if (!(subvalue = ast_get_value (dict->keys[i], key, error)))
1310             {
1311               g_variant_builder_clear (&builder);
1312               return NULL;
1313             }
1314           g_variant_builder_add_value (&builder, subvalue);
1315
1316           if (!(subvalue = ast_get_value (dict->values[i], val, error)))
1317             {
1318               g_variant_builder_clear (&builder);
1319               return NULL;
1320             }
1321           g_variant_builder_add_value (&builder, subvalue);
1322           g_variant_builder_close (&builder);
1323         }
1324
1325       return g_variant_builder_end (&builder);
1326     }
1327 }
1328
1329 static void
1330 dictionary_free (AST *ast)
1331 {
1332   Dictionary *dict = (Dictionary *) ast;
1333   gint n_children;
1334
1335   if (dict->n_children > -1)
1336     n_children = dict->n_children;
1337   else
1338     n_children = 1;
1339
1340   ast_array_free (dict->keys, n_children);
1341   ast_array_free (dict->values, n_children);
1342   g_slice_free (Dictionary, dict);
1343 }
1344
1345 static AST *
1346 dictionary_parse (TokenStream  *stream,
1347                   va_list      *app,
1348                   GError      **error)
1349 {
1350   static const ASTClass dictionary_class = {
1351     dictionary_get_pattern,
1352     maybe_wrapper, dictionary_get_value,
1353     dictionary_free
1354   };
1355   gint n_keys, n_values;
1356   gboolean only_one;
1357   Dictionary *dict;
1358   AST *first;
1359
1360   dict = g_slice_new (Dictionary);
1361   dict->ast.class = &dictionary_class;
1362   dict->keys = NULL;
1363   dict->values = NULL;
1364   n_keys = n_values = 0;
1365
1366   token_stream_assert (stream, "{");
1367
1368   if (token_stream_consume (stream, "}"))
1369     {
1370       dict->n_children = 0;
1371       return (AST *) dict;
1372     }
1373
1374   if ((first = parse (stream, app, error)) == NULL)
1375     goto error;
1376
1377   ast_array_append (&dict->keys, &n_keys, first);
1378
1379   only_one = token_stream_consume (stream, ",");
1380   if (!only_one &&
1381       !token_stream_require (stream, ":",
1382                              " or `,' to follow dictionary entry key",
1383                              error))
1384     goto error;
1385
1386   if ((first = parse (stream, app, error)) == NULL)
1387     goto error;
1388
1389   ast_array_append (&dict->values, &n_values, first);
1390
1391   if (only_one)
1392     {
1393       if (!token_stream_require (stream, "}", " at end of dictionary entry",
1394                                  error))
1395         goto error;
1396
1397       g_assert (n_keys == 1 && n_values == 1);
1398       dict->n_children = -1;
1399
1400       return (AST *) dict;
1401     }
1402
1403   while (!token_stream_consume (stream, "}"))
1404     {
1405       AST *child;
1406
1407       if (!token_stream_require (stream, ",",
1408                                  " or `}' to follow dictionary entry", error))
1409         goto error;
1410
1411       child = parse (stream, app, error);
1412
1413       if (!child)
1414         goto error;
1415
1416       ast_array_append (&dict->keys, &n_keys, child);
1417
1418       if (!token_stream_require (stream, ":",
1419                                  " to follow dictionary entry key", error))
1420         goto error;
1421
1422       child = parse (stream, app, error);
1423
1424       if (!child)
1425         goto error;
1426
1427       ast_array_append (&dict->values, &n_values, child);
1428     }
1429
1430   g_assert (n_keys == n_values);
1431   dict->n_children = n_keys;
1432
1433   return (AST *) dict;
1434
1435  error:
1436   ast_array_free (dict->keys, n_keys);
1437   ast_array_free (dict->values, n_values);
1438   g_slice_free (Dictionary, dict);
1439
1440   return NULL;
1441 }
1442
1443 typedef struct
1444 {
1445   AST ast;
1446   gchar *string;
1447 } String;
1448
1449 static gchar *
1450 string_get_pattern (AST     *ast,
1451                     GError **error)
1452 {
1453   return g_strdup ("MS");
1454 }
1455
1456 static GVariant *
1457 string_get_value (AST                 *ast,
1458                   const GVariantType  *type,
1459                   GError             **error)
1460 {
1461   String *string = (String *) ast;
1462
1463   if (g_variant_type_equal (type, G_VARIANT_TYPE_STRING))
1464     return g_variant_new_string (string->string);
1465
1466   else if (g_variant_type_equal (type, G_VARIANT_TYPE_OBJECT_PATH))
1467     {
1468       if (!g_variant_is_object_path (string->string))
1469         {
1470           ast_set_error (ast, error, NULL,
1471                          G_VARIANT_PARSE_ERROR_INVALID_OBJECT_PATH,
1472                          "not a valid object path");
1473           return NULL;
1474         }
1475
1476       return g_variant_new_object_path (string->string);
1477     }
1478
1479   else if (g_variant_type_equal (type, G_VARIANT_TYPE_SIGNATURE))
1480     {
1481       if (!g_variant_is_signature (string->string))
1482         {
1483           ast_set_error (ast, error, NULL,
1484                          G_VARIANT_PARSE_ERROR_INVALID_SIGNATURE,
1485                          "not a valid signature");
1486           return NULL;
1487         }
1488
1489       return g_variant_new_signature (string->string);
1490     }
1491
1492   else
1493     return ast_type_error (ast, type, error);
1494 }
1495
1496 static void
1497 string_free (AST *ast)
1498 {
1499   String *string = (String *) ast;
1500
1501   g_free (string->string);
1502   g_slice_free (String, string);
1503 }
1504
1505 static gboolean
1506 unicode_unescape (const gchar  *src,
1507                   gint         *src_ofs,
1508                   gchar        *dest,
1509                   gint         *dest_ofs,
1510                   gint          length,
1511                   SourceRef    *ref,
1512                   GError      **error)
1513 {
1514   gchar buffer[9];
1515   guint64 value;
1516   gchar *end;
1517
1518   (*src_ofs)++;
1519
1520   g_assert (length < sizeof (buffer));
1521   strncpy (buffer, src + *src_ofs, length);
1522   buffer[length] = '\0';
1523
1524   value = g_ascii_strtoull (buffer, &end, 0x10);
1525
1526   if (value == 0 || end != buffer + length)
1527     {
1528       parser_set_error (error, ref, NULL,
1529                         G_VARIANT_PARSE_ERROR_INVALID_CHARACTER,
1530                         "invalid %d-character unicode escape", length);
1531       return FALSE;
1532     }
1533
1534   g_assert (value <= G_MAXUINT32);
1535
1536   *dest_ofs += g_unichar_to_utf8 (value, dest + *dest_ofs);
1537   *src_ofs += length;
1538
1539   return TRUE;
1540 }
1541
1542 static AST *
1543 string_parse (TokenStream  *stream,
1544               va_list      *app,
1545               GError      **error)
1546 {
1547   static const ASTClass string_class = {
1548     string_get_pattern,
1549     maybe_wrapper, string_get_value,
1550     string_free
1551   };
1552   String *string;
1553   SourceRef ref;
1554   gchar *token;
1555   gsize length;
1556   gchar quote;
1557   gchar *str;
1558   gint i, j;
1559
1560   token_stream_start_ref (stream, &ref);
1561   token = token_stream_get (stream);
1562   token_stream_end_ref (stream, &ref);
1563   length = strlen (token);
1564   quote = token[0];
1565
1566   str = g_malloc (length);
1567   g_assert (quote == '"' || quote == '\'');
1568   j = 0;
1569   i = 1;
1570   while (token[i] != quote)
1571     switch (token[i])
1572       {
1573       case '\0':
1574         parser_set_error (error, &ref, NULL,
1575                           G_VARIANT_PARSE_ERROR_UNTERMINATED_STRING_CONSTANT,
1576                           "unterminated string constant");
1577         g_free (token);
1578         g_free (str);
1579         return NULL;
1580
1581       case '\\':
1582         switch (token[++i])
1583           {
1584           case '\0':
1585             parser_set_error (error, &ref, NULL,
1586                               G_VARIANT_PARSE_ERROR_UNTERMINATED_STRING_CONSTANT,
1587                               "unterminated string constant");
1588             g_free (token);
1589             g_free (str);
1590             return NULL;
1591
1592           case 'u':
1593             if (!unicode_unescape (token, &i, str, &j, 4, &ref, error))
1594               {
1595                 g_free (token);
1596                 g_free (str);
1597                 return NULL;
1598               }
1599             continue;
1600
1601           case 'U':
1602             if (!unicode_unescape (token, &i, str, &j, 8, &ref, error))
1603               {
1604                 g_free (token);
1605                 g_free (str);
1606                 return NULL;
1607               }
1608             continue;
1609
1610           case 'a': str[j++] = '\a'; i++; continue;
1611           case 'b': str[j++] = '\b'; i++; continue;
1612           case 'f': str[j++] = '\f'; i++; continue;
1613           case 'n': str[j++] = '\n'; i++; continue;
1614           case 'r': str[j++] = '\r'; i++; continue;
1615           case 't': str[j++] = '\t'; i++; continue;
1616           case 'v': str[j++] = '\v'; i++; continue;
1617           case '\n': i++; continue;
1618           }
1619
1620       default:
1621         str[j++] = token[i++];
1622       }
1623   str[j++] = '\0';
1624   g_free (token);
1625
1626   string = g_slice_new (String);
1627   string->ast.class = &string_class;
1628   string->string = str;
1629
1630   token_stream_next (stream);
1631
1632   return (AST *) string;
1633 }
1634
1635 typedef struct
1636 {
1637   AST ast;
1638   gchar *string;
1639 } ByteString;
1640
1641 static gchar *
1642 bytestring_get_pattern (AST     *ast,
1643                         GError **error)
1644 {
1645   return g_strdup ("May");
1646 }
1647
1648 static GVariant *
1649 bytestring_get_value (AST                 *ast,
1650                       const GVariantType  *type,
1651                       GError             **error)
1652 {
1653   ByteString *string = (ByteString *) ast;
1654
1655   g_assert (g_variant_type_equal (type, G_VARIANT_TYPE_BYTESTRING));
1656
1657   return g_variant_new_bytestring (string->string);
1658 }
1659
1660 static void
1661 bytestring_free (AST *ast)
1662 {
1663   ByteString *string = (ByteString *) ast;
1664
1665   g_free (string->string);
1666   g_slice_free (ByteString, string);
1667 }
1668
1669 static AST *
1670 bytestring_parse (TokenStream  *stream,
1671                   va_list      *app,
1672                   GError      **error)
1673 {
1674   static const ASTClass bytestring_class = {
1675     bytestring_get_pattern,
1676     maybe_wrapper, bytestring_get_value,
1677     bytestring_free
1678   };
1679   ByteString *string;
1680   SourceRef ref;
1681   gchar *token;
1682   gsize length;
1683   gchar quote;
1684   gchar *str;
1685   gint i, j;
1686
1687   token_stream_start_ref (stream, &ref);
1688   token = token_stream_get (stream);
1689   token_stream_end_ref (stream, &ref);
1690   g_assert (token[0] == 'b');
1691   length = strlen (token);
1692   quote = token[1];
1693
1694   str = g_malloc (length);
1695   g_assert (quote == '"' || quote == '\'');
1696   j = 0;
1697   i = 2;
1698   while (token[i] != quote)
1699     switch (token[i])
1700       {
1701       case '\0':
1702         parser_set_error (error, &ref, NULL,
1703                           G_VARIANT_PARSE_ERROR_UNTERMINATED_STRING_CONSTANT,
1704                           "unterminated string constant");
1705         g_free (token);
1706         return NULL;
1707
1708       case '\\':
1709         switch (token[++i])
1710           {
1711           case '\0':
1712             parser_set_error (error, &ref, NULL,
1713                               G_VARIANT_PARSE_ERROR_UNTERMINATED_STRING_CONSTANT,
1714                               "unterminated string constant");
1715             g_free (token);
1716             return NULL;
1717
1718           case '0': case '1': case '2': case '3':
1719           case '4': case '5': case '6': case '7':
1720             {
1721               /* up to 3 characters */
1722               guchar val = token[i++] - '0';
1723
1724               if ('0' <= token[i] && token[i] < '8')
1725                 val = (val << 3) | (token[i++] - '0');
1726
1727               if ('0' <= token[i] && token[i] < '8')
1728                 val = (val << 3) | (token[i++] - '0');
1729
1730               str[j++] = val;
1731             }
1732             continue;
1733
1734           case 'a': str[j++] = '\a'; i++; continue;
1735           case 'b': str[j++] = '\b'; i++; continue;
1736           case 'f': str[j++] = '\f'; i++; continue;
1737           case 'n': str[j++] = '\n'; i++; continue;
1738           case 'r': str[j++] = '\r'; i++; continue;
1739           case 't': str[j++] = '\t'; i++; continue;
1740           case 'v': str[j++] = '\v'; i++; continue;
1741           case '\n': i++; continue;
1742           }
1743
1744       default:
1745         str[j++] = token[i++];
1746       }
1747   str[j++] = '\0';
1748   g_free (token);
1749
1750   string = g_slice_new (ByteString);
1751   string->ast.class = &bytestring_class;
1752   string->string = str;
1753
1754   token_stream_next (stream);
1755
1756   return (AST *) string;
1757 }
1758
1759 typedef struct
1760 {
1761   AST ast;
1762
1763   gchar *token;
1764 } Number;
1765
1766 static gchar *
1767 number_get_pattern (AST     *ast,
1768                     GError **error)
1769 {
1770   Number *number = (Number *) ast;
1771
1772   if (strchr (number->token, '.') ||
1773       (!g_str_has_prefix (number->token, "0x") && strchr (number->token, 'e')) ||
1774       strstr (number->token, "inf") ||
1775       strstr (number->token, "nan"))
1776     return g_strdup ("Md");
1777
1778   return g_strdup ("MN");
1779 }
1780
1781 static GVariant *
1782 number_overflow (AST                 *ast,
1783                  const GVariantType  *type,
1784                  GError             **error)
1785 {
1786   ast_set_error (ast, error, NULL,
1787                  G_VARIANT_PARSE_ERROR_NUMBER_OUT_OF_RANGE,
1788                  "number out of range for type `%c'",
1789                  g_variant_type_peek_string (type)[0]);
1790   return NULL;
1791 }
1792
1793 static GVariant *
1794 number_get_value (AST                 *ast,
1795                   const GVariantType  *type,
1796                   GError             **error)
1797 {
1798   Number *number = (Number *) ast;
1799   const gchar *token;
1800   gboolean negative;
1801   gboolean floating;
1802   guint64 abs_val;
1803   gdouble dbl_val;
1804   gchar *end;
1805
1806   token = number->token;
1807
1808   if (g_variant_type_equal (type, G_VARIANT_TYPE_DOUBLE))
1809     {
1810       floating = TRUE;
1811
1812       errno = 0;
1813       dbl_val = g_ascii_strtod (token, &end);
1814       if (dbl_val != 0.0 && errno == ERANGE)
1815         {
1816           ast_set_error (ast, error, NULL,
1817                          G_VARIANT_PARSE_ERROR_NUMBER_TOO_BIG,
1818                          "number too big for any type");
1819           return NULL;
1820         }
1821
1822       /* silence uninitialised warnings... */
1823       negative = FALSE;
1824       abs_val = 0;
1825     }
1826   else
1827     {
1828       floating = FALSE;
1829       negative = token[0] == '-';
1830       if (token[0] == '-')
1831         token++;
1832
1833       errno = 0;
1834       abs_val = g_ascii_strtoull (token, &end, 0);
1835       if (abs_val == G_MAXUINT64 && errno == ERANGE)
1836         {
1837           ast_set_error (ast, error, NULL,
1838                          G_VARIANT_PARSE_ERROR_NUMBER_TOO_BIG,
1839                          "integer too big for any type");
1840           return NULL;
1841         }
1842
1843       if (abs_val == 0)
1844         negative = FALSE;
1845
1846       /* silence uninitialised warning... */
1847       dbl_val = 0.0;
1848     }
1849
1850   if (*end != '\0')
1851     {
1852       SourceRef ref;
1853
1854       ref = ast->source_ref;
1855       ref.start += end - number->token;
1856       ref.end = ref.start + 1;
1857
1858       parser_set_error (error, &ref, NULL,
1859                         G_VARIANT_PARSE_ERROR_INVALID_CHARACTER,
1860                         "invalid character in number");
1861       return NULL;
1862      }
1863
1864   if (floating)
1865     return g_variant_new_double (dbl_val);
1866
1867   switch (*g_variant_type_peek_string (type))
1868     {
1869     case 'y':
1870       if (negative || abs_val > G_MAXUINT8)
1871         return number_overflow (ast, type, error);
1872       return g_variant_new_byte (abs_val);
1873
1874     case 'n':
1875       if (abs_val - negative > G_MAXINT16)
1876         return number_overflow (ast, type, error);
1877       return g_variant_new_int16 (negative ? -abs_val : abs_val);
1878
1879     case 'q':
1880       if (negative || abs_val > G_MAXUINT16)
1881         return number_overflow (ast, type, error);
1882       return g_variant_new_uint16 (abs_val);
1883
1884     case 'i':
1885       if (abs_val - negative > G_MAXINT32)
1886         return number_overflow (ast, type, error);
1887       return g_variant_new_int32 (negative ? -abs_val : abs_val);
1888
1889     case 'u':
1890       if (negative || abs_val > G_MAXUINT32)
1891         return number_overflow (ast, type, error);
1892       return g_variant_new_uint32 (abs_val);
1893
1894     case 'x':
1895       if (abs_val - negative > G_MAXINT64)
1896         return number_overflow (ast, type, error);
1897       return g_variant_new_int64 (negative ? -abs_val : abs_val);
1898
1899     case 't':
1900       if (negative)
1901         return number_overflow (ast, type, error);
1902       return g_variant_new_uint64 (abs_val);
1903
1904     case 'h':
1905       if (abs_val - negative > G_MAXINT32)
1906         return number_overflow (ast, type, error);
1907       return g_variant_new_handle (negative ? -abs_val : abs_val);
1908
1909     default:
1910       return ast_type_error (ast, type, error);
1911     }
1912 }
1913
1914 static void
1915 number_free (AST *ast)
1916 {
1917   Number *number = (Number *) ast;
1918
1919   g_free (number->token);
1920   g_slice_free (Number, number);
1921 }
1922
1923 static AST *
1924 number_parse (TokenStream  *stream,
1925               va_list      *app,
1926               GError      **error)
1927 {
1928   static const ASTClass number_class = {
1929     number_get_pattern,
1930     maybe_wrapper, number_get_value,
1931     number_free
1932   };
1933   Number *number;
1934
1935   number = g_slice_new (Number);
1936   number->ast.class = &number_class;
1937   number->token = token_stream_get (stream);
1938   token_stream_next (stream);
1939
1940   return (AST *) number;
1941 }
1942
1943 typedef struct
1944 {
1945   AST ast;
1946   gboolean value;
1947 } Boolean;
1948
1949 static gchar *
1950 boolean_get_pattern (AST     *ast,
1951                      GError **error)
1952 {
1953   return g_strdup ("Mb");
1954 }
1955
1956 static GVariant *
1957 boolean_get_value (AST                 *ast,
1958                    const GVariantType  *type,
1959                    GError             **error)
1960 {
1961   Boolean *boolean = (Boolean *) ast;
1962
1963   if (!g_variant_type_equal (type, G_VARIANT_TYPE_BOOLEAN))
1964     return ast_type_error (ast, type, error);
1965
1966   return g_variant_new_boolean (boolean->value);
1967 }
1968
1969 static void
1970 boolean_free (AST *ast)
1971 {
1972   Boolean *boolean = (Boolean *) ast;
1973
1974   g_slice_free (Boolean, boolean);
1975 }
1976
1977 static AST *
1978 boolean_new (gboolean value)
1979 {
1980   static const ASTClass boolean_class = {
1981     boolean_get_pattern,
1982     maybe_wrapper, boolean_get_value,
1983     boolean_free
1984   };
1985   Boolean *boolean;
1986
1987   boolean = g_slice_new (Boolean);
1988   boolean->ast.class = &boolean_class;
1989   boolean->value = value;
1990
1991   return (AST *) boolean;
1992 }
1993
1994 typedef struct
1995 {
1996   AST ast;
1997
1998   GVariant *value;
1999 } Positional;
2000
2001 static gchar *
2002 positional_get_pattern (AST     *ast,
2003                         GError **error)
2004 {
2005   Positional *positional = (Positional *) ast;
2006
2007   return g_strdup (g_variant_get_type_string (positional->value));
2008 }
2009
2010 static GVariant *
2011 positional_get_value (AST                 *ast,
2012                       const GVariantType  *type,
2013                       GError             **error)
2014 {
2015   Positional *positional = (Positional *) ast;
2016   GVariant *value;
2017
2018   g_assert (positional->value != NULL);
2019
2020   if G_UNLIKELY (!g_variant_is_of_type (positional->value, type))
2021     return ast_type_error (ast, type, error);
2022
2023   /* NOTE: if _get is called more than once then
2024    * things get messed up with respect to floating refs.
2025    *
2026    * fortunately, this function should only ever get called once.
2027    */
2028   g_assert (positional->value != NULL);
2029   value = positional->value;
2030   positional->value = NULL;
2031
2032   return value;
2033 }
2034
2035 static void
2036 positional_free (AST *ast)
2037 {
2038   Positional *positional = (Positional *) ast;
2039
2040   /* if positional->value is set, just leave it.
2041    * memory management doesn't matter in case of programmer error.
2042    */
2043   g_slice_free (Positional, positional);
2044 }
2045
2046 static AST *
2047 positional_parse (TokenStream  *stream,
2048                   va_list      *app,
2049                   GError      **error)
2050 {
2051   static const ASTClass positional_class = {
2052     positional_get_pattern,
2053     positional_get_value, NULL,
2054     positional_free
2055   };
2056   Positional *positional;
2057   const gchar *endptr;
2058   gchar *token;
2059
2060   token = token_stream_get (stream);
2061   g_assert (token[0] == '%');
2062
2063   positional = g_slice_new (Positional);
2064   positional->ast.class = &positional_class;
2065   positional->value = g_variant_new_va (token + 1, &endptr, app);
2066
2067   if (*endptr || positional->value == NULL)
2068     {
2069       token_stream_set_error (stream, error, TRUE,
2070                               G_VARIANT_PARSE_ERROR_INVALID_FORMAT_STRING,
2071                               "invalid GVariant format string");
2072       /* memory management doesn't matter in case of programmer error. */
2073       return NULL;
2074     }
2075
2076   token_stream_next (stream);
2077   g_free (token);
2078
2079   return (AST *) positional;
2080 }
2081
2082 typedef struct
2083 {
2084   AST ast;
2085
2086   GVariantType *type;
2087   AST *child;
2088 } TypeDecl;
2089
2090 static gchar *
2091 typedecl_get_pattern (AST     *ast,
2092                       GError **error)
2093 {
2094   TypeDecl *decl = (TypeDecl *) ast;
2095
2096   return g_variant_type_dup_string (decl->type);
2097 }
2098
2099 static GVariant *
2100 typedecl_get_value (AST                 *ast,
2101                     const GVariantType  *type,
2102                     GError             **error)
2103 {
2104   TypeDecl *decl = (TypeDecl *) ast;
2105
2106   return ast_get_value (decl->child, type, error);
2107 }
2108
2109 static void
2110 typedecl_free (AST *ast)
2111 {
2112   TypeDecl *decl = (TypeDecl *) ast;
2113
2114   ast_free (decl->child);
2115   g_variant_type_free (decl->type);
2116   g_slice_free (TypeDecl, decl);
2117 }
2118
2119 static AST *
2120 typedecl_parse (TokenStream  *stream,
2121                 va_list      *app,
2122                 GError      **error)
2123 {
2124   static const ASTClass typedecl_class = {
2125     typedecl_get_pattern,
2126     typedecl_get_value, NULL,
2127     typedecl_free
2128   };
2129   GVariantType *type;
2130   TypeDecl *decl;
2131   AST *child;
2132
2133   if (token_stream_peek (stream, '@'))
2134     {
2135       gchar *token;
2136
2137       token = token_stream_get (stream);
2138
2139       if (!g_variant_type_string_is_valid (token + 1))
2140         {
2141           token_stream_set_error (stream, error, TRUE,
2142                                   G_VARIANT_PARSE_ERROR_INVALID_TYPE_STRING,
2143                                   "invalid type declaration");
2144           g_free (token);
2145
2146           return NULL;
2147         }
2148
2149       type = g_variant_type_new (token + 1);
2150
2151       if (!g_variant_type_is_definite (type))
2152         {
2153           token_stream_set_error (stream, error, TRUE,
2154                                   G_VARIANT_PARSE_ERROR_DEFINITE_TYPE_EXPECTED,
2155                                   "type declarations must be definite");
2156           g_variant_type_free (type);
2157           g_free (token);
2158
2159           return NULL;
2160         }
2161
2162       token_stream_next (stream);
2163       g_free (token);
2164     }
2165   else
2166     {
2167       if (token_stream_consume (stream, "boolean"))
2168         type = g_variant_type_copy (G_VARIANT_TYPE_BOOLEAN);
2169
2170       else if (token_stream_consume (stream, "byte"))
2171         type = g_variant_type_copy (G_VARIANT_TYPE_BYTE);
2172
2173       else if (token_stream_consume (stream, "int16"))
2174         type = g_variant_type_copy (G_VARIANT_TYPE_INT16);
2175
2176       else if (token_stream_consume (stream, "uint16"))
2177         type = g_variant_type_copy (G_VARIANT_TYPE_UINT16);
2178
2179       else if (token_stream_consume (stream, "int32"))
2180         type = g_variant_type_copy (G_VARIANT_TYPE_INT32);
2181
2182       else if (token_stream_consume (stream, "handle"))
2183         type = g_variant_type_copy (G_VARIANT_TYPE_HANDLE);
2184
2185       else if (token_stream_consume (stream, "uint32"))
2186         type = g_variant_type_copy (G_VARIANT_TYPE_UINT32);
2187
2188       else if (token_stream_consume (stream, "int64"))
2189         type = g_variant_type_copy (G_VARIANT_TYPE_INT64);
2190
2191       else if (token_stream_consume (stream, "uint64"))
2192         type = g_variant_type_copy (G_VARIANT_TYPE_UINT64);
2193
2194       else if (token_stream_consume (stream, "double"))
2195         type = g_variant_type_copy (G_VARIANT_TYPE_DOUBLE);
2196
2197       else if (token_stream_consume (stream, "string"))
2198         type = g_variant_type_copy (G_VARIANT_TYPE_STRING);
2199
2200       else if (token_stream_consume (stream, "objectpath"))
2201         type = g_variant_type_copy (G_VARIANT_TYPE_OBJECT_PATH);
2202
2203       else if (token_stream_consume (stream, "signature"))
2204         type = g_variant_type_copy (G_VARIANT_TYPE_SIGNATURE);
2205
2206       else
2207         {
2208           token_stream_set_error (stream, error, TRUE,
2209                                   G_VARIANT_PARSE_ERROR_UNKNOWN_KEYWORD,
2210                                   "unknown keyword");
2211           return NULL;
2212         }
2213     }
2214
2215   if ((child = parse (stream, app, error)) == NULL)
2216     {
2217       g_variant_type_free (type);
2218       return NULL;
2219     }
2220
2221   decl = g_slice_new (TypeDecl);
2222   decl->ast.class = &typedecl_class;
2223   decl->type = type;
2224   decl->child = child;
2225
2226   return (AST *) decl;
2227 }
2228
2229 static AST *
2230 parse (TokenStream  *stream,
2231        va_list      *app,
2232        GError      **error)
2233 {
2234   SourceRef source_ref;
2235   AST *result;
2236
2237   token_stream_prepare (stream);
2238   token_stream_start_ref (stream, &source_ref);
2239
2240   if (token_stream_peek (stream, '['))
2241     result = array_parse (stream, app, error);
2242
2243   else if (token_stream_peek (stream, '('))
2244     result = tuple_parse (stream, app, error);
2245
2246   else if (token_stream_peek (stream, '<'))
2247     result = variant_parse (stream, app, error);
2248
2249   else if (token_stream_peek (stream, '{'))
2250     result = dictionary_parse (stream, app, error);
2251
2252   else if (app && token_stream_peek (stream, '%'))
2253     result = positional_parse (stream, app, error);
2254
2255   else if (token_stream_consume (stream, "true"))
2256     result = boolean_new (TRUE);
2257
2258   else if (token_stream_consume (stream, "false"))
2259     result = boolean_new (FALSE);
2260
2261   else if (token_stream_is_numeric (stream) ||
2262            token_stream_peek_string (stream, "inf") ||
2263            token_stream_peek_string (stream, "nan"))
2264     result = number_parse (stream, app, error);
2265
2266   else if (token_stream_peek (stream, 'n') ||
2267            token_stream_peek (stream, 'j'))
2268     result = maybe_parse (stream, app, error);
2269
2270   else if (token_stream_peek (stream, '@') ||
2271            token_stream_is_keyword (stream))
2272     result = typedecl_parse (stream, app, error);
2273
2274   else if (token_stream_peek (stream, '\'') ||
2275            token_stream_peek (stream, '"'))
2276     result = string_parse (stream, app, error);
2277
2278   else if (token_stream_peek2 (stream, 'b', '\'') ||
2279            token_stream_peek2 (stream, 'b', '"'))
2280     result = bytestring_parse (stream, app, error);
2281
2282   else
2283     {
2284       token_stream_set_error (stream, error, FALSE,
2285                               G_VARIANT_PARSE_ERROR_VALUE_EXPECTED,
2286                               "expected value");
2287       return NULL;
2288     }
2289
2290   if (result != NULL)
2291     {
2292       token_stream_end_ref (stream, &source_ref);
2293       result->source_ref = source_ref;
2294     }
2295
2296   return result;
2297 }
2298
2299 /**
2300  * g_variant_parse:
2301  * @type: (allow-none): a #GVariantType, or %NULL
2302  * @text: a string containing a GVariant in text form
2303  * @limit: (allow-none): a pointer to the end of @text, or %NULL
2304  * @endptr: (allow-none): a location to store the end pointer, or %NULL
2305  * @error: (allow-none): a pointer to a %NULL #GError pointer, or %NULL
2306  *
2307  * Parses a #GVariant from a text representation.
2308  *
2309  * A single #GVariant is parsed from the content of @text.
2310  *
2311  * The format is described <link linkend='gvariant-text'>here</link>.
2312  *
2313  * The memory at @limit will never be accessed and the parser behaves as
2314  * if the character at @limit is the nul terminator.  This has the
2315  * effect of bounding @text.
2316  *
2317  * If @endptr is non-%NULL then @text is permitted to contain data
2318  * following the value that this function parses and @endptr will be
2319  * updated to point to the first character past the end of the text
2320  * parsed by this function.  If @endptr is %NULL and there is extra data
2321  * then an error is returned.
2322  *
2323  * If @type is non-%NULL then the value will be parsed to have that
2324  * type.  This may result in additional parse errors (in the case that
2325  * the parsed value doesn't fit the type) but may also result in fewer
2326  * errors (in the case that the type would have been ambiguous, such as
2327  * with empty arrays).
2328  *
2329  * In the event that the parsing is successful, the resulting #GVariant
2330  * is returned.
2331  *
2332  * In case of any error, %NULL will be returned.  If @error is non-%NULL
2333  * then it will be set to reflect the error that occurred.
2334  *
2335  * Officially, the language understood by the parser is "any string
2336  * produced by g_variant_print()".
2337  *
2338  * Returns: a reference to a #GVariant, or %NULL
2339  **/
2340 GVariant *
2341 g_variant_parse (const GVariantType  *type,
2342                  const gchar         *text,
2343                  const gchar         *limit,
2344                  const gchar        **endptr,
2345                  GError             **error)
2346 {
2347   TokenStream stream = { 0, };
2348   GVariant *result = NULL;
2349   AST *ast;
2350
2351   g_return_val_if_fail (text != NULL, NULL);
2352   g_return_val_if_fail (text == limit || text != NULL, NULL);
2353
2354   stream.start = text;
2355   stream.stream = text;
2356   stream.end = limit;
2357
2358   if ((ast = parse (&stream, NULL, error)))
2359     {
2360       if (type == NULL)
2361         result = ast_resolve (ast, error);
2362       else
2363         result = ast_get_value (ast, type, error);
2364
2365       if (result != NULL)
2366         {
2367           g_variant_ref_sink (result);
2368
2369           if (endptr == NULL)
2370             {
2371               while (stream.stream != limit &&
2372                      g_ascii_isspace (*stream.stream))
2373                 stream.stream++;
2374
2375               if (stream.stream != limit && *stream.stream != '\0')
2376                 {
2377                   SourceRef ref = { stream.stream - text,
2378                                     stream.stream - text };
2379
2380                   parser_set_error (error, &ref, NULL,
2381                                     G_VARIANT_PARSE_ERROR_INPUT_NOT_AT_END,
2382                                     "expected end of input");
2383                   g_variant_unref (result);
2384
2385                   result = NULL;
2386                 }
2387             }
2388           else
2389             *endptr = stream.stream;
2390         }
2391
2392       ast_free (ast);
2393     }
2394
2395   return result;
2396 }
2397
2398 /**
2399  * g_variant_new_parsed_va:
2400  * @format: a text format #GVariant
2401  * @app: a pointer to a #va_list
2402  *
2403  * Parses @format and returns the result.
2404  *
2405  * This is the version of g_variant_new_parsed() intended to be used
2406  * from libraries.
2407  *
2408  * The return value will be floating if it was a newly created GVariant
2409  * instance.  In the case that @format simply specified the collection
2410  * of a #GVariant pointer (eg: @format was "%*") then the collected
2411  * #GVariant pointer will be returned unmodified, without adding any
2412  * additional references.
2413  *
2414  * In order to behave correctly in all cases it is necessary for the
2415  * calling function to g_variant_ref_sink() the return result before
2416  * returning control to the user that originally provided the pointer.
2417  * At this point, the caller will have their own full reference to the
2418  * result.  This can also be done by adding the result to a container,
2419  * or by passing it to another g_variant_new() call.
2420  *
2421  * Returns: a new, usually floating, #GVariant
2422  **/
2423 GVariant *
2424 g_variant_new_parsed_va (const gchar *format,
2425                          va_list     *app)
2426 {
2427   TokenStream stream = { 0, };
2428   GVariant *result = NULL;
2429   GError *error = NULL;
2430   AST *ast;
2431
2432   g_return_val_if_fail (format != NULL, NULL);
2433   g_return_val_if_fail (app != NULL, NULL);
2434
2435   stream.start = format;
2436   stream.stream = format;
2437   stream.end = NULL;
2438
2439   if ((ast = parse (&stream, app, &error)))
2440     {
2441       result = ast_resolve (ast, &error);
2442       ast_free (ast);
2443     }
2444
2445   if (result == NULL)
2446     g_error ("g_variant_new_parsed: %s", error->message);
2447
2448   if (*stream.stream)
2449     g_error ("g_variant_new_parsed: trailing text after value");
2450
2451   return result;
2452 }
2453
2454 /**
2455  * g_variant_new_parsed:
2456  * @format: a text format #GVariant
2457  * @...: arguments as per @format
2458  *
2459  * Parses @format and returns the result.
2460  *
2461  * @format must be a text format #GVariant with one extension: at any
2462  * point that a value may appear in the text, a '%' character followed
2463  * by a GVariant format string (as per g_variant_new()) may appear.  In
2464  * that case, the same arguments are collected from the argument list as
2465  * g_variant_new() would have collected.
2466  *
2467  * Consider this simple example:
2468  *
2469  * <informalexample><programlisting>
2470  *  g_variant_new_parsed ("[('one', 1), ('two', %i), (%s, 3)]", 2, "three");
2471  * </programlisting></informalexample>
2472  *
2473  * In the example, the variable argument parameters are collected and
2474  * filled in as if they were part of the original string to produce the
2475  * result of <code>[('one', 1), ('two', 2), ('three', 3)]</code>.
2476  *
2477  * This function is intended only to be used with @format as a string
2478  * literal.  Any parse error is fatal to the calling process.  If you
2479  * want to parse data from untrusted sources, use g_variant_parse().
2480  *
2481  * You may not use this function to return, unmodified, a single
2482  * #GVariant pointer from the argument list.  ie: @format may not solely
2483  * be anything along the lines of "%*", "%?", "\%r", or anything starting
2484  * with "%@".
2485  *
2486  * Returns: a new floating #GVariant instance
2487  **/
2488 GVariant *
2489 g_variant_new_parsed (const gchar *format,
2490                       ...)
2491 {
2492   GVariant *result;
2493   va_list ap;
2494
2495   va_start (ap, format);
2496   result = g_variant_new_parsed_va (format, &ap);
2497   va_end (ap);
2498
2499   return result;
2500 }
2501
2502 /**
2503  * g_variant_builder_add_parsed:
2504  * @builder: a #GVariantBuilder
2505  * @format: a text format #GVariant
2506  * @...: arguments as per @format
2507  *
2508  * Adds to a #GVariantBuilder.
2509  *
2510  * This call is a convenience wrapper that is exactly equivalent to
2511  * calling g_variant_new_parsed() followed by
2512  * g_variant_builder_add_value().
2513  *
2514  * This function might be used as follows:
2515  *
2516  * <programlisting>
2517  * GVariant *
2518  * make_pointless_dictionary (void)
2519  * {
2520  *   GVariantBuilder *builder;
2521  *   int i;
2522  *
2523  *   builder = g_variant_builder_new (G_VARIANT_TYPE_ARRAY);
2524  *   g_variant_builder_add_parsed (builder, "{'width', <%i>}", 600);
2525  *   g_variant_builder_add_parsed (builder, "{'title', <%s>}", "foo");
2526  *   g_variant_builder_add_parsed (builder, "{'transparency', <0.5>}");
2527  *   return g_variant_builder_end (builder);
2528  * }
2529  * </programlisting>
2530  *
2531  * Since: 2.26
2532  **/
2533 void
2534 g_variant_builder_add_parsed (GVariantBuilder *builder,
2535                               const gchar     *format,
2536                               ...)
2537 {
2538   va_list ap;
2539
2540   va_start (ap, format);
2541   g_variant_builder_add_value (builder, g_variant_new_parsed_va (format, &ap));
2542   va_end (ap);
2543 }