2 * Copyright © 2009, 2010 Codethink Limited
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.
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.
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.
19 * Author: Ryan Lortie <desrt@desrt.ca>
31 * designed by ryan lortie and william hua
32 * designed in itb-229 and at ghazi's, 2009.
36 g_variant_parser_get_error_quark (void)
38 static GQuark the_quark;
41 the_quark = g_quark_from_static_string ("g-variant-parse-error-quark");
52 parser_set_error_va (GError **error,
58 GString *msg = g_string_new (NULL);
60 if (location->start == location->end)
61 g_string_append_printf (msg, "%d", location->start);
63 g_string_append_printf (msg, "%d-%d", location->start, location->end);
67 g_assert (other->start != other->end);
68 g_string_append_printf (msg, ",%d-%d", other->start, other->end);
70 g_string_append_c (msg, ':');
72 g_string_append_vprintf (msg, format, ap);
73 g_set_error_literal (error, G_VARIANT_PARSE_ERROR, 0, msg->str);
74 g_string_free (msg, TRUE);
78 parser_set_error (GError **error,
86 va_start (ap, format);
87 parser_set_error_va (error, location, other, format, ap);
102 token_stream_set_error (TokenStream *stream,
111 ref.start = stream->this - stream->start;
114 ref.end = stream->stream - stream->start;
118 va_start (ap, format);
119 parser_set_error_va (error, &ref, NULL, format, ap);
124 token_stream_prepare (TokenStream *stream)
129 if (stream->this != NULL)
132 while (stream->stream != stream->end && g_ascii_isspace (*stream->stream))
135 if (stream->stream == stream->end || *stream->stream == '\0')
137 stream->this = stream->stream;
141 switch (stream->stream[0])
143 case '-': case '+': case '.': case '0': case '1': case '2':
144 case '3': case '4': case '5': case '6': case '7': case '8':
146 for (end = stream->stream; end != stream->end; end++)
147 if (!g_ascii_isalnum (*end) &&
148 *end != '-' && *end != '+' && *end != '.')
152 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
153 case 'g': case 'h': case 'i': case 'j': case 'k': case 'l':
154 case 'm': case 'n': case 'o': case 'p': case 'q': case 'r':
155 case 's': case 't': case 'u': case 'v': case 'w': case 'x':
157 for (end = stream->stream; end != stream->end; end++)
158 if (!g_ascii_isalnum (*end))
163 /* stop at the first space, comma or unmatched bracket.
164 * deals nicely with cases like (%i, %i).
166 for (end = stream->stream + 1;
167 end != stream->end && *end != ',' && !g_ascii_isspace (*end);
170 if (*end == '(' || *end == '{')
173 else if ((*end == ')' || *end == '}') && !brackets--)
179 for (end = stream->stream + 1; end != stream->end; end++)
180 if (*end == stream->stream[0] || *end == '\0' ||
181 (*end == '\\' && (++end == stream->end || *end == '\0')))
184 if (end != stream->end && *end)
189 end = stream->stream + 1;
193 stream->this = stream->stream;
194 stream->stream = end;
198 token_stream_next (TokenStream *stream)
204 token_stream_peek (TokenStream *stream,
207 token_stream_prepare (stream);
209 return stream->this[0] == first_char;
213 token_stream_is_keyword (TokenStream *stream)
215 token_stream_prepare (stream);
217 return g_ascii_isalpha (stream->this[0]);
221 token_stream_is_numeric (TokenStream *stream)
223 token_stream_prepare (stream);
225 return (g_ascii_isdigit (stream->this[0]) ||
226 stream->this[0] == '-' ||
227 stream->this[0] == '+' ||
228 stream->this[0] == '.');
232 token_stream_consume (TokenStream *stream,
235 gint length = strlen (token);
237 token_stream_prepare (stream);
239 if (stream->stream - stream->this == length &&
240 memcmp (stream->this, token, length) == 0)
242 token_stream_next (stream);
250 token_stream_require (TokenStream *stream,
252 const gchar *purpose,
256 if (!token_stream_consume (stream, token))
258 token_stream_set_error (stream, error, FALSE,
259 "expected `%s'%s", token, purpose);
267 token_stream_assert (TokenStream *stream,
270 gboolean correct_token;
272 correct_token = token_stream_consume (stream, token);
273 g_assert (correct_token);
277 token_stream_get (TokenStream *stream)
281 token_stream_prepare (stream);
283 result = g_strndup (stream->this, stream->stream - stream->this);
289 token_stream_start_ref (TokenStream *stream,
292 token_stream_prepare (stream);
293 ref->start = stream->this - stream->start;
297 token_stream_end_ref (TokenStream *stream,
300 ref->end = stream->stream - stream->start;
304 pattern_copy (gchar **out,
309 while (**in == 'a' || **in == 'm' || **in == 'M')
310 *(*out)++ = *(*in)++;
314 if (**in == '(' || **in == '{')
317 else if (**in == ')' || **in == '}')
320 *(*out)++ = *(*in)++;
326 pattern_coalesce (const gchar *left,
332 /* the length of the output is loosely bound by the sum of the input
333 * lengths, not simply the greater of the two lengths.
335 * (*(iii)) + ((iii)*) ((iii)(iii))
339 out = result = g_malloc (strlen (left) + strlen (right));
341 while (*left && *right)
351 const gchar **one = &left, **the_other = &right;
354 if (**one == '*' && **the_other != ')')
356 pattern_copy (&out, the_other);
360 else if (**one == 'M' && **the_other == 'm')
362 *out++ = *(*the_other)++;
365 else if (**one == 'M' && **the_other != 'm')
370 else if (**one == 'N' && strchr ("ynqiuxthd", **the_other))
372 *out++ = *(*the_other)++;
376 else if (**one == 'S' && strchr ("sog", **the_other))
378 *out++ = *(*the_other)++;
382 else if (one == &left)
384 one = &right, the_other = &left;
404 typedef struct _AST AST;
405 typedef gchar * (*get_pattern_func) (AST *ast,
407 typedef GVariant * (*get_value_func) (AST *ast,
408 const GVariantType *type,
410 typedef GVariant * (*get_base_value_func) (AST *ast,
411 const GVariantType *type,
413 typedef void (*free_func) (AST *ast);
417 gchar * (* get_pattern) (AST *ast,
419 GVariant * (* get_value) (AST *ast,
420 const GVariantType *type,
422 GVariant * (* get_base_value) (AST *ast,
423 const GVariantType *type,
425 void (* free) (AST *ast);
430 const ASTClass *class;
431 SourceRef source_ref;
435 ast_get_pattern (AST *ast,
438 return ast->class->get_pattern (ast, error);
442 ast_get_value (AST *ast,
443 const GVariantType *type,
446 return ast->class->get_value (ast, type, error);
452 ast->class->free (ast);
456 ast_set_error (AST *ast,
464 va_start (ap, format);
465 parser_set_error_va (error, &ast->source_ref,
466 other_ast ? & other_ast->source_ref : NULL,
472 ast_type_error (AST *ast,
473 const GVariantType *type,
478 typestr = g_variant_type_dup_string (type);
479 ast_set_error (ast, error, NULL,
480 "can not parse as value of type `%s'",
488 ast_resolve (AST *ast,
495 pattern = ast_get_pattern (ast, error);
500 /* choose reasonable defaults
502 * 1) favour non-maybe values where possible
503 * 2) default type for strings is 's'
504 * 3) default type for integers is 'i'
506 for (i = 0; pattern[i]; i++)
510 ast_set_error (ast, error, NULL, "unable to infer type");
526 pattern[j++] = pattern[i];
531 value = ast_get_value (ast, G_VARIANT_TYPE (pattern), error);
538 static AST *parse (TokenStream *stream,
543 ast_array_append (AST ***array,
547 if ((*n_items & (*n_items - 1)) == 0)
548 *array = g_renew (AST *, *array, *n_items ? 2 ** n_items : 1);
550 (*array)[(*n_items)++] = ast;
554 ast_array_free (AST **array,
559 for (i = 0; i < n_items; i++)
565 ast_array_get_pattern (AST **array,
572 pattern = ast_get_pattern (array[0], error);
577 for (i = 1; i < n_items; i++)
581 tmp = ast_get_pattern (array[i], error);
589 merged = pattern_coalesce (pattern, tmp);
594 /* set coalescence implies pairwise coalescence (i think).
595 * we should therefore be able to trace the failure to a single
606 /* if 'j' reaches 'i' then we failed to find the pair */
609 tmp2 = ast_get_pattern (array[j], NULL);
610 g_assert (tmp2 != NULL);
612 m = pattern_coalesce (tmp, tmp2);
618 /* we found a conflict between 'i' and 'j'.
620 * report the error. note: 'j' is first.
622 ast_set_error (array[j], error, array[i],
623 "unable to find a common type");
644 maybe_get_pattern (AST *ast,
647 Maybe *maybe = (Maybe *) ast;
649 if (maybe->child != NULL)
651 gchar *child_pattern;
654 child_pattern = ast_get_pattern (maybe->child, error);
656 if (child_pattern == NULL)
659 pattern = g_strdup_printf ("m%s", child_pattern);
660 g_free (child_pattern);
665 return g_strdup ("m*");
669 maybe_get_value (AST *ast,
670 const GVariantType *type,
673 Maybe *maybe = (Maybe *) ast;
676 if (!g_variant_type_is_maybe (type))
677 return ast_type_error (ast, type, error);
679 type = g_variant_type_element (type);
683 value = ast_get_value (maybe->child, type, error);
691 return g_variant_new_maybe (type, value);
695 maybe_free (AST *ast)
697 Maybe *maybe = (Maybe *) ast;
699 if (maybe->child != NULL)
700 ast_free (maybe->child);
702 g_slice_free (Maybe, maybe);
706 maybe_parse (TokenStream *stream,
710 static const ASTClass maybe_class = {
712 maybe_get_value, NULL,
718 if (token_stream_consume (stream, "just"))
720 child = parse (stream, app, error);
725 else if (!token_stream_consume (stream, "nothing"))
727 token_stream_set_error (stream, error, TRUE, "unknown keyword");
731 maybe = g_slice_new (Maybe);
732 maybe->ast.class = &maybe_class;
733 maybe->child = child;
735 return (AST *) maybe;
739 maybe_wrapper (AST *ast,
740 const GVariantType *type,
743 const GVariantType *t;
747 for (depth = 0, t = type;
748 g_variant_type_is_maybe (t);
749 depth++, t = g_variant_type_element (t));
751 value = ast->class->get_base_value (ast, t, error);
757 value = g_variant_new_maybe (NULL, value);
771 array_get_pattern (AST *ast,
774 Array *array = (Array *) ast;
778 if (array->n_children == 0)
779 return g_strdup ("Ma*");
781 pattern = ast_array_get_pattern (array->children, array->n_children, error);
786 result = g_strdup_printf ("Ma%s", pattern);
793 array_get_value (AST *ast,
794 const GVariantType *type,
797 Array *array = (Array *) ast;
798 const GVariantType *childtype;
799 GVariantBuilder builder;
802 if (!g_variant_type_is_array (type))
803 return ast_type_error (ast, type, error);
805 g_variant_builder_init (&builder, type);
806 childtype = g_variant_type_element (type);
808 for (i = 0; i < array->n_children; i++)
812 if (!(child = ast_get_value (array->children[i], childtype, error)))
814 g_variant_builder_clear (&builder);
818 g_variant_builder_add_value (&builder, child);
821 return g_variant_builder_end (&builder);
825 array_free (AST *ast)
827 Array *array = (Array *) ast;
829 ast_array_free (array->children, array->n_children);
830 g_slice_free (Array, array);
834 array_parse (TokenStream *stream,
838 static const ASTClass array_class = {
840 maybe_wrapper, array_get_value,
843 gboolean need_comma = FALSE;
846 array = g_slice_new (Array);
847 array->ast.class = &array_class;
848 array->children = NULL;
849 array->n_children = 0;
851 token_stream_assert (stream, "[");
852 while (!token_stream_consume (stream, "]"))
857 !token_stream_require (stream, ",",
858 " or `]' to follow array element",
862 child = parse (stream, app, error);
867 ast_array_append (&array->children, &array->n_children, child);
871 return (AST *) array;
874 ast_array_free (array->children, array->n_children);
875 g_slice_free (Array, array);
889 tuple_get_pattern (AST *ast,
892 Tuple *tuple = (Tuple *) ast;
893 gchar *result = NULL;
897 parts = g_new (gchar *, tuple->n_children + 4);
898 parts[tuple->n_children + 1] = (gchar *) ")";
899 parts[tuple->n_children + 2] = NULL;
900 parts[0] = (gchar *) "M(";
902 for (i = 0; i < tuple->n_children; i++)
903 if (!(parts[i + 1] = ast_get_pattern (tuple->children[i], error)))
906 if (i == tuple->n_children)
907 result = g_strjoinv ("", parts);
909 /* parts[0] should not be freed */
918 tuple_get_value (AST *ast,
919 const GVariantType *type,
922 Tuple *tuple = (Tuple *) ast;
923 const GVariantType *childtype;
924 GVariantBuilder builder;
927 if (!g_variant_type_is_tuple (type))
928 return ast_type_error (ast, type, error);
930 g_variant_builder_init (&builder, type);
931 childtype = g_variant_type_first (type);
933 for (i = 0; i < tuple->n_children; i++)
937 if (!(child = ast_get_value (tuple->children[i], childtype, error)))
939 g_variant_builder_clear (&builder);
943 g_variant_builder_add_value (&builder, child);
944 childtype = g_variant_type_next (childtype);
947 return g_variant_builder_end (&builder);
951 tuple_free (AST *ast)
953 Tuple *tuple = (Tuple *) ast;
955 ast_array_free (tuple->children, tuple->n_children);
956 g_slice_free (Tuple, tuple);
960 tuple_parse (TokenStream *stream,
964 static const ASTClass tuple_class = {
966 maybe_wrapper, tuple_get_value,
969 gboolean need_comma = FALSE;
970 gboolean first = TRUE;
973 tuple = g_slice_new (Tuple);
974 tuple->ast.class = &tuple_class;
975 tuple->children = NULL;
976 tuple->n_children = 0;
978 token_stream_assert (stream, "(");
979 while (!token_stream_consume (stream, ")"))
984 !token_stream_require (stream, ",",
985 " or `)' to follow tuple element",
989 child = parse (stream, app, error);
994 ast_array_append (&tuple->children, &tuple->n_children, child);
996 /* the first time, we absolutely require a comma, so grab it here
997 * and leave need_comma = FALSE so that the code above doesn't
998 * require a second comma.
1000 * the second and remaining times, we set need_comma = TRUE.
1004 if (!token_stream_require (stream, ",",
1005 " after first tuple element", error))
1014 return (AST *) tuple;
1017 ast_array_free (tuple->children, tuple->n_children);
1018 g_slice_free (Tuple, tuple);
1031 variant_get_pattern (AST *ast,
1034 return g_strdup ("Mv");
1038 variant_get_value (AST *ast,
1039 const GVariantType *type,
1042 Variant *variant = (Variant *) ast;
1045 g_assert (g_variant_type_equal (type, G_VARIANT_TYPE_VARIANT));
1046 child = ast_resolve (variant->value, error);
1051 return g_variant_new_variant (child);
1055 variant_free (AST *ast)
1057 Variant *variant = (Variant *) ast;
1059 ast_free (variant->value);
1060 g_slice_free (Variant, variant);
1064 variant_parse (TokenStream *stream,
1068 static const ASTClass variant_class = {
1069 variant_get_pattern,
1070 maybe_wrapper, variant_get_value,
1076 token_stream_assert (stream, "<");
1077 value = parse (stream, app, error);
1082 if (!token_stream_require (stream, ">", " to follow variant value", error))
1088 variant = g_slice_new (Variant);
1089 variant->ast.class = &variant_class;
1090 variant->value = value;
1092 return (AST *) variant;
1105 dictionary_get_pattern (AST *ast,
1108 Dictionary *dict = (Dictionary *) ast;
1109 gchar *value_pattern;
1114 if (dict->n_children == 0)
1115 return g_strdup ("Ma{**}");
1117 key_pattern = ast_array_get_pattern (dict->keys,
1118 abs (dict->n_children),
1121 if (key_pattern == NULL)
1124 /* we can not have maybe keys */
1125 if (key_pattern[0] == 'M')
1126 key_char = key_pattern[1];
1128 key_char = key_pattern[0];
1130 g_free (key_pattern);
1133 * plus undetermined number type and undetermined string type.
1135 if (!strchr ("bynqiuxthdsogNS", key_char))
1137 ast_set_error (ast, error, NULL,
1138 "dictionary keys must have basic types");
1142 value_pattern = ast_get_pattern (dict->values[0], error);
1144 if (value_pattern == NULL)
1147 result = g_strdup_printf ("M%s{%c%s}",
1148 dict->n_children > 0 ? "a" : "",
1149 key_char, value_pattern);
1150 g_free (value_pattern);
1156 dictionary_get_value (AST *ast,
1157 const GVariantType *type,
1160 Dictionary *dict = (Dictionary *) ast;
1162 if (dict->n_children == -1)
1164 const GVariantType *subtype;
1165 GVariantBuilder builder;
1168 if (!g_variant_type_is_dict_entry (type))
1169 return ast_type_error (ast, type, error);
1171 g_variant_builder_init (&builder, type);
1173 subtype = g_variant_type_key (type);
1174 if (!(subvalue = ast_get_value (dict->keys[0], subtype, error)))
1176 g_variant_builder_clear (&builder);
1179 g_variant_builder_add_value (&builder, subvalue);
1181 subtype = g_variant_type_value (type);
1182 if (!(subvalue = ast_get_value (dict->values[0], subtype, error)))
1184 g_variant_builder_clear (&builder);
1187 g_variant_builder_add_value (&builder, subvalue);
1189 return g_variant_builder_end (&builder);
1193 const GVariantType *entry, *key, *val;
1194 GVariantBuilder builder;
1197 if (!g_variant_type_is_subtype_of (type, G_VARIANT_TYPE_DICTIONARY))
1198 return ast_type_error (ast, type, error);
1200 entry = g_variant_type_element (type);
1201 key = g_variant_type_key (entry);
1202 val = g_variant_type_value (entry);
1204 g_variant_builder_init (&builder, type);
1206 for (i = 0; i < dict->n_children; i++)
1210 g_variant_builder_open (&builder, entry);
1212 if (!(subvalue = ast_get_value (dict->keys[i], key, error)))
1214 g_variant_builder_clear (&builder);
1217 g_variant_builder_add_value (&builder, subvalue);
1219 if (!(subvalue = ast_get_value (dict->values[i], val, error)))
1221 g_variant_builder_clear (&builder);
1224 g_variant_builder_add_value (&builder, subvalue);
1225 g_variant_builder_close (&builder);
1228 return g_variant_builder_end (&builder);
1233 dictionary_free (AST *ast)
1235 Dictionary *dict = (Dictionary *) ast;
1238 if (dict->n_children > -1)
1239 n_children = dict->n_children;
1243 ast_array_free (dict->keys, n_children);
1244 ast_array_free (dict->values, n_children);
1245 g_slice_free (Dictionary, dict);
1249 dictionary_parse (TokenStream *stream,
1253 static const ASTClass dictionary_class = {
1254 dictionary_get_pattern,
1255 maybe_wrapper, dictionary_get_value,
1258 gint n_keys, n_values;
1263 dict = g_slice_new (Dictionary);
1264 dict->ast.class = &dictionary_class;
1266 dict->values = NULL;
1267 n_keys = n_values = 0;
1269 token_stream_assert (stream, "{");
1271 if (token_stream_consume (stream, "}"))
1273 dict->n_children = 0;
1274 return (AST *) dict;
1277 if ((first = parse (stream, app, error)) == NULL)
1280 ast_array_append (&dict->keys, &n_keys, first);
1282 only_one = token_stream_consume (stream, ",");
1284 !token_stream_require (stream, ":",
1285 " or `,' to follow dictionary entry key",
1289 if ((first = parse (stream, app, error)) == NULL)
1292 ast_array_append (&dict->values, &n_values, first);
1296 if (!token_stream_require (stream, "}", " at end of dictionary entry",
1300 g_assert (n_keys == 1 && n_values == 1);
1301 dict->n_children = -1;
1303 return (AST *) dict;
1306 while (!token_stream_consume (stream, "}"))
1310 if (!token_stream_require (stream, ",",
1311 " or `}' to follow dictionary entry", error))
1314 child = parse (stream, app, error);
1319 ast_array_append (&dict->keys, &n_keys, child);
1321 if (!token_stream_require (stream, ":",
1322 " to follow dictionary entry key", error))
1325 child = parse (stream, app, error);
1330 ast_array_append (&dict->values, &n_values, child);
1333 g_assert (n_keys == n_values);
1334 dict->n_children = n_keys;
1336 return (AST *) dict;
1339 ast_array_free (dict->keys, n_keys);
1340 ast_array_free (dict->values, n_values);
1341 g_slice_free (Dictionary, dict);
1353 string_get_pattern (AST *ast,
1356 return g_strdup ("MS");
1360 string_get_value (AST *ast,
1361 const GVariantType *type,
1364 String *string = (String *) ast;
1366 if (g_variant_type_equal (type, G_VARIANT_TYPE_STRING))
1367 return g_variant_new_string (string->string);
1369 else if (g_variant_type_equal (type, G_VARIANT_TYPE_OBJECT_PATH))
1371 if (!g_variant_is_object_path (string->string))
1373 ast_set_error (ast, error, NULL, "not a valid object path");
1377 return g_variant_new_object_path (string->string);
1380 else if (g_variant_type_equal (type, G_VARIANT_TYPE_SIGNATURE))
1382 if (!g_variant_is_signature (string->string))
1384 ast_set_error (ast, error, NULL, "not a valid signature");
1388 return g_variant_new_signature (string->string);
1392 return ast_type_error (ast, type, error);
1396 string_free (AST *ast)
1398 String *string = (String *) ast;
1400 g_free (string->string);
1401 g_slice_free (String, string);
1405 string_parse (TokenStream *stream,
1409 static const ASTClass string_class = {
1411 maybe_wrapper, string_get_value,
1422 token_stream_start_ref (stream, &ref);
1423 token = token_stream_get (stream);
1424 token_stream_end_ref (stream, &ref);
1425 length = strlen (token);
1428 str = g_malloc (length);
1429 g_assert (quote == '"' || quote == '\'');
1432 while (token[i] != quote)
1436 parser_set_error (error, &ref, NULL,
1437 "unterminated string constant");
1445 parser_set_error (error, &ref, NULL,
1446 "unterminated string constant");
1450 case '0': case '1': case '2': case '3':
1451 case '4': case '5': case '6': case '7':
1453 /* up to 3 characters */
1454 guchar val = token[i++] - '0';
1456 if ('0' <= token[i] && token[i] < '8')
1457 val = (val << 3) | (token[i++] - '0');
1459 if ('0' <= token[i] && token[i] < '8')
1460 val = (val << 3) | (token[i++] - '0');
1466 case 'b': str[j++] = '\b'; i++; continue;
1467 case 'f': str[j++] = '\f'; i++; continue;
1468 case 'n': str[j++] = '\n'; i++; continue;
1469 case 'r': str[j++] = '\r'; i++; continue;
1470 case 't': str[j++] = '\t'; i++; continue;
1471 case '\n': i++; continue;
1475 str[j++] = token[i++];
1480 string = g_slice_new (String);
1481 string->ast.class = &string_class;
1482 string->string = str;
1484 token_stream_next (stream);
1486 return (AST *) string;
1497 number_get_pattern (AST *ast,
1500 Number *number = (Number *) ast;
1502 if (strchr (number->token, '.') ||
1503 (!g_str_has_prefix (number->token, "0x") &&
1504 strchr (number->token, 'e')))
1505 return g_strdup ("Md");
1507 return g_strdup ("MN");
1511 number_overflow (AST *ast,
1512 const GVariantType *type,
1515 ast_set_error (ast, error, NULL, "number out of range for type `%c'",
1516 g_variant_type_peek_string (type)[0]);
1521 number_get_value (AST *ast,
1522 const GVariantType *type,
1525 Number *number = (Number *) ast;
1533 token = number->token;
1535 if (g_variant_type_equal (type, G_VARIANT_TYPE_DOUBLE))
1540 dbl_val = g_ascii_strtod (token, &end);
1541 if (dbl_val != 0.0 && errno == ERANGE)
1543 ast_set_error (ast, error, NULL, "number too big for any type");
1550 negative = token[0] == '-';
1551 if (token[0] == '-')
1555 abs_val = g_ascii_strtoull (token, &end, 0);
1556 if (abs_val == G_MAXUINT64 && errno == ERANGE)
1558 ast_set_error (ast, error, NULL, "integer too big for any type");
1570 ref = ast->source_ref;
1571 ref.start += end - number->token;
1572 ref.end = ref.start + 1;
1574 parser_set_error (error, &ref, NULL,
1575 "invalid character in number");
1580 return g_variant_new_double (dbl_val);
1582 switch (*g_variant_type_peek_string (type))
1585 if (negative || abs_val > G_MAXUINT8)
1586 return number_overflow (ast, type, error);
1587 return g_variant_new_byte (abs_val);
1590 if (abs_val - negative > G_MAXINT16)
1591 return number_overflow (ast, type, error);
1592 return g_variant_new_int16 (negative ? -abs_val : abs_val);
1595 if (negative || abs_val > G_MAXUINT16)
1596 return number_overflow (ast, type, error);
1597 return g_variant_new_uint16 (negative ? -abs_val : abs_val);
1600 if (abs_val - negative > G_MAXINT32)
1601 return number_overflow (ast, type, error);
1602 return g_variant_new_int32 (negative ? -abs_val : abs_val);
1605 if (negative || abs_val > G_MAXUINT32)
1606 return number_overflow (ast, type, error);
1607 return g_variant_new_uint32 (negative ? -abs_val : abs_val);
1610 if (abs_val - negative > G_MAXINT64)
1611 return number_overflow (ast, type, error);
1612 return g_variant_new_int64 (negative ? -abs_val : abs_val);
1616 return number_overflow (ast, type, error);
1617 return g_variant_new_uint64 (negative ? -abs_val : abs_val);
1620 if (abs_val - negative > G_MAXINT32)
1621 return number_overflow (ast, type, error);
1622 return g_variant_new_handle (negative ? -abs_val : abs_val);
1625 return ast_type_error (ast, type, error);
1630 number_free (AST *ast)
1632 Number *number = (Number *) ast;
1634 g_free (number->token);
1635 g_slice_free (Number, number);
1639 number_parse (TokenStream *stream,
1643 static const ASTClass number_class = {
1645 maybe_wrapper, number_get_value,
1650 number = g_slice_new (Number);
1651 number->ast.class = &number_class;
1652 number->token = token_stream_get (stream);
1653 token_stream_next (stream);
1655 return (AST *) number;
1665 boolean_get_pattern (AST *ast,
1668 return g_strdup ("Mb");
1672 boolean_get_value (AST *ast,
1673 const GVariantType *type,
1676 Boolean *boolean = (Boolean *) ast;
1678 if (!g_variant_type_equal (type, G_VARIANT_TYPE_BOOLEAN))
1679 return ast_type_error (ast, type, error);
1681 return g_variant_new_boolean (boolean->value);
1685 boolean_free (AST *ast)
1687 Boolean *boolean = (Boolean *) ast;
1689 g_slice_free (Boolean, boolean);
1693 boolean_new (gboolean value)
1695 static const ASTClass boolean_class = {
1696 boolean_get_pattern,
1697 maybe_wrapper, boolean_get_value,
1702 boolean = g_slice_new (Boolean);
1703 boolean->ast.class = &boolean_class;
1704 boolean->value = value;
1706 return (AST *) boolean;
1717 positional_get_pattern (AST *ast,
1720 Positional *positional = (Positional *) ast;
1722 return g_strdup (g_variant_get_type_string (positional->value));
1726 positional_get_value (AST *ast,
1727 const GVariantType *type,
1730 Positional *positional = (Positional *) ast;
1733 g_assert (positional->value != NULL);
1735 if G_UNLIKELY (!g_variant_is_of_type (positional->value, type))
1736 return ast_type_error (ast, type, error);
1738 /* NOTE: if _get is called more than once then
1739 * things get messed up with respect to floating refs.
1741 * fortunately, this function should only ever get called once.
1743 g_assert (positional->value != NULL);
1744 value = positional->value;
1745 positional->value = NULL;
1751 positional_free (AST *ast)
1753 Positional *positional = (Positional *) ast;
1755 /* if positional->value is set, just leave it.
1756 * memory management doesn't matter in case of programmer error.
1758 g_slice_free (Positional, positional);
1762 positional_parse (TokenStream *stream,
1766 static const ASTClass positional_class = {
1767 positional_get_pattern,
1768 positional_get_value, NULL,
1771 Positional *positional;
1772 const gchar *endptr;
1775 token = token_stream_get (stream);
1776 g_assert (token[0] == '%');
1778 positional = g_slice_new (Positional);
1779 positional->ast.class = &positional_class;
1780 positional->value = g_variant_new_va (token + 1, &endptr, app);
1782 if (*endptr || positional->value == NULL)
1784 token_stream_set_error (stream, error, TRUE,
1785 "invalid GVariant format string");
1786 /* memory management doesn't matter in case of programmer error. */
1790 token_stream_next (stream);
1793 return (AST *) positional;
1805 typedecl_get_pattern (AST *ast,
1808 TypeDecl *decl = (TypeDecl *) ast;
1810 return g_variant_type_dup_string (decl->type);
1814 typedecl_get_value (AST *ast,
1815 const GVariantType *type,
1818 TypeDecl *decl = (TypeDecl *) ast;
1820 return ast_get_value (decl->child, type, error);
1824 typedecl_free (AST *ast)
1826 TypeDecl *decl = (TypeDecl *) ast;
1828 ast_free (decl->child);
1829 g_variant_type_free (decl->type);
1830 g_slice_free (TypeDecl, decl);
1834 typedecl_parse (TokenStream *stream,
1838 static const ASTClass typedecl_class = {
1839 typedecl_get_pattern,
1840 typedecl_get_value, NULL,
1847 if (token_stream_peek (stream, '@'))
1851 token = token_stream_get (stream);
1853 if (!g_variant_type_string_is_valid (token + 1))
1855 token_stream_set_error (stream, error, TRUE,
1856 "invalid type declaration");
1862 type = g_variant_type_new (token + 1);
1864 if (!g_variant_type_is_definite (type))
1866 token_stream_set_error (stream, error, TRUE,
1867 "type declarations must be definite");
1868 g_variant_type_free (type);
1874 token_stream_next (stream);
1879 if (token_stream_consume (stream, "boolean"))
1880 type = g_variant_type_copy (G_VARIANT_TYPE_BOOLEAN);
1882 else if (token_stream_consume (stream, "byte"))
1883 type = g_variant_type_copy (G_VARIANT_TYPE_BYTE);
1885 else if (token_stream_consume (stream, "int16"))
1886 type = g_variant_type_copy (G_VARIANT_TYPE_INT16);
1888 else if (token_stream_consume (stream, "uint16"))
1889 type = g_variant_type_copy (G_VARIANT_TYPE_UINT16);
1891 else if (token_stream_consume (stream, "int32"))
1892 type = g_variant_type_copy (G_VARIANT_TYPE_INT32);
1894 else if (token_stream_consume (stream, "handle"))
1895 type = g_variant_type_copy (G_VARIANT_TYPE_HANDLE);
1897 else if (token_stream_consume (stream, "uint32"))
1898 type = g_variant_type_copy (G_VARIANT_TYPE_UINT32);
1900 else if (token_stream_consume (stream, "int64"))
1901 type = g_variant_type_copy (G_VARIANT_TYPE_INT64);
1903 else if (token_stream_consume (stream, "uint64"))
1904 type = g_variant_type_copy (G_VARIANT_TYPE_UINT64);
1906 else if (token_stream_consume (stream, "double"))
1907 type = g_variant_type_copy (G_VARIANT_TYPE_DOUBLE);
1909 else if (token_stream_consume (stream, "string"))
1910 type = g_variant_type_copy (G_VARIANT_TYPE_STRING);
1912 else if (token_stream_consume (stream, "objectpath"))
1913 type = g_variant_type_copy (G_VARIANT_TYPE_OBJECT_PATH);
1915 else if (token_stream_consume (stream, "signature"))
1916 type = g_variant_type_copy (G_VARIANT_TYPE_SIGNATURE);
1920 token_stream_set_error (stream, error, TRUE, "unknown keyword");
1925 if ((child = parse (stream, app, error)) == NULL)
1927 g_variant_type_free (type);
1931 decl = g_slice_new (TypeDecl);
1932 decl->ast.class = &typedecl_class;
1934 decl->child = child;
1936 return (AST *) decl;
1940 parse (TokenStream *stream,
1944 SourceRef source_ref;
1947 token_stream_prepare (stream);
1948 token_stream_start_ref (stream, &source_ref);
1950 if (token_stream_peek (stream, '['))
1951 result = array_parse (stream, app, error);
1953 else if (token_stream_peek (stream, '('))
1954 result = tuple_parse (stream, app, error);
1956 else if (token_stream_peek (stream, '<'))
1957 result = variant_parse (stream, app, error);
1959 else if (token_stream_peek (stream, '{'))
1960 result = dictionary_parse (stream, app, error);
1962 else if (app && token_stream_peek (stream, '%'))
1963 result = positional_parse (stream, app, error);
1965 else if (token_stream_consume (stream, "true"))
1966 result = boolean_new (TRUE);
1968 else if (token_stream_consume (stream, "false"))
1969 result = boolean_new (FALSE);
1971 else if (token_stream_peek (stream, 'n') ||
1972 token_stream_peek (stream, 'j'))
1973 result = maybe_parse (stream, app, error);
1975 else if (token_stream_peek (stream, '@') ||
1976 token_stream_is_keyword (stream))
1977 result = typedecl_parse (stream, app, error);
1979 else if (token_stream_is_numeric (stream))
1980 result = number_parse (stream, app, error);
1982 else if (token_stream_peek (stream, '\'') ||
1983 token_stream_peek (stream, '"'))
1984 result = string_parse (stream, app, error);
1988 token_stream_set_error (stream, error, FALSE, "expected value");
1994 token_stream_end_ref (stream, &source_ref);
1995 result->source_ref = source_ref;
2003 * @type: a #GVariantType, or %NULL
2004 * @text: a string containing a GVariant in text form
2005 * @limit: a pointer to the end of @text, or %NULL
2006 * @endptr: a location to store the end pointer, or %NULL
2007 * @error: a pointer to a %NULL #GError pointer, or %NULL
2008 * @Returns: a reference to a #GVariant, or %NULL
2010 * Parses a #GVariant from a text representation.
2012 * A single #GVariant is parsed from the content of @text.
2014 * The memory at @limit will never be accessed and the parser behaves as
2015 * if the character at @limit is the nul terminator. This has the
2016 * effect of bounding @text.
2018 * If @endptr is non-%NULL then @text is permitted to contain data
2019 * following the value that this function parses and @endptr will be
2020 * updated to point to the first character past the end of the text
2021 * parsed by this function. If @endptr is %NULL and there is extra data
2022 * then an error is returned.
2024 * If @type is non-%NULL then the value will be parsed to have that
2025 * type. This may result in additional parse errors (in the case that
2026 * the parsed value doesn't fit the type) but may also result in fewer
2027 * errors (in the case that the type would have been ambiguous, such as
2028 * with empty arrays).
2030 * In the event that the parsing is successful, the resulting #GVariant
2033 * In case of any error, %NULL will be returned. If @error is non-%NULL
2034 * then it will be set to reflect the error that occured.
2036 * Officially, the language understood by the parser is "any string
2037 * produced by g_variant_print()".
2040 g_variant_parse (const GVariantType *type,
2043 const gchar **endptr,
2046 TokenStream stream = { };
2047 GVariant *result = NULL;
2050 g_return_val_if_fail (text != NULL, NULL);
2051 g_return_val_if_fail (text == limit || text != NULL, NULL);
2053 stream.start = text;
2054 stream.stream = text;
2057 if ((ast = parse (&stream, NULL, error)))
2060 result = ast_resolve (ast, error);
2062 result = ast_get_value (ast, type, error);
2066 g_variant_ref_sink (result);
2070 while (stream.stream != limit &&
2071 g_ascii_isspace (*stream.stream))
2074 if (stream.stream != limit && *stream.stream != '\0')
2076 SourceRef ref = { stream.stream - text,
2077 stream.stream - text };
2079 parser_set_error (error, &ref, NULL,
2080 "expected end of input");
2081 g_variant_unref (result);
2087 *endptr = stream.stream;
2097 * g_variant_new_parsed_va:
2098 * @format: a text format #GVariant
2099 * @app: a pointer to a #va_list
2100 * @returns: a new floating #GVariant instance
2102 * Parses @format and returns the result.
2104 * This is the version of g_variant_new_parsed() intended to be used
2108 g_variant_new_parsed_va (const gchar *format,
2111 TokenStream stream = { };
2112 GVariant *result = NULL;
2113 GError *error = NULL;
2116 g_return_val_if_fail (format != NULL, NULL);
2117 g_return_val_if_fail (app != NULL, NULL);
2119 stream.start = format;
2120 stream.stream = format;
2123 if ((ast = parse (&stream, app, &error)))
2125 result = ast_resolve (ast, &error);
2130 g_error ("g_variant_new_parsed: %s", error->message);
2133 g_error ("g_variant_new_parsed: trailing text after value");
2139 * g_variant_new_parsed:
2140 * @format: a text format #GVariant
2141 * @...: arguments as per @format
2143 * Parses @format and returns the result.
2145 * @format must be a text format #GVariant with one extention: at any
2146 * point that a value may appear in the text, a '%' character followed
2147 * by a GVariant format string (as per g_variant_new()) may appear. In
2148 * that case, the same arguments are collected from the argument list as
2149 * g_variant_new() would have collected.
2151 * Consider this simple example:
2153 * <informalexample><programlisting>
2154 * g_variant_new_parsed ("[('one', 1), ('two', %i), (%s, 3)]", 2, "three");
2155 * </programlisting></informalexample>
2157 * In the example, the variable argument parameters are collected and
2158 * filled in as if they were part of the original string to produce the
2159 * result of <code>[('one', 1), ('two', 2), ('three', 3)]</code>.
2161 * This function is intended only to be used with @format as a string
2162 * literal. Any parse error is fatal to the calling process. If you
2163 * want to parse data from untrusted sources, use g_variant_parse().
2165 * You may not use this function to return, unmodified, a single
2166 * #GVariant pointer from the argument list. ie: @format may not solely
2167 * be anything along the lines of "%*", "%?", "%r", or anything starting
2171 g_variant_new_parsed (const gchar *format,
2177 va_start (ap, format);
2178 result = g_variant_new_parsed_va (format, &ap);
2184 #define __G_VARIANT_PARSER_C__
2185 #include "galiasdef.c"