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