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>
30 * designed by ryan lortie and william hua
31 * designed in itb-229 and at ghazi's, 2009.
35 * G_VARIANT_PARSE_ERROR:
37 * Error domain for GVariant text format parsing. Specific error codes
38 * are not currently defined for this domain. See #GError for
39 * information on error domains.
43 * @G_VARIANT_PARSE_ERROR_FAILED: generic error
45 * Error codes returned by parsing text-format GVariants. Currently the
46 * parser makes no distinction between different types of error.
49 g_variant_parser_get_error_quark (void)
51 static GQuark the_quark;
54 the_quark = g_quark_from_static_string ("g-variant-parse-error-quark");
65 parser_set_error_va (GError **error,
71 GString *msg = g_string_new (NULL);
73 if (location->start == location->end)
74 g_string_append_printf (msg, "%d", location->start);
76 g_string_append_printf (msg, "%d-%d", location->start, location->end);
80 g_assert (other->start != other->end);
81 g_string_append_printf (msg, ",%d-%d", other->start, other->end);
83 g_string_append_c (msg, ':');
85 g_string_append_vprintf (msg, format, ap);
86 g_set_error_literal (error, G_VARIANT_PARSE_ERROR, 0, msg->str);
87 g_string_free (msg, TRUE);
91 parser_set_error (GError **error,
99 va_start (ap, format);
100 parser_set_error_va (error, location, other, format, ap);
115 token_stream_set_error (TokenStream *stream,
124 ref.start = stream->this - stream->start;
127 ref.end = stream->stream - stream->start;
131 va_start (ap, format);
132 parser_set_error_va (error, &ref, NULL, format, ap);
137 token_stream_prepare (TokenStream *stream)
142 if (stream->this != NULL)
145 while (stream->stream != stream->end && g_ascii_isspace (*stream->stream))
148 if (stream->stream == stream->end || *stream->stream == '\0')
150 stream->this = stream->stream;
154 switch (stream->stream[0])
156 case '-': case '+': case '.': case '0': case '1': case '2':
157 case '3': case '4': case '5': case '6': case '7': case '8':
159 for (end = stream->stream; end != stream->end; end++)
160 if (!g_ascii_isalnum (*end) &&
161 *end != '-' && *end != '+' && *end != '.')
166 if (stream->stream[1] == '\'' || stream->stream[1] == '"')
168 for (end = stream->stream + 2; end != stream->end; end++)
169 if (*end == stream->stream[1] || *end == '\0' ||
170 (*end == '\\' && (++end == stream->end || *end == '\0')))
173 if (end != stream->end && *end)
180 case 'a': /* 'b' */ case 'c': case 'd': case 'e': case 'f':
181 case 'g': case 'h': case 'i': case 'j': case 'k': case 'l':
182 case 'm': case 'n': case 'o': case 'p': case 'q': case 'r':
183 case 's': case 't': case 'u': case 'v': case 'w': case 'x':
185 for (end = stream->stream; end != stream->end; end++)
186 if (!g_ascii_isalnum (*end))
191 for (end = stream->stream + 1; end != stream->end; end++)
192 if (*end == stream->stream[0] || *end == '\0' ||
193 (*end == '\\' && (++end == stream->end || *end == '\0')))
196 if (end != stream->end && *end)
201 /* stop at the first space, comma, colon or unmatched bracket.
202 * deals nicely with cases like (%i, %i) or {%i: %i}.
204 for (end = stream->stream + 1;
205 end != stream->end && *end != ',' &&
206 *end != ':' && *end != '>' && !g_ascii_isspace (*end);
209 if (*end == '(' || *end == '{')
212 else if ((*end == ')' || *end == '}') && !brackets--)
218 end = stream->stream + 1;
222 stream->this = stream->stream;
223 stream->stream = end;
227 token_stream_next (TokenStream *stream)
233 token_stream_peek (TokenStream *stream,
236 token_stream_prepare (stream);
238 return stream->this[0] == first_char;
242 token_stream_peek2 (TokenStream *stream,
246 token_stream_prepare (stream);
248 return stream->this[0] == first_char &&
249 stream->this[1] == second_char;
253 token_stream_is_keyword (TokenStream *stream)
255 token_stream_prepare (stream);
257 return g_ascii_isalpha (stream->this[0]) &&
258 g_ascii_isalpha (stream->this[1]);
262 token_stream_is_numeric (TokenStream *stream)
264 token_stream_prepare (stream);
266 return (g_ascii_isdigit (stream->this[0]) ||
267 stream->this[0] == '-' ||
268 stream->this[0] == '+' ||
269 stream->this[0] == '.');
273 token_stream_consume (TokenStream *stream,
276 gint length = strlen (token);
278 token_stream_prepare (stream);
280 if (stream->stream - stream->this == length &&
281 memcmp (stream->this, token, length) == 0)
283 token_stream_next (stream);
291 token_stream_require (TokenStream *stream,
293 const gchar *purpose,
297 if (!token_stream_consume (stream, token))
299 token_stream_set_error (stream, error, FALSE,
300 "expected `%s'%s", token, purpose);
308 token_stream_assert (TokenStream *stream,
311 gboolean correct_token;
313 correct_token = token_stream_consume (stream, token);
314 g_assert (correct_token);
318 token_stream_get (TokenStream *stream)
322 token_stream_prepare (stream);
324 result = g_strndup (stream->this, stream->stream - stream->this);
330 token_stream_start_ref (TokenStream *stream,
333 token_stream_prepare (stream);
334 ref->start = stream->this - stream->start;
338 token_stream_end_ref (TokenStream *stream,
341 ref->end = stream->stream - stream->start;
345 pattern_copy (gchar **out,
350 while (**in == 'a' || **in == 'm' || **in == 'M')
351 *(*out)++ = *(*in)++;
355 if (**in == '(' || **in == '{')
358 else if (**in == ')' || **in == '}')
361 *(*out)++ = *(*in)++;
367 pattern_coalesce (const gchar *left,
373 /* the length of the output is loosely bound by the sum of the input
374 * lengths, not simply the greater of the two lengths.
376 * (*(iii)) + ((iii)*) ((iii)(iii))
380 out = result = g_malloc (strlen (left) + strlen (right));
382 while (*left && *right)
392 const gchar **one = &left, **the_other = &right;
395 if (**one == '*' && **the_other != ')')
397 pattern_copy (&out, the_other);
401 else if (**one == 'M' && **the_other == 'm')
403 *out++ = *(*the_other)++;
406 else if (**one == 'M' && **the_other != 'm')
411 else if (**one == 'N' && strchr ("ynqiuxthd", **the_other))
413 *out++ = *(*the_other)++;
417 else if (**one == 'S' && strchr ("sog", **the_other))
419 *out++ = *(*the_other)++;
423 else if (one == &left)
425 one = &right, the_other = &left;
445 typedef struct _AST AST;
446 typedef gchar * (*get_pattern_func) (AST *ast,
448 typedef GVariant * (*get_value_func) (AST *ast,
449 const GVariantType *type,
451 typedef GVariant * (*get_base_value_func) (AST *ast,
452 const GVariantType *type,
454 typedef void (*free_func) (AST *ast);
458 gchar * (* get_pattern) (AST *ast,
460 GVariant * (* get_value) (AST *ast,
461 const GVariantType *type,
463 GVariant * (* get_base_value) (AST *ast,
464 const GVariantType *type,
466 void (* free) (AST *ast);
471 const ASTClass *class;
472 SourceRef source_ref;
476 ast_get_pattern (AST *ast,
479 return ast->class->get_pattern (ast, error);
483 ast_get_value (AST *ast,
484 const GVariantType *type,
487 return ast->class->get_value (ast, type, error);
493 ast->class->free (ast);
497 ast_set_error (AST *ast,
505 va_start (ap, format);
506 parser_set_error_va (error, &ast->source_ref,
507 other_ast ? & other_ast->source_ref : NULL,
513 ast_type_error (AST *ast,
514 const GVariantType *type,
519 typestr = g_variant_type_dup_string (type);
520 ast_set_error (ast, error, NULL,
521 "can not parse as value of type `%s'",
529 ast_resolve (AST *ast,
536 pattern = ast_get_pattern (ast, error);
541 /* choose reasonable defaults
543 * 1) favour non-maybe values where possible
544 * 2) default type for strings is 's'
545 * 3) default type for integers is 'i'
547 for (i = 0; pattern[i]; i++)
551 ast_set_error (ast, error, NULL, "unable to infer type");
567 pattern[j++] = pattern[i];
572 value = ast_get_value (ast, G_VARIANT_TYPE (pattern), error);
579 static AST *parse (TokenStream *stream,
584 ast_array_append (AST ***array,
588 if ((*n_items & (*n_items - 1)) == 0)
589 *array = g_renew (AST *, *array, *n_items ? 2 ** n_items : 1);
591 (*array)[(*n_items)++] = ast;
595 ast_array_free (AST **array,
600 for (i = 0; i < n_items; i++)
606 ast_array_get_pattern (AST **array,
613 pattern = ast_get_pattern (array[0], error);
618 for (i = 1; i < n_items; i++)
622 tmp = ast_get_pattern (array[i], error);
630 merged = pattern_coalesce (pattern, tmp);
635 /* set coalescence implies pairwise coalescence (i think).
636 * we should therefore be able to trace the failure to a single
647 /* if 'j' reaches 'i' then we failed to find the pair */
650 tmp2 = ast_get_pattern (array[j], NULL);
651 g_assert (tmp2 != NULL);
653 m = pattern_coalesce (tmp, tmp2);
659 /* we found a conflict between 'i' and 'j'.
661 * report the error. note: 'j' is first.
663 ast_set_error (array[j], error, array[i],
664 "unable to find a common type");
685 maybe_get_pattern (AST *ast,
688 Maybe *maybe = (Maybe *) ast;
690 if (maybe->child != NULL)
692 gchar *child_pattern;
695 child_pattern = ast_get_pattern (maybe->child, error);
697 if (child_pattern == NULL)
700 pattern = g_strdup_printf ("m%s", child_pattern);
701 g_free (child_pattern);
706 return g_strdup ("m*");
710 maybe_get_value (AST *ast,
711 const GVariantType *type,
714 Maybe *maybe = (Maybe *) ast;
717 if (!g_variant_type_is_maybe (type))
718 return ast_type_error (ast, type, error);
720 type = g_variant_type_element (type);
724 value = ast_get_value (maybe->child, type, error);
732 return g_variant_new_maybe (type, value);
736 maybe_free (AST *ast)
738 Maybe *maybe = (Maybe *) ast;
740 if (maybe->child != NULL)
741 ast_free (maybe->child);
743 g_slice_free (Maybe, maybe);
747 maybe_parse (TokenStream *stream,
751 static const ASTClass maybe_class = {
753 maybe_get_value, NULL,
759 if (token_stream_consume (stream, "just"))
761 child = parse (stream, app, error);
766 else if (!token_stream_consume (stream, "nothing"))
768 token_stream_set_error (stream, error, TRUE, "unknown keyword");
772 maybe = g_slice_new (Maybe);
773 maybe->ast.class = &maybe_class;
774 maybe->child = child;
776 return (AST *) maybe;
780 maybe_wrapper (AST *ast,
781 const GVariantType *type,
784 const GVariantType *t;
788 for (depth = 0, t = type;
789 g_variant_type_is_maybe (t);
790 depth++, t = g_variant_type_element (t));
792 value = ast->class->get_base_value (ast, t, error);
798 value = g_variant_new_maybe (NULL, value);
812 array_get_pattern (AST *ast,
815 Array *array = (Array *) ast;
819 if (array->n_children == 0)
820 return g_strdup ("Ma*");
822 pattern = ast_array_get_pattern (array->children, array->n_children, error);
827 result = g_strdup_printf ("Ma%s", pattern);
834 array_get_value (AST *ast,
835 const GVariantType *type,
838 Array *array = (Array *) ast;
839 const GVariantType *childtype;
840 GVariantBuilder builder;
843 if (!g_variant_type_is_array (type))
844 return ast_type_error (ast, type, error);
846 g_variant_builder_init (&builder, type);
847 childtype = g_variant_type_element (type);
849 for (i = 0; i < array->n_children; i++)
853 if (!(child = ast_get_value (array->children[i], childtype, error)))
855 g_variant_builder_clear (&builder);
859 g_variant_builder_add_value (&builder, child);
862 return g_variant_builder_end (&builder);
866 array_free (AST *ast)
868 Array *array = (Array *) ast;
870 ast_array_free (array->children, array->n_children);
871 g_slice_free (Array, array);
875 array_parse (TokenStream *stream,
879 static const ASTClass array_class = {
881 maybe_wrapper, array_get_value,
884 gboolean need_comma = FALSE;
887 array = g_slice_new (Array);
888 array->ast.class = &array_class;
889 array->children = NULL;
890 array->n_children = 0;
892 token_stream_assert (stream, "[");
893 while (!token_stream_consume (stream, "]"))
898 !token_stream_require (stream, ",",
899 " or `]' to follow array element",
903 child = parse (stream, app, error);
908 ast_array_append (&array->children, &array->n_children, child);
912 return (AST *) array;
915 ast_array_free (array->children, array->n_children);
916 g_slice_free (Array, array);
930 tuple_get_pattern (AST *ast,
933 Tuple *tuple = (Tuple *) ast;
934 gchar *result = NULL;
938 parts = g_new (gchar *, tuple->n_children + 4);
939 parts[tuple->n_children + 1] = (gchar *) ")";
940 parts[tuple->n_children + 2] = NULL;
941 parts[0] = (gchar *) "M(";
943 for (i = 0; i < tuple->n_children; i++)
944 if (!(parts[i + 1] = ast_get_pattern (tuple->children[i], error)))
947 if (i == tuple->n_children)
948 result = g_strjoinv ("", parts);
950 /* parts[0] should not be freed */
959 tuple_get_value (AST *ast,
960 const GVariantType *type,
963 Tuple *tuple = (Tuple *) ast;
964 const GVariantType *childtype;
965 GVariantBuilder builder;
968 if (!g_variant_type_is_tuple (type))
969 return ast_type_error (ast, type, error);
971 g_variant_builder_init (&builder, type);
972 childtype = g_variant_type_first (type);
974 for (i = 0; i < tuple->n_children; i++)
978 if (!(child = ast_get_value (tuple->children[i], childtype, error)))
980 g_variant_builder_clear (&builder);
984 g_variant_builder_add_value (&builder, child);
985 childtype = g_variant_type_next (childtype);
988 return g_variant_builder_end (&builder);
992 tuple_free (AST *ast)
994 Tuple *tuple = (Tuple *) ast;
996 ast_array_free (tuple->children, tuple->n_children);
997 g_slice_free (Tuple, tuple);
1001 tuple_parse (TokenStream *stream,
1005 static const ASTClass tuple_class = {
1007 maybe_wrapper, tuple_get_value,
1010 gboolean need_comma = FALSE;
1011 gboolean first = TRUE;
1014 tuple = g_slice_new (Tuple);
1015 tuple->ast.class = &tuple_class;
1016 tuple->children = NULL;
1017 tuple->n_children = 0;
1019 token_stream_assert (stream, "(");
1020 while (!token_stream_consume (stream, ")"))
1025 !token_stream_require (stream, ",",
1026 " or `)' to follow tuple element",
1030 child = parse (stream, app, error);
1035 ast_array_append (&tuple->children, &tuple->n_children, child);
1037 /* the first time, we absolutely require a comma, so grab it here
1038 * and leave need_comma = FALSE so that the code above doesn't
1039 * require a second comma.
1041 * the second and remaining times, we set need_comma = TRUE.
1045 if (!token_stream_require (stream, ",",
1046 " after first tuple element", error))
1055 return (AST *) tuple;
1058 ast_array_free (tuple->children, tuple->n_children);
1059 g_slice_free (Tuple, tuple);
1072 variant_get_pattern (AST *ast,
1075 return g_strdup ("Mv");
1079 variant_get_value (AST *ast,
1080 const GVariantType *type,
1083 Variant *variant = (Variant *) ast;
1086 g_assert (g_variant_type_equal (type, G_VARIANT_TYPE_VARIANT));
1087 child = ast_resolve (variant->value, error);
1092 return g_variant_new_variant (child);
1096 variant_free (AST *ast)
1098 Variant *variant = (Variant *) ast;
1100 ast_free (variant->value);
1101 g_slice_free (Variant, variant);
1105 variant_parse (TokenStream *stream,
1109 static const ASTClass variant_class = {
1110 variant_get_pattern,
1111 maybe_wrapper, variant_get_value,
1117 token_stream_assert (stream, "<");
1118 value = parse (stream, app, error);
1123 if (!token_stream_require (stream, ">", " to follow variant value", error))
1129 variant = g_slice_new (Variant);
1130 variant->ast.class = &variant_class;
1131 variant->value = value;
1133 return (AST *) variant;
1146 dictionary_get_pattern (AST *ast,
1149 Dictionary *dict = (Dictionary *) ast;
1150 gchar *value_pattern;
1155 if (dict->n_children == 0)
1156 return g_strdup ("Ma{**}");
1158 key_pattern = ast_array_get_pattern (dict->keys,
1159 abs (dict->n_children),
1162 if (key_pattern == NULL)
1165 /* we can not have maybe keys */
1166 if (key_pattern[0] == 'M')
1167 key_char = key_pattern[1];
1169 key_char = key_pattern[0];
1171 g_free (key_pattern);
1174 * plus undetermined number type and undetermined string type.
1176 if (!strchr ("bynqiuxthdsogNS", key_char))
1178 ast_set_error (ast, error, NULL,
1179 "dictionary keys must have basic types");
1183 value_pattern = ast_get_pattern (dict->values[0], error);
1185 if (value_pattern == NULL)
1188 result = g_strdup_printf ("M%s{%c%s}",
1189 dict->n_children > 0 ? "a" : "",
1190 key_char, value_pattern);
1191 g_free (value_pattern);
1197 dictionary_get_value (AST *ast,
1198 const GVariantType *type,
1201 Dictionary *dict = (Dictionary *) ast;
1203 if (dict->n_children == -1)
1205 const GVariantType *subtype;
1206 GVariantBuilder builder;
1209 if (!g_variant_type_is_dict_entry (type))
1210 return ast_type_error (ast, type, error);
1212 g_variant_builder_init (&builder, type);
1214 subtype = g_variant_type_key (type);
1215 if (!(subvalue = ast_get_value (dict->keys[0], subtype, error)))
1217 g_variant_builder_clear (&builder);
1220 g_variant_builder_add_value (&builder, subvalue);
1222 subtype = g_variant_type_value (type);
1223 if (!(subvalue = ast_get_value (dict->values[0], subtype, error)))
1225 g_variant_builder_clear (&builder);
1228 g_variant_builder_add_value (&builder, subvalue);
1230 return g_variant_builder_end (&builder);
1234 const GVariantType *entry, *key, *val;
1235 GVariantBuilder builder;
1238 if (!g_variant_type_is_subtype_of (type, G_VARIANT_TYPE_DICTIONARY))
1239 return ast_type_error (ast, type, error);
1241 entry = g_variant_type_element (type);
1242 key = g_variant_type_key (entry);
1243 val = g_variant_type_value (entry);
1245 g_variant_builder_init (&builder, type);
1247 for (i = 0; i < dict->n_children; i++)
1251 g_variant_builder_open (&builder, entry);
1253 if (!(subvalue = ast_get_value (dict->keys[i], key, error)))
1255 g_variant_builder_clear (&builder);
1258 g_variant_builder_add_value (&builder, subvalue);
1260 if (!(subvalue = ast_get_value (dict->values[i], val, error)))
1262 g_variant_builder_clear (&builder);
1265 g_variant_builder_add_value (&builder, subvalue);
1266 g_variant_builder_close (&builder);
1269 return g_variant_builder_end (&builder);
1274 dictionary_free (AST *ast)
1276 Dictionary *dict = (Dictionary *) ast;
1279 if (dict->n_children > -1)
1280 n_children = dict->n_children;
1284 ast_array_free (dict->keys, n_children);
1285 ast_array_free (dict->values, n_children);
1286 g_slice_free (Dictionary, dict);
1290 dictionary_parse (TokenStream *stream,
1294 static const ASTClass dictionary_class = {
1295 dictionary_get_pattern,
1296 maybe_wrapper, dictionary_get_value,
1299 gint n_keys, n_values;
1304 dict = g_slice_new (Dictionary);
1305 dict->ast.class = &dictionary_class;
1307 dict->values = NULL;
1308 n_keys = n_values = 0;
1310 token_stream_assert (stream, "{");
1312 if (token_stream_consume (stream, "}"))
1314 dict->n_children = 0;
1315 return (AST *) dict;
1318 if ((first = parse (stream, app, error)) == NULL)
1321 ast_array_append (&dict->keys, &n_keys, first);
1323 only_one = token_stream_consume (stream, ",");
1325 !token_stream_require (stream, ":",
1326 " or `,' to follow dictionary entry key",
1330 if ((first = parse (stream, app, error)) == NULL)
1333 ast_array_append (&dict->values, &n_values, first);
1337 if (!token_stream_require (stream, "}", " at end of dictionary entry",
1341 g_assert (n_keys == 1 && n_values == 1);
1342 dict->n_children = -1;
1344 return (AST *) dict;
1347 while (!token_stream_consume (stream, "}"))
1351 if (!token_stream_require (stream, ",",
1352 " or `}' to follow dictionary entry", error))
1355 child = parse (stream, app, error);
1360 ast_array_append (&dict->keys, &n_keys, child);
1362 if (!token_stream_require (stream, ":",
1363 " to follow dictionary entry key", error))
1366 child = parse (stream, app, error);
1371 ast_array_append (&dict->values, &n_values, child);
1374 g_assert (n_keys == n_values);
1375 dict->n_children = n_keys;
1377 return (AST *) dict;
1380 ast_array_free (dict->keys, n_keys);
1381 ast_array_free (dict->values, n_values);
1382 g_slice_free (Dictionary, dict);
1394 string_get_pattern (AST *ast,
1397 return g_strdup ("MS");
1401 string_get_value (AST *ast,
1402 const GVariantType *type,
1405 String *string = (String *) ast;
1407 if (g_variant_type_equal (type, G_VARIANT_TYPE_STRING))
1408 return g_variant_new_string (string->string);
1410 else if (g_variant_type_equal (type, G_VARIANT_TYPE_OBJECT_PATH))
1412 if (!g_variant_is_object_path (string->string))
1414 ast_set_error (ast, error, NULL, "not a valid object path");
1418 return g_variant_new_object_path (string->string);
1421 else if (g_variant_type_equal (type, G_VARIANT_TYPE_SIGNATURE))
1423 if (!g_variant_is_signature (string->string))
1425 ast_set_error (ast, error, NULL, "not a valid signature");
1429 return g_variant_new_signature (string->string);
1433 return ast_type_error (ast, type, error);
1437 string_free (AST *ast)
1439 String *string = (String *) ast;
1441 g_free (string->string);
1442 g_slice_free (String, string);
1446 unicode_unescape (const gchar *src,
1460 g_assert (length < sizeof (buffer));
1461 strncpy (buffer, src + *src_ofs, length);
1462 buffer[length] = '\0';
1464 value = g_ascii_strtoull (buffer, &end, 0x10);
1466 if (value == 0 || end != buffer + length)
1468 parser_set_error (error, ref, NULL,
1469 "invalid %d-character unicode escape", length);
1473 g_assert (value <= G_MAXUINT32);
1475 *dest_ofs += g_unichar_to_utf8 (value, dest + *dest_ofs);
1482 string_parse (TokenStream *stream,
1486 static const ASTClass string_class = {
1488 maybe_wrapper, string_get_value,
1499 token_stream_start_ref (stream, &ref);
1500 token = token_stream_get (stream);
1501 token_stream_end_ref (stream, &ref);
1502 length = strlen (token);
1505 str = g_malloc (length);
1506 g_assert (quote == '"' || quote == '\'');
1509 while (token[i] != quote)
1513 parser_set_error (error, &ref, NULL,
1514 "unterminated string constant");
1522 parser_set_error (error, &ref, NULL,
1523 "unterminated string constant");
1528 if (!unicode_unescape (token, &i, str, &j, 4, &ref, error))
1536 if (!unicode_unescape (token, &i, str, &j, 8, &ref, error))
1543 case 'a': str[j++] = '\a'; i++; continue;
1544 case 'b': str[j++] = '\b'; i++; continue;
1545 case 'f': str[j++] = '\f'; i++; continue;
1546 case 'n': str[j++] = '\n'; i++; continue;
1547 case 'r': str[j++] = '\r'; i++; continue;
1548 case 't': str[j++] = '\t'; i++; continue;
1549 case 'v': str[j++] = '\v'; i++; continue;
1550 case '\n': i++; continue;
1554 str[j++] = token[i++];
1559 string = g_slice_new (String);
1560 string->ast.class = &string_class;
1561 string->string = str;
1563 token_stream_next (stream);
1565 return (AST *) string;
1575 bytestring_get_pattern (AST *ast,
1578 return g_strdup ("May");
1582 bytestring_get_value (AST *ast,
1583 const GVariantType *type,
1586 ByteString *string = (ByteString *) ast;
1588 g_assert (g_variant_type_equal (type, G_VARIANT_TYPE_BYTESTRING));
1590 return g_variant_new_bytestring (string->string);
1594 bytestring_free (AST *ast)
1596 ByteString *string = (ByteString *) ast;
1598 g_free (string->string);
1599 g_slice_free (ByteString, string);
1603 bytestring_parse (TokenStream *stream,
1607 static const ASTClass bytestring_class = {
1608 bytestring_get_pattern,
1609 maybe_wrapper, bytestring_get_value,
1620 token_stream_start_ref (stream, &ref);
1621 token = token_stream_get (stream);
1622 token_stream_end_ref (stream, &ref);
1623 g_assert (token[0] == 'b');
1624 length = strlen (token);
1627 str = g_malloc (length);
1628 g_assert (quote == '"' || quote == '\'');
1631 while (token[i] != quote)
1635 parser_set_error (error, &ref, NULL,
1636 "unterminated string constant");
1644 parser_set_error (error, &ref, NULL,
1645 "unterminated string constant");
1649 case '0': case '1': case '2': case '3':
1650 case '4': case '5': case '6': case '7':
1652 /* up to 3 characters */
1653 guchar val = token[i++] - '0';
1655 if ('0' <= token[i] && token[i] < '8')
1656 val = (val << 3) | (token[i++] - '0');
1658 if ('0' <= token[i] && token[i] < '8')
1659 val = (val << 3) | (token[i++] - '0');
1665 case 'a': str[j++] = '\a'; i++; continue;
1666 case 'b': str[j++] = '\b'; i++; continue;
1667 case 'f': str[j++] = '\f'; i++; continue;
1668 case 'n': str[j++] = '\n'; i++; continue;
1669 case 'r': str[j++] = '\r'; i++; continue;
1670 case 't': str[j++] = '\t'; i++; continue;
1671 case 'v': str[j++] = '\v'; i++; continue;
1672 case '\n': i++; continue;
1676 str[j++] = token[i++];
1681 string = g_slice_new (ByteString);
1682 string->ast.class = &bytestring_class;
1683 string->string = str;
1685 token_stream_next (stream);
1687 return (AST *) string;
1698 number_get_pattern (AST *ast,
1701 Number *number = (Number *) ast;
1703 if (strchr (number->token, '.') ||
1704 (!g_str_has_prefix (number->token, "0x") &&
1705 strchr (number->token, 'e')))
1706 return g_strdup ("Md");
1708 return g_strdup ("MN");
1712 number_overflow (AST *ast,
1713 const GVariantType *type,
1716 ast_set_error (ast, error, NULL, "number out of range for type `%c'",
1717 g_variant_type_peek_string (type)[0]);
1722 number_get_value (AST *ast,
1723 const GVariantType *type,
1726 Number *number = (Number *) ast;
1734 token = number->token;
1736 if (g_variant_type_equal (type, G_VARIANT_TYPE_DOUBLE))
1741 dbl_val = g_ascii_strtod (token, &end);
1742 if (dbl_val != 0.0 && errno == ERANGE)
1744 ast_set_error (ast, error, NULL, "number too big for any type");
1748 /* silence uninitialised warnings... */
1755 negative = token[0] == '-';
1756 if (token[0] == '-')
1760 abs_val = g_ascii_strtoull (token, &end, 0);
1761 if (abs_val == G_MAXUINT64 && errno == ERANGE)
1763 ast_set_error (ast, error, NULL, "integer too big for any type");
1770 /* silence uninitialised warning... */
1778 ref = ast->source_ref;
1779 ref.start += end - number->token;
1780 ref.end = ref.start + 1;
1782 parser_set_error (error, &ref, NULL,
1783 "invalid character in number");
1788 return g_variant_new_double (dbl_val);
1790 switch (*g_variant_type_peek_string (type))
1793 if (negative || abs_val > G_MAXUINT8)
1794 return number_overflow (ast, type, error);
1795 return g_variant_new_byte (abs_val);
1798 if (abs_val - negative > G_MAXINT16)
1799 return number_overflow (ast, type, error);
1800 return g_variant_new_int16 (negative ? -abs_val : abs_val);
1803 if (negative || abs_val > G_MAXUINT16)
1804 return number_overflow (ast, type, error);
1805 return g_variant_new_uint16 (negative ? -abs_val : abs_val);
1808 if (abs_val - negative > G_MAXINT32)
1809 return number_overflow (ast, type, error);
1810 return g_variant_new_int32 (negative ? -abs_val : abs_val);
1813 if (negative || abs_val > G_MAXUINT32)
1814 return number_overflow (ast, type, error);
1815 return g_variant_new_uint32 (negative ? -abs_val : abs_val);
1818 if (abs_val - negative > G_MAXINT64)
1819 return number_overflow (ast, type, error);
1820 return g_variant_new_int64 (negative ? -abs_val : abs_val);
1824 return number_overflow (ast, type, error);
1825 return g_variant_new_uint64 (negative ? -abs_val : abs_val);
1828 if (abs_val - negative > G_MAXINT32)
1829 return number_overflow (ast, type, error);
1830 return g_variant_new_handle (negative ? -abs_val : abs_val);
1833 return ast_type_error (ast, type, error);
1838 number_free (AST *ast)
1840 Number *number = (Number *) ast;
1842 g_free (number->token);
1843 g_slice_free (Number, number);
1847 number_parse (TokenStream *stream,
1851 static const ASTClass number_class = {
1853 maybe_wrapper, number_get_value,
1858 number = g_slice_new (Number);
1859 number->ast.class = &number_class;
1860 number->token = token_stream_get (stream);
1861 token_stream_next (stream);
1863 return (AST *) number;
1873 boolean_get_pattern (AST *ast,
1876 return g_strdup ("Mb");
1880 boolean_get_value (AST *ast,
1881 const GVariantType *type,
1884 Boolean *boolean = (Boolean *) ast;
1886 if (!g_variant_type_equal (type, G_VARIANT_TYPE_BOOLEAN))
1887 return ast_type_error (ast, type, error);
1889 return g_variant_new_boolean (boolean->value);
1893 boolean_free (AST *ast)
1895 Boolean *boolean = (Boolean *) ast;
1897 g_slice_free (Boolean, boolean);
1901 boolean_new (gboolean value)
1903 static const ASTClass boolean_class = {
1904 boolean_get_pattern,
1905 maybe_wrapper, boolean_get_value,
1910 boolean = g_slice_new (Boolean);
1911 boolean->ast.class = &boolean_class;
1912 boolean->value = value;
1914 return (AST *) boolean;
1925 positional_get_pattern (AST *ast,
1928 Positional *positional = (Positional *) ast;
1930 return g_strdup (g_variant_get_type_string (positional->value));
1934 positional_get_value (AST *ast,
1935 const GVariantType *type,
1938 Positional *positional = (Positional *) ast;
1941 g_assert (positional->value != NULL);
1943 if G_UNLIKELY (!g_variant_is_of_type (positional->value, type))
1944 return ast_type_error (ast, type, error);
1946 /* NOTE: if _get is called more than once then
1947 * things get messed up with respect to floating refs.
1949 * fortunately, this function should only ever get called once.
1951 g_assert (positional->value != NULL);
1952 value = positional->value;
1953 positional->value = NULL;
1959 positional_free (AST *ast)
1961 Positional *positional = (Positional *) ast;
1963 /* if positional->value is set, just leave it.
1964 * memory management doesn't matter in case of programmer error.
1966 g_slice_free (Positional, positional);
1970 positional_parse (TokenStream *stream,
1974 static const ASTClass positional_class = {
1975 positional_get_pattern,
1976 positional_get_value, NULL,
1979 Positional *positional;
1980 const gchar *endptr;
1983 token = token_stream_get (stream);
1984 g_assert (token[0] == '%');
1986 positional = g_slice_new (Positional);
1987 positional->ast.class = &positional_class;
1988 positional->value = g_variant_new_va (token + 1, &endptr, app);
1990 if (*endptr || positional->value == NULL)
1992 token_stream_set_error (stream, error, TRUE,
1993 "invalid GVariant format string");
1994 /* memory management doesn't matter in case of programmer error. */
1998 token_stream_next (stream);
2001 return (AST *) positional;
2013 typedecl_get_pattern (AST *ast,
2016 TypeDecl *decl = (TypeDecl *) ast;
2018 return g_variant_type_dup_string (decl->type);
2022 typedecl_get_value (AST *ast,
2023 const GVariantType *type,
2026 TypeDecl *decl = (TypeDecl *) ast;
2028 return ast_get_value (decl->child, type, error);
2032 typedecl_free (AST *ast)
2034 TypeDecl *decl = (TypeDecl *) ast;
2036 ast_free (decl->child);
2037 g_variant_type_free (decl->type);
2038 g_slice_free (TypeDecl, decl);
2042 typedecl_parse (TokenStream *stream,
2046 static const ASTClass typedecl_class = {
2047 typedecl_get_pattern,
2048 typedecl_get_value, NULL,
2055 if (token_stream_peek (stream, '@'))
2059 token = token_stream_get (stream);
2061 if (!g_variant_type_string_is_valid (token + 1))
2063 token_stream_set_error (stream, error, TRUE,
2064 "invalid type declaration");
2070 type = g_variant_type_new (token + 1);
2072 if (!g_variant_type_is_definite (type))
2074 token_stream_set_error (stream, error, TRUE,
2075 "type declarations must be definite");
2076 g_variant_type_free (type);
2082 token_stream_next (stream);
2087 if (token_stream_consume (stream, "boolean"))
2088 type = g_variant_type_copy (G_VARIANT_TYPE_BOOLEAN);
2090 else if (token_stream_consume (stream, "byte"))
2091 type = g_variant_type_copy (G_VARIANT_TYPE_BYTE);
2093 else if (token_stream_consume (stream, "int16"))
2094 type = g_variant_type_copy (G_VARIANT_TYPE_INT16);
2096 else if (token_stream_consume (stream, "uint16"))
2097 type = g_variant_type_copy (G_VARIANT_TYPE_UINT16);
2099 else if (token_stream_consume (stream, "int32"))
2100 type = g_variant_type_copy (G_VARIANT_TYPE_INT32);
2102 else if (token_stream_consume (stream, "handle"))
2103 type = g_variant_type_copy (G_VARIANT_TYPE_HANDLE);
2105 else if (token_stream_consume (stream, "uint32"))
2106 type = g_variant_type_copy (G_VARIANT_TYPE_UINT32);
2108 else if (token_stream_consume (stream, "int64"))
2109 type = g_variant_type_copy (G_VARIANT_TYPE_INT64);
2111 else if (token_stream_consume (stream, "uint64"))
2112 type = g_variant_type_copy (G_VARIANT_TYPE_UINT64);
2114 else if (token_stream_consume (stream, "double"))
2115 type = g_variant_type_copy (G_VARIANT_TYPE_DOUBLE);
2117 else if (token_stream_consume (stream, "string"))
2118 type = g_variant_type_copy (G_VARIANT_TYPE_STRING);
2120 else if (token_stream_consume (stream, "objectpath"))
2121 type = g_variant_type_copy (G_VARIANT_TYPE_OBJECT_PATH);
2123 else if (token_stream_consume (stream, "signature"))
2124 type = g_variant_type_copy (G_VARIANT_TYPE_SIGNATURE);
2128 token_stream_set_error (stream, error, TRUE, "unknown keyword");
2133 if ((child = parse (stream, app, error)) == NULL)
2135 g_variant_type_free (type);
2139 decl = g_slice_new (TypeDecl);
2140 decl->ast.class = &typedecl_class;
2142 decl->child = child;
2144 return (AST *) decl;
2148 parse (TokenStream *stream,
2152 SourceRef source_ref;
2155 token_stream_prepare (stream);
2156 token_stream_start_ref (stream, &source_ref);
2158 if (token_stream_peek (stream, '['))
2159 result = array_parse (stream, app, error);
2161 else if (token_stream_peek (stream, '('))
2162 result = tuple_parse (stream, app, error);
2164 else if (token_stream_peek (stream, '<'))
2165 result = variant_parse (stream, app, error);
2167 else if (token_stream_peek (stream, '{'))
2168 result = dictionary_parse (stream, app, error);
2170 else if (app && token_stream_peek (stream, '%'))
2171 result = positional_parse (stream, app, error);
2173 else if (token_stream_consume (stream, "true"))
2174 result = boolean_new (TRUE);
2176 else if (token_stream_consume (stream, "false"))
2177 result = boolean_new (FALSE);
2179 else if (token_stream_peek (stream, 'n') ||
2180 token_stream_peek (stream, 'j'))
2181 result = maybe_parse (stream, app, error);
2183 else if (token_stream_peek (stream, '@') ||
2184 token_stream_is_keyword (stream))
2185 result = typedecl_parse (stream, app, error);
2187 else if (token_stream_is_numeric (stream))
2188 result = number_parse (stream, app, error);
2190 else if (token_stream_peek (stream, '\'') ||
2191 token_stream_peek (stream, '"'))
2192 result = string_parse (stream, app, error);
2194 else if (token_stream_peek2 (stream, 'b', '\'') ||
2195 token_stream_peek2 (stream, 'b', '"'))
2196 result = bytestring_parse (stream, app, error);
2200 token_stream_set_error (stream, error, FALSE, "expected value");
2206 token_stream_end_ref (stream, &source_ref);
2207 result->source_ref = source_ref;
2215 * @type: a #GVariantType, or %NULL
2216 * @text: a string containing a GVariant in text form
2217 * @limit: a pointer to the end of @text, or %NULL
2218 * @endptr: a location to store the end pointer, or %NULL
2219 * @error: a pointer to a %NULL #GError pointer, or %NULL
2220 * @Returns: a reference to a #GVariant, or %NULL
2222 * Parses a #GVariant from a text representation.
2224 * A single #GVariant is parsed from the content of @text.
2226 * The memory at @limit will never be accessed and the parser behaves as
2227 * if the character at @limit is the nul terminator. This has the
2228 * effect of bounding @text.
2230 * If @endptr is non-%NULL then @text is permitted to contain data
2231 * following the value that this function parses and @endptr will be
2232 * updated to point to the first character past the end of the text
2233 * parsed by this function. If @endptr is %NULL and there is extra data
2234 * then an error is returned.
2236 * If @type is non-%NULL then the value will be parsed to have that
2237 * type. This may result in additional parse errors (in the case that
2238 * the parsed value doesn't fit the type) but may also result in fewer
2239 * errors (in the case that the type would have been ambiguous, such as
2240 * with empty arrays).
2242 * In the event that the parsing is successful, the resulting #GVariant
2245 * In case of any error, %NULL will be returned. If @error is non-%NULL
2246 * then it will be set to reflect the error that occured.
2248 * Officially, the language understood by the parser is "any string
2249 * produced by g_variant_print()".
2252 g_variant_parse (const GVariantType *type,
2255 const gchar **endptr,
2258 TokenStream stream = { 0, };
2259 GVariant *result = NULL;
2262 g_return_val_if_fail (text != NULL, NULL);
2263 g_return_val_if_fail (text == limit || text != NULL, NULL);
2265 stream.start = text;
2266 stream.stream = text;
2269 if ((ast = parse (&stream, NULL, error)))
2272 result = ast_resolve (ast, error);
2274 result = ast_get_value (ast, type, error);
2278 g_variant_ref_sink (result);
2282 while (stream.stream != limit &&
2283 g_ascii_isspace (*stream.stream))
2286 if (stream.stream != limit && *stream.stream != '\0')
2288 SourceRef ref = { stream.stream - text,
2289 stream.stream - text };
2291 parser_set_error (error, &ref, NULL,
2292 "expected end of input");
2293 g_variant_unref (result);
2299 *endptr = stream.stream;
2309 * g_variant_new_parsed_va:
2310 * @format: a text format #GVariant
2311 * @app: a pointer to a #va_list
2312 * @returns: a new, usually floating, #GVariant
2314 * Parses @format and returns the result.
2316 * This is the version of g_variant_new_parsed() intended to be used
2319 * The return value will be floating if it was a newly created GVariant
2320 * instance. In the case that @format simply specified the collection
2321 * of a #GVariant pointer (eg: @format was "%*") then the collected
2322 * #GVariant pointer will be returned unmodified, without adding any
2323 * additional references.
2325 * In order to behave correctly in all cases it is necessary for the
2326 * calling function to g_variant_ref_sink() the return result before
2327 * returning control to the user that originally provided the pointer.
2328 * At this point, the caller will have their own full reference to the
2329 * result. This can also be done by adding the result to a container,
2330 * or by passing it to another g_variant_new() call.
2333 g_variant_new_parsed_va (const gchar *format,
2336 TokenStream stream = { 0, };
2337 GVariant *result = NULL;
2338 GError *error = NULL;
2341 g_return_val_if_fail (format != NULL, NULL);
2342 g_return_val_if_fail (app != NULL, NULL);
2344 stream.start = format;
2345 stream.stream = format;
2348 if ((ast = parse (&stream, app, &error)))
2350 result = ast_resolve (ast, &error);
2355 g_error ("g_variant_new_parsed: %s", error->message);
2358 g_error ("g_variant_new_parsed: trailing text after value");
2364 * g_variant_new_parsed:
2365 * @format: a text format #GVariant
2366 * @...: arguments as per @format
2367 * @returns: a new floating #GVariant instance
2369 * Parses @format and returns the result.
2371 * @format must be a text format #GVariant with one extention: at any
2372 * point that a value may appear in the text, a '%' character followed
2373 * by a GVariant format string (as per g_variant_new()) may appear. In
2374 * that case, the same arguments are collected from the argument list as
2375 * g_variant_new() would have collected.
2377 * Consider this simple example:
2379 * <informalexample><programlisting>
2380 * g_variant_new_parsed ("[('one', 1), ('two', %i), (%s, 3)]", 2, "three");
2381 * </programlisting></informalexample>
2383 * In the example, the variable argument parameters are collected and
2384 * filled in as if they were part of the original string to produce the
2385 * result of <code>[('one', 1), ('two', 2), ('three', 3)]</code>.
2387 * This function is intended only to be used with @format as a string
2388 * literal. Any parse error is fatal to the calling process. If you
2389 * want to parse data from untrusted sources, use g_variant_parse().
2391 * You may not use this function to return, unmodified, a single
2392 * #GVariant pointer from the argument list. ie: @format may not solely
2393 * be anything along the lines of "%*", "%?", "%r", or anything starting
2397 g_variant_new_parsed (const gchar *format,
2403 va_start (ap, format);
2404 result = g_variant_new_parsed_va (format, &ap);
2411 * g_variant_builder_add_parsed:
2412 * @builder: a #GVariantBuilder
2413 * @format: a text format #GVariant
2414 * @...: arguments as per @format
2416 * Adds to a #GVariantBuilder.
2418 * This call is a convenience wrapper that is exactly equivalent to
2419 * calling g_variant_new_parsed() followed by
2420 * g_variant_builder_add_value().
2422 * This function might be used as follows:
2426 * make_pointless_dictionary (void)
2428 * GVariantBuilder *builder;
2431 * builder = g_variant_builder_new (G_VARIANT_TYPE_ARRAY);
2432 * g_variant_builder_add_parsed (builder, "{'width', <%i>}", 600);
2433 * g_variant_builder_add_parsed (builder, "{'title', <%s>}", "foo");
2434 * g_variant_builder_add_parsed (builder, "{'transparency', <0.5>}");
2435 * return g_variant_builder_end (builder);
2442 g_variant_builder_add_parsed (GVariantBuilder *builder,
2443 const gchar *format,
2448 va_start (ap, format);
2449 g_variant_builder_add_value (builder, g_variant_new_parsed_va (format, &ap));