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