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