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, see <http://www.gnu.org/licenses/>.
17 * Author: Ryan Lortie <desrt@desrt.ca>
29 #include "gstrfuncs.h"
30 #include "gtestutils.h"
32 #include "gvarianttype.h"
38 * designed by ryan lortie and william hua
39 * designed in itb-229 and at ghazi's, 2009.
43 * G_VARIANT_PARSE_ERROR:
45 * Error domain for GVariant text format parsing. Specific error codes
46 * are not currently defined for this domain. See #GError for
47 * information on error domains.
51 * @G_VARIANT_PARSE_ERROR_FAILED: generic error (unused)
52 * @G_VARIANT_PARSE_ERROR_BASIC_TYPE_EXPECTED: a non-basic #GVariantType was given where a basic type was expected
53 * @G_VARIANT_PARSE_ERROR_CANNOT_INFER_TYPE: cannot infer the #GVariantType
54 * @G_VARIANT_PARSE_ERROR_DEFINITE_TYPE_EXPECTED: an indefinite #GVariantType was given where a definite type was expected
55 * @G_VARIANT_PARSE_ERROR_INPUT_NOT_AT_END: extra data after parsing finished
56 * @G_VARIANT_PARSE_ERROR_INVALID_CHARACTER: invalid character in number or unicode escape
57 * @G_VARIANT_PARSE_ERROR_INVALID_FORMAT_STRING: not a valid #GVariant format string
58 * @G_VARIANT_PARSE_ERROR_INVALID_OBJECT_PATH: not a valid object path
59 * @G_VARIANT_PARSE_ERROR_INVALID_SIGNATURE: not a valid type signature
60 * @G_VARIANT_PARSE_ERROR_INVALID_TYPE_STRING: not a valid #GVariant type string
61 * @G_VARIANT_PARSE_ERROR_NO_COMMON_TYPE: could not find a common type for array entries
62 * @G_VARIANT_PARSE_ERROR_NUMBER_OUT_OF_RANGE: the numerical value is out of range of the given type
63 * @G_VARIANT_PARSE_ERROR_NUMBER_TOO_BIG: the numerical value is out of range for any type
64 * @G_VARIANT_PARSE_ERROR_TYPE_ERROR: cannot parse as variant of the specified type
65 * @G_VARIANT_PARSE_ERROR_UNEXPECTED_TOKEN: an unexpected token was encountered
66 * @G_VARIANT_PARSE_ERROR_UNKNOWN_KEYWORD: an unknown keyword was encountered
67 * @G_VARIANT_PARSE_ERROR_UNTERMINATED_STRING_CONSTANT: unterminated string constant
68 * @G_VARIANT_PARSE_ERROR_VALUE_EXPECTED: no value given
70 * Error codes returned by parsing text-format GVariants.
72 G_DEFINE_QUARK (g-variant-parse-error-quark, g_variant_parse_error)
75 * Deprecated: Use g_variant_parse_error_quark() instead.
78 g_variant_parser_get_error_quark (void)
80 return g_variant_parse_error_quark ();
90 parser_set_error_va (GError **error,
97 GString *msg = g_string_new (NULL);
99 if (location->start == location->end)
100 g_string_append_printf (msg, "%d", location->start);
102 g_string_append_printf (msg, "%d-%d", location->start, location->end);
106 g_assert (other->start != other->end);
107 g_string_append_printf (msg, ",%d-%d", other->start, other->end);
109 g_string_append_c (msg, ':');
111 g_string_append_vprintf (msg, format, ap);
112 g_set_error_literal (error, G_VARIANT_PARSE_ERROR, code, msg->str);
113 g_string_free (msg, TRUE);
118 parser_set_error (GError **error,
127 va_start (ap, format);
128 parser_set_error_va (error, location, other, code, format, ap);
144 token_stream_set_error (TokenStream *stream,
154 ref.start = stream->this - stream->start;
157 ref.end = stream->stream - stream->start;
161 va_start (ap, format);
162 parser_set_error_va (error, &ref, NULL, code, format, ap);
167 token_stream_prepare (TokenStream *stream)
172 if (stream->this != NULL)
175 while (stream->stream != stream->end && g_ascii_isspace (*stream->stream))
178 if (stream->stream == stream->end || *stream->stream == '\0')
180 stream->this = stream->stream;
184 switch (stream->stream[0])
186 case '-': case '+': case '.': case '0': case '1': case '2':
187 case '3': case '4': case '5': case '6': case '7': case '8':
189 for (end = stream->stream; end != stream->end; end++)
190 if (!g_ascii_isalnum (*end) &&
191 *end != '-' && *end != '+' && *end != '.')
196 if (stream->stream[1] == '\'' || stream->stream[1] == '"')
198 for (end = stream->stream + 2; end != stream->end; end++)
199 if (*end == stream->stream[1] || *end == '\0' ||
200 (*end == '\\' && (++end == stream->end || *end == '\0')))
203 if (end != stream->end && *end)
210 case 'a': /* 'b' */ case 'c': case 'd': case 'e': case 'f':
211 case 'g': case 'h': case 'i': case 'j': case 'k': case 'l':
212 case 'm': case 'n': case 'o': case 'p': case 'q': case 'r':
213 case 's': case 't': case 'u': case 'v': case 'w': case 'x':
215 for (end = stream->stream; end != stream->end; end++)
216 if (!g_ascii_isalnum (*end))
221 for (end = stream->stream + 1; end != stream->end; end++)
222 if (*end == stream->stream[0] || *end == '\0' ||
223 (*end == '\\' && (++end == stream->end || *end == '\0')))
226 if (end != stream->end && *end)
231 /* stop at the first space, comma, colon or unmatched bracket.
232 * deals nicely with cases like (%i, %i) or {%i: %i}.
233 * Also: ] and > are never in format strings.
235 for (end = stream->stream + 1;
236 end != stream->end && *end != ',' &&
237 *end != ':' && *end != '>' && *end != ']' && !g_ascii_isspace (*end);
240 if (*end == '(' || *end == '{')
243 else if ((*end == ')' || *end == '}') && !brackets--)
249 end = stream->stream + 1;
253 stream->this = stream->stream;
254 stream->stream = end;
260 token_stream_next (TokenStream *stream)
266 token_stream_peek (TokenStream *stream,
269 if (!token_stream_prepare (stream))
272 return stream->this[0] == first_char;
276 token_stream_peek2 (TokenStream *stream,
280 if (!token_stream_prepare (stream))
283 return stream->this[0] == first_char &&
284 stream->this[1] == second_char;
288 token_stream_is_keyword (TokenStream *stream)
290 if (!token_stream_prepare (stream))
293 return g_ascii_isalpha (stream->this[0]) &&
294 g_ascii_isalpha (stream->this[1]);
298 token_stream_is_numeric (TokenStream *stream)
300 if (!token_stream_prepare (stream))
303 return (g_ascii_isdigit (stream->this[0]) ||
304 stream->this[0] == '-' ||
305 stream->this[0] == '+' ||
306 stream->this[0] == '.');
310 token_stream_peek_string (TokenStream *stream,
313 gint length = strlen (token);
315 return token_stream_prepare (stream) &&
316 stream->stream - stream->this == length &&
317 memcmp (stream->this, token, length) == 0;
321 token_stream_consume (TokenStream *stream,
324 if (!token_stream_peek_string (stream, token))
327 token_stream_next (stream);
332 token_stream_require (TokenStream *stream,
334 const gchar *purpose,
338 if (!token_stream_consume (stream, token))
340 token_stream_set_error (stream, error, FALSE,
341 G_VARIANT_PARSE_ERROR_UNEXPECTED_TOKEN,
342 "expected '%s'%s", token, purpose);
350 token_stream_assert (TokenStream *stream,
353 gboolean correct_token;
355 correct_token = token_stream_consume (stream, token);
356 g_assert (correct_token);
360 token_stream_get (TokenStream *stream)
364 if (!token_stream_prepare (stream))
367 result = g_strndup (stream->this, stream->stream - stream->this);
373 token_stream_start_ref (TokenStream *stream,
376 token_stream_prepare (stream);
377 ref->start = stream->this - stream->start;
381 token_stream_end_ref (TokenStream *stream,
384 ref->end = stream->stream - stream->start;
388 pattern_copy (gchar **out,
393 while (**in == 'a' || **in == 'm' || **in == 'M')
394 *(*out)++ = *(*in)++;
398 if (**in == '(' || **in == '{')
401 else if (**in == ')' || **in == '}')
404 *(*out)++ = *(*in)++;
410 pattern_coalesce (const gchar *left,
416 /* the length of the output is loosely bound by the sum of the input
417 * lengths, not simply the greater of the two lengths.
419 * (*(iii)) + ((iii)*) ((iii)(iii))
423 out = result = g_malloc (strlen (left) + strlen (right));
425 while (*left && *right)
435 const gchar **one = &left, **the_other = &right;
438 if (**one == '*' && **the_other != ')')
440 pattern_copy (&out, the_other);
444 else if (**one == 'M' && **the_other == 'm')
446 *out++ = *(*the_other)++;
449 else if (**one == 'M' && **the_other != 'm')
454 else if (**one == 'N' && strchr ("ynqiuxthd", **the_other))
456 *out++ = *(*the_other)++;
460 else if (**one == 'S' && strchr ("sog", **the_other))
462 *out++ = *(*the_other)++;
466 else if (one == &left)
468 one = &right, the_other = &left;
488 typedef struct _AST AST;
489 typedef gchar * (*get_pattern_func) (AST *ast,
491 typedef GVariant * (*get_value_func) (AST *ast,
492 const GVariantType *type,
494 typedef GVariant * (*get_base_value_func) (AST *ast,
495 const GVariantType *type,
497 typedef void (*free_func) (AST *ast);
501 gchar * (* get_pattern) (AST *ast,
503 GVariant * (* get_value) (AST *ast,
504 const GVariantType *type,
506 GVariant * (* get_base_value) (AST *ast,
507 const GVariantType *type,
509 void (* free) (AST *ast);
514 const ASTClass *class;
515 SourceRef source_ref;
519 ast_get_pattern (AST *ast,
522 return ast->class->get_pattern (ast, error);
526 ast_get_value (AST *ast,
527 const GVariantType *type,
530 return ast->class->get_value (ast, type, error);
536 ast->class->free (ast);
541 ast_set_error (AST *ast,
550 va_start (ap, format);
551 parser_set_error_va (error, &ast->source_ref,
552 other_ast ? & other_ast->source_ref : NULL,
559 ast_type_error (AST *ast,
560 const GVariantType *type,
565 typestr = g_variant_type_dup_string (type);
566 ast_set_error (ast, error, NULL,
567 G_VARIANT_PARSE_ERROR_TYPE_ERROR,
568 "can not parse as value of type '%s'",
576 ast_resolve (AST *ast,
583 pattern = ast_get_pattern (ast, error);
588 /* choose reasonable defaults
590 * 1) favour non-maybe values where possible
591 * 2) default type for strings is 's'
592 * 3) default type for integers is 'i'
594 for (i = 0; pattern[i]; i++)
598 ast_set_error (ast, error, NULL,
599 G_VARIANT_PARSE_ERROR_CANNOT_INFER_TYPE,
600 "unable to infer type");
616 pattern[j++] = pattern[i];
621 value = ast_get_value (ast, G_VARIANT_TYPE (pattern), error);
628 static AST *parse (TokenStream *stream,
633 ast_array_append (AST ***array,
637 if ((*n_items & (*n_items - 1)) == 0)
638 *array = g_renew (AST *, *array, *n_items ? 2 ** n_items : 1);
640 (*array)[(*n_items)++] = ast;
644 ast_array_free (AST **array,
649 for (i = 0; i < n_items; i++)
655 ast_array_get_pattern (AST **array,
662 pattern = ast_get_pattern (array[0], error);
667 for (i = 1; i < n_items; i++)
671 tmp = ast_get_pattern (array[i], error);
679 merged = pattern_coalesce (pattern, tmp);
684 /* set coalescence implies pairwise coalescence (i think).
685 * we should therefore be able to trace the failure to a single
696 /* if 'j' reaches 'i' then we failed to find the pair */
699 tmp2 = ast_get_pattern (array[j], NULL);
700 g_assert (tmp2 != NULL);
702 m = pattern_coalesce (tmp, tmp2);
708 /* we found a conflict between 'i' and 'j'.
710 * report the error. note: 'j' is first.
712 ast_set_error (array[j], error, array[i],
713 G_VARIANT_PARSE_ERROR_NO_COMMON_TYPE,
714 "unable to find a common type");
738 maybe_get_pattern (AST *ast,
741 Maybe *maybe = (Maybe *) ast;
743 if (maybe->child != NULL)
745 gchar *child_pattern;
748 child_pattern = ast_get_pattern (maybe->child, error);
750 if (child_pattern == NULL)
753 pattern = g_strdup_printf ("m%s", child_pattern);
754 g_free (child_pattern);
759 return g_strdup ("m*");
763 maybe_get_value (AST *ast,
764 const GVariantType *type,
767 Maybe *maybe = (Maybe *) ast;
770 if (!g_variant_type_is_maybe (type))
771 return ast_type_error (ast, type, error);
773 type = g_variant_type_element (type);
777 value = ast_get_value (maybe->child, type, error);
785 return g_variant_new_maybe (type, value);
789 maybe_free (AST *ast)
791 Maybe *maybe = (Maybe *) ast;
793 if (maybe->child != NULL)
794 ast_free (maybe->child);
796 g_slice_free (Maybe, maybe);
800 maybe_parse (TokenStream *stream,
804 static const ASTClass maybe_class = {
806 maybe_get_value, NULL,
812 if (token_stream_consume (stream, "just"))
814 child = parse (stream, app, error);
819 else if (!token_stream_consume (stream, "nothing"))
821 token_stream_set_error (stream, error, TRUE,
822 G_VARIANT_PARSE_ERROR_UNKNOWN_KEYWORD,
827 maybe = g_slice_new (Maybe);
828 maybe->ast.class = &maybe_class;
829 maybe->child = child;
831 return (AST *) maybe;
835 maybe_wrapper (AST *ast,
836 const GVariantType *type,
839 const GVariantType *t;
843 for (depth = 0, t = type;
844 g_variant_type_is_maybe (t);
845 depth++, t = g_variant_type_element (t));
847 value = ast->class->get_base_value (ast, t, error);
853 value = g_variant_new_maybe (NULL, value);
867 array_get_pattern (AST *ast,
870 Array *array = (Array *) ast;
874 if (array->n_children == 0)
875 return g_strdup ("Ma*");
877 pattern = ast_array_get_pattern (array->children, array->n_children, error);
882 result = g_strdup_printf ("Ma%s", pattern);
889 array_get_value (AST *ast,
890 const GVariantType *type,
893 Array *array = (Array *) ast;
894 const GVariantType *childtype;
895 GVariantBuilder builder;
898 if (!g_variant_type_is_array (type))
899 return ast_type_error (ast, type, error);
901 g_variant_builder_init (&builder, type);
902 childtype = g_variant_type_element (type);
904 for (i = 0; i < array->n_children; i++)
908 if (!(child = ast_get_value (array->children[i], childtype, error)))
910 g_variant_builder_clear (&builder);
914 g_variant_builder_add_value (&builder, child);
917 return g_variant_builder_end (&builder);
921 array_free (AST *ast)
923 Array *array = (Array *) ast;
925 ast_array_free (array->children, array->n_children);
926 g_slice_free (Array, array);
930 array_parse (TokenStream *stream,
934 static const ASTClass array_class = {
936 maybe_wrapper, array_get_value,
939 gboolean need_comma = FALSE;
942 array = g_slice_new (Array);
943 array->ast.class = &array_class;
944 array->children = NULL;
945 array->n_children = 0;
947 token_stream_assert (stream, "[");
948 while (!token_stream_consume (stream, "]"))
953 !token_stream_require (stream, ",",
954 " or ']' to follow array element",
958 child = parse (stream, app, error);
963 ast_array_append (&array->children, &array->n_children, child);
967 return (AST *) array;
970 ast_array_free (array->children, array->n_children);
971 g_slice_free (Array, array);
985 tuple_get_pattern (AST *ast,
988 Tuple *tuple = (Tuple *) ast;
989 gchar *result = NULL;
993 parts = g_new (gchar *, tuple->n_children + 4);
994 parts[tuple->n_children + 1] = (gchar *) ")";
995 parts[tuple->n_children + 2] = NULL;
996 parts[0] = (gchar *) "M(";
998 for (i = 0; i < tuple->n_children; i++)
999 if (!(parts[i + 1] = ast_get_pattern (tuple->children[i], error)))
1002 if (i == tuple->n_children)
1003 result = g_strjoinv ("", parts);
1005 /* parts[0] should not be freed */
1007 g_free (parts[i--]);
1014 tuple_get_value (AST *ast,
1015 const GVariantType *type,
1018 Tuple *tuple = (Tuple *) ast;
1019 const GVariantType *childtype;
1020 GVariantBuilder builder;
1023 if (!g_variant_type_is_tuple (type))
1024 return ast_type_error (ast, type, error);
1026 g_variant_builder_init (&builder, type);
1027 childtype = g_variant_type_first (type);
1029 for (i = 0; i < tuple->n_children; i++)
1033 if (childtype == NULL)
1035 g_variant_builder_clear (&builder);
1036 return ast_type_error (ast, type, error);
1039 if (!(child = ast_get_value (tuple->children[i], childtype, error)))
1041 g_variant_builder_clear (&builder);
1045 g_variant_builder_add_value (&builder, child);
1046 childtype = g_variant_type_next (childtype);
1049 if (childtype != NULL)
1051 g_variant_builder_clear (&builder);
1052 return ast_type_error (ast, type, error);
1055 return g_variant_builder_end (&builder);
1059 tuple_free (AST *ast)
1061 Tuple *tuple = (Tuple *) ast;
1063 ast_array_free (tuple->children, tuple->n_children);
1064 g_slice_free (Tuple, tuple);
1068 tuple_parse (TokenStream *stream,
1072 static const ASTClass tuple_class = {
1074 maybe_wrapper, tuple_get_value,
1077 gboolean need_comma = FALSE;
1078 gboolean first = TRUE;
1081 tuple = g_slice_new (Tuple);
1082 tuple->ast.class = &tuple_class;
1083 tuple->children = NULL;
1084 tuple->n_children = 0;
1086 token_stream_assert (stream, "(");
1087 while (!token_stream_consume (stream, ")"))
1092 !token_stream_require (stream, ",",
1093 " or ')' to follow tuple element",
1097 child = parse (stream, app, error);
1102 ast_array_append (&tuple->children, &tuple->n_children, child);
1104 /* the first time, we absolutely require a comma, so grab it here
1105 * and leave need_comma = FALSE so that the code above doesn't
1106 * require a second comma.
1108 * the second and remaining times, we set need_comma = TRUE.
1112 if (!token_stream_require (stream, ",",
1113 " after first tuple element", error))
1122 return (AST *) tuple;
1125 ast_array_free (tuple->children, tuple->n_children);
1126 g_slice_free (Tuple, tuple);
1139 variant_get_pattern (AST *ast,
1142 return g_strdup ("Mv");
1146 variant_get_value (AST *ast,
1147 const GVariantType *type,
1150 Variant *variant = (Variant *) ast;
1153 if (!g_variant_type_equal (type, G_VARIANT_TYPE_VARIANT))
1154 return ast_type_error (ast, type, error);
1156 child = ast_resolve (variant->value, error);
1161 return g_variant_new_variant (child);
1165 variant_free (AST *ast)
1167 Variant *variant = (Variant *) ast;
1169 ast_free (variant->value);
1170 g_slice_free (Variant, variant);
1174 variant_parse (TokenStream *stream,
1178 static const ASTClass variant_class = {
1179 variant_get_pattern,
1180 maybe_wrapper, variant_get_value,
1186 token_stream_assert (stream, "<");
1187 value = parse (stream, app, error);
1192 if (!token_stream_require (stream, ">", " to follow variant value", error))
1198 variant = g_slice_new (Variant);
1199 variant->ast.class = &variant_class;
1200 variant->value = value;
1202 return (AST *) variant;
1215 dictionary_get_pattern (AST *ast,
1218 Dictionary *dict = (Dictionary *) ast;
1219 gchar *value_pattern;
1224 if (dict->n_children == 0)
1225 return g_strdup ("Ma{**}");
1227 key_pattern = ast_array_get_pattern (dict->keys,
1228 abs (dict->n_children),
1231 if (key_pattern == NULL)
1234 /* we can not have maybe keys */
1235 if (key_pattern[0] == 'M')
1236 key_char = key_pattern[1];
1238 key_char = key_pattern[0];
1240 g_free (key_pattern);
1243 * plus undetermined number type and undetermined string type.
1245 if (!strchr ("bynqiuxthdsogNS", key_char))
1247 ast_set_error (ast, error, NULL,
1248 G_VARIANT_PARSE_ERROR_BASIC_TYPE_EXPECTED,
1249 "dictionary keys must have basic types");
1253 value_pattern = ast_get_pattern (dict->values[0], error);
1255 if (value_pattern == NULL)
1258 result = g_strdup_printf ("M%s{%c%s}",
1259 dict->n_children > 0 ? "a" : "",
1260 key_char, value_pattern);
1261 g_free (value_pattern);
1267 dictionary_get_value (AST *ast,
1268 const GVariantType *type,
1271 Dictionary *dict = (Dictionary *) ast;
1273 if (dict->n_children == -1)
1275 const GVariantType *subtype;
1276 GVariantBuilder builder;
1279 if (!g_variant_type_is_dict_entry (type))
1280 return ast_type_error (ast, type, error);
1282 g_variant_builder_init (&builder, type);
1284 subtype = g_variant_type_key (type);
1285 if (!(subvalue = ast_get_value (dict->keys[0], subtype, error)))
1287 g_variant_builder_clear (&builder);
1290 g_variant_builder_add_value (&builder, subvalue);
1292 subtype = g_variant_type_value (type);
1293 if (!(subvalue = ast_get_value (dict->values[0], subtype, error)))
1295 g_variant_builder_clear (&builder);
1298 g_variant_builder_add_value (&builder, subvalue);
1300 return g_variant_builder_end (&builder);
1304 const GVariantType *entry, *key, *val;
1305 GVariantBuilder builder;
1308 if (!g_variant_type_is_subtype_of (type, G_VARIANT_TYPE_DICTIONARY))
1309 return ast_type_error (ast, type, error);
1311 entry = g_variant_type_element (type);
1312 key = g_variant_type_key (entry);
1313 val = g_variant_type_value (entry);
1315 g_variant_builder_init (&builder, type);
1317 for (i = 0; i < dict->n_children; i++)
1321 g_variant_builder_open (&builder, entry);
1323 if (!(subvalue = ast_get_value (dict->keys[i], key, error)))
1325 g_variant_builder_clear (&builder);
1328 g_variant_builder_add_value (&builder, subvalue);
1330 if (!(subvalue = ast_get_value (dict->values[i], val, error)))
1332 g_variant_builder_clear (&builder);
1335 g_variant_builder_add_value (&builder, subvalue);
1336 g_variant_builder_close (&builder);
1339 return g_variant_builder_end (&builder);
1344 dictionary_free (AST *ast)
1346 Dictionary *dict = (Dictionary *) ast;
1349 if (dict->n_children > -1)
1350 n_children = dict->n_children;
1354 ast_array_free (dict->keys, n_children);
1355 ast_array_free (dict->values, n_children);
1356 g_slice_free (Dictionary, dict);
1360 dictionary_parse (TokenStream *stream,
1364 static const ASTClass dictionary_class = {
1365 dictionary_get_pattern,
1366 maybe_wrapper, dictionary_get_value,
1369 gint n_keys, n_values;
1374 dict = g_slice_new (Dictionary);
1375 dict->ast.class = &dictionary_class;
1377 dict->values = NULL;
1378 n_keys = n_values = 0;
1380 token_stream_assert (stream, "{");
1382 if (token_stream_consume (stream, "}"))
1384 dict->n_children = 0;
1385 return (AST *) dict;
1388 if ((first = parse (stream, app, error)) == NULL)
1391 ast_array_append (&dict->keys, &n_keys, first);
1393 only_one = token_stream_consume (stream, ",");
1395 !token_stream_require (stream, ":",
1396 " or ',' to follow dictionary entry key",
1400 if ((first = parse (stream, app, error)) == NULL)
1403 ast_array_append (&dict->values, &n_values, first);
1407 if (!token_stream_require (stream, "}", " at end of dictionary entry",
1411 g_assert (n_keys == 1 && n_values == 1);
1412 dict->n_children = -1;
1414 return (AST *) dict;
1417 while (!token_stream_consume (stream, "}"))
1421 if (!token_stream_require (stream, ",",
1422 " or '}' to follow dictionary entry", error))
1425 child = parse (stream, app, error);
1430 ast_array_append (&dict->keys, &n_keys, child);
1432 if (!token_stream_require (stream, ":",
1433 " to follow dictionary entry key", error))
1436 child = parse (stream, app, error);
1441 ast_array_append (&dict->values, &n_values, child);
1444 g_assert (n_keys == n_values);
1445 dict->n_children = n_keys;
1447 return (AST *) dict;
1450 ast_array_free (dict->keys, n_keys);
1451 ast_array_free (dict->values, n_values);
1452 g_slice_free (Dictionary, dict);
1464 string_get_pattern (AST *ast,
1467 return g_strdup ("MS");
1471 string_get_value (AST *ast,
1472 const GVariantType *type,
1475 String *string = (String *) ast;
1477 if (g_variant_type_equal (type, G_VARIANT_TYPE_STRING))
1478 return g_variant_new_string (string->string);
1480 else if (g_variant_type_equal (type, G_VARIANT_TYPE_OBJECT_PATH))
1482 if (!g_variant_is_object_path (string->string))
1484 ast_set_error (ast, error, NULL,
1485 G_VARIANT_PARSE_ERROR_INVALID_OBJECT_PATH,
1486 "not a valid object path");
1490 return g_variant_new_object_path (string->string);
1493 else if (g_variant_type_equal (type, G_VARIANT_TYPE_SIGNATURE))
1495 if (!g_variant_is_signature (string->string))
1497 ast_set_error (ast, error, NULL,
1498 G_VARIANT_PARSE_ERROR_INVALID_SIGNATURE,
1499 "not a valid signature");
1503 return g_variant_new_signature (string->string);
1507 return ast_type_error (ast, type, error);
1511 string_free (AST *ast)
1513 String *string = (String *) ast;
1515 g_free (string->string);
1516 g_slice_free (String, string);
1520 unicode_unescape (const gchar *src,
1534 g_assert (length < sizeof (buffer));
1535 strncpy (buffer, src + *src_ofs, length);
1536 buffer[length] = '\0';
1538 value = g_ascii_strtoull (buffer, &end, 0x10);
1540 if (value == 0 || end != buffer + length)
1542 parser_set_error (error, ref, NULL,
1543 G_VARIANT_PARSE_ERROR_INVALID_CHARACTER,
1544 "invalid %d-character unicode escape", length);
1548 g_assert (value <= G_MAXUINT32);
1550 *dest_ofs += g_unichar_to_utf8 (value, dest + *dest_ofs);
1557 string_parse (TokenStream *stream,
1561 static const ASTClass string_class = {
1563 maybe_wrapper, string_get_value,
1574 token_stream_start_ref (stream, &ref);
1575 token = token_stream_get (stream);
1576 token_stream_end_ref (stream, &ref);
1577 length = strlen (token);
1580 str = g_malloc (length);
1581 g_assert (quote == '"' || quote == '\'');
1584 while (token[i] != quote)
1588 parser_set_error (error, &ref, NULL,
1589 G_VARIANT_PARSE_ERROR_UNTERMINATED_STRING_CONSTANT,
1590 "unterminated string constant");
1599 parser_set_error (error, &ref, NULL,
1600 G_VARIANT_PARSE_ERROR_UNTERMINATED_STRING_CONSTANT,
1601 "unterminated string constant");
1607 if (!unicode_unescape (token, &i, str, &j, 4, &ref, error))
1616 if (!unicode_unescape (token, &i, str, &j, 8, &ref, error))
1624 case 'a': str[j++] = '\a'; i++; continue;
1625 case 'b': str[j++] = '\b'; i++; continue;
1626 case 'f': str[j++] = '\f'; i++; continue;
1627 case 'n': str[j++] = '\n'; i++; continue;
1628 case 'r': str[j++] = '\r'; i++; continue;
1629 case 't': str[j++] = '\t'; i++; continue;
1630 case 'v': str[j++] = '\v'; i++; continue;
1631 case '\n': i++; continue;
1635 str[j++] = token[i++];
1640 string = g_slice_new (String);
1641 string->ast.class = &string_class;
1642 string->string = str;
1644 token_stream_next (stream);
1646 return (AST *) string;
1656 bytestring_get_pattern (AST *ast,
1659 return g_strdup ("May");
1663 bytestring_get_value (AST *ast,
1664 const GVariantType *type,
1667 ByteString *string = (ByteString *) ast;
1669 if (!g_variant_type_equal (type, G_VARIANT_TYPE_BYTESTRING))
1670 return ast_type_error (ast, type, error);
1672 return g_variant_new_bytestring (string->string);
1676 bytestring_free (AST *ast)
1678 ByteString *string = (ByteString *) ast;
1680 g_free (string->string);
1681 g_slice_free (ByteString, string);
1685 bytestring_parse (TokenStream *stream,
1689 static const ASTClass bytestring_class = {
1690 bytestring_get_pattern,
1691 maybe_wrapper, bytestring_get_value,
1702 token_stream_start_ref (stream, &ref);
1703 token = token_stream_get (stream);
1704 token_stream_end_ref (stream, &ref);
1705 g_assert (token[0] == 'b');
1706 length = strlen (token);
1709 str = g_malloc (length);
1710 g_assert (quote == '"' || quote == '\'');
1713 while (token[i] != quote)
1717 parser_set_error (error, &ref, NULL,
1718 G_VARIANT_PARSE_ERROR_UNTERMINATED_STRING_CONSTANT,
1719 "unterminated string constant");
1727 parser_set_error (error, &ref, NULL,
1728 G_VARIANT_PARSE_ERROR_UNTERMINATED_STRING_CONSTANT,
1729 "unterminated string constant");
1733 case '0': case '1': case '2': case '3':
1734 case '4': case '5': case '6': case '7':
1736 /* up to 3 characters */
1737 guchar val = token[i++] - '0';
1739 if ('0' <= token[i] && token[i] < '8')
1740 val = (val << 3) | (token[i++] - '0');
1742 if ('0' <= token[i] && token[i] < '8')
1743 val = (val << 3) | (token[i++] - '0');
1749 case 'a': str[j++] = '\a'; i++; continue;
1750 case 'b': str[j++] = '\b'; i++; continue;
1751 case 'f': str[j++] = '\f'; i++; continue;
1752 case 'n': str[j++] = '\n'; i++; continue;
1753 case 'r': str[j++] = '\r'; i++; continue;
1754 case 't': str[j++] = '\t'; i++; continue;
1755 case 'v': str[j++] = '\v'; i++; continue;
1756 case '\n': i++; continue;
1760 str[j++] = token[i++];
1765 string = g_slice_new (ByteString);
1766 string->ast.class = &bytestring_class;
1767 string->string = str;
1769 token_stream_next (stream);
1771 return (AST *) string;
1782 number_get_pattern (AST *ast,
1785 Number *number = (Number *) ast;
1787 if (strchr (number->token, '.') ||
1788 (!g_str_has_prefix (number->token, "0x") && strchr (number->token, 'e')) ||
1789 strstr (number->token, "inf") ||
1790 strstr (number->token, "nan"))
1791 return g_strdup ("Md");
1793 return g_strdup ("MN");
1797 number_overflow (AST *ast,
1798 const GVariantType *type,
1801 ast_set_error (ast, error, NULL,
1802 G_VARIANT_PARSE_ERROR_NUMBER_OUT_OF_RANGE,
1803 "number out of range for type '%c'",
1804 g_variant_type_peek_string (type)[0]);
1809 number_get_value (AST *ast,
1810 const GVariantType *type,
1813 Number *number = (Number *) ast;
1821 token = number->token;
1823 if (g_variant_type_equal (type, G_VARIANT_TYPE_DOUBLE))
1828 dbl_val = g_ascii_strtod (token, &end);
1829 if (dbl_val != 0.0 && errno == ERANGE)
1831 ast_set_error (ast, error, NULL,
1832 G_VARIANT_PARSE_ERROR_NUMBER_TOO_BIG,
1833 "number too big for any type");
1837 /* silence uninitialised warnings... */
1844 negative = token[0] == '-';
1845 if (token[0] == '-')
1849 abs_val = g_ascii_strtoull (token, &end, 0);
1850 if (abs_val == G_MAXUINT64 && errno == ERANGE)
1852 ast_set_error (ast, error, NULL,
1853 G_VARIANT_PARSE_ERROR_NUMBER_TOO_BIG,
1854 "integer too big for any type");
1861 /* silence uninitialised warning... */
1869 ref = ast->source_ref;
1870 ref.start += end - number->token;
1871 ref.end = ref.start + 1;
1873 parser_set_error (error, &ref, NULL,
1874 G_VARIANT_PARSE_ERROR_INVALID_CHARACTER,
1875 "invalid character in number");
1880 return g_variant_new_double (dbl_val);
1882 switch (*g_variant_type_peek_string (type))
1885 if (negative || abs_val > G_MAXUINT8)
1886 return number_overflow (ast, type, error);
1887 return g_variant_new_byte (abs_val);
1890 if (abs_val - negative > G_MAXINT16)
1891 return number_overflow (ast, type, error);
1892 return g_variant_new_int16 (negative ? -abs_val : abs_val);
1895 if (negative || abs_val > G_MAXUINT16)
1896 return number_overflow (ast, type, error);
1897 return g_variant_new_uint16 (abs_val);
1900 if (abs_val - negative > G_MAXINT32)
1901 return number_overflow (ast, type, error);
1902 return g_variant_new_int32 (negative ? -abs_val : abs_val);
1905 if (negative || abs_val > G_MAXUINT32)
1906 return number_overflow (ast, type, error);
1907 return g_variant_new_uint32 (abs_val);
1910 if (abs_val - negative > G_MAXINT64)
1911 return number_overflow (ast, type, error);
1912 return g_variant_new_int64 (negative ? -abs_val : abs_val);
1916 return number_overflow (ast, type, error);
1917 return g_variant_new_uint64 (abs_val);
1920 if (abs_val - negative > G_MAXINT32)
1921 return number_overflow (ast, type, error);
1922 return g_variant_new_handle (negative ? -abs_val : abs_val);
1925 return ast_type_error (ast, type, error);
1930 number_free (AST *ast)
1932 Number *number = (Number *) ast;
1934 g_free (number->token);
1935 g_slice_free (Number, number);
1939 number_parse (TokenStream *stream,
1943 static const ASTClass number_class = {
1945 maybe_wrapper, number_get_value,
1950 number = g_slice_new (Number);
1951 number->ast.class = &number_class;
1952 number->token = token_stream_get (stream);
1953 token_stream_next (stream);
1955 return (AST *) number;
1965 boolean_get_pattern (AST *ast,
1968 return g_strdup ("Mb");
1972 boolean_get_value (AST *ast,
1973 const GVariantType *type,
1976 Boolean *boolean = (Boolean *) ast;
1978 if (!g_variant_type_equal (type, G_VARIANT_TYPE_BOOLEAN))
1979 return ast_type_error (ast, type, error);
1981 return g_variant_new_boolean (boolean->value);
1985 boolean_free (AST *ast)
1987 Boolean *boolean = (Boolean *) ast;
1989 g_slice_free (Boolean, boolean);
1993 boolean_new (gboolean value)
1995 static const ASTClass boolean_class = {
1996 boolean_get_pattern,
1997 maybe_wrapper, boolean_get_value,
2002 boolean = g_slice_new (Boolean);
2003 boolean->ast.class = &boolean_class;
2004 boolean->value = value;
2006 return (AST *) boolean;
2017 positional_get_pattern (AST *ast,
2020 Positional *positional = (Positional *) ast;
2022 return g_strdup (g_variant_get_type_string (positional->value));
2026 positional_get_value (AST *ast,
2027 const GVariantType *type,
2030 Positional *positional = (Positional *) ast;
2033 g_assert (positional->value != NULL);
2035 if G_UNLIKELY (!g_variant_is_of_type (positional->value, type))
2036 return ast_type_error (ast, type, error);
2038 /* NOTE: if _get is called more than once then
2039 * things get messed up with respect to floating refs.
2041 * fortunately, this function should only ever get called once.
2043 g_assert (positional->value != NULL);
2044 value = positional->value;
2045 positional->value = NULL;
2051 positional_free (AST *ast)
2053 Positional *positional = (Positional *) ast;
2055 /* if positional->value is set, just leave it.
2056 * memory management doesn't matter in case of programmer error.
2058 g_slice_free (Positional, positional);
2062 positional_parse (TokenStream *stream,
2066 static const ASTClass positional_class = {
2067 positional_get_pattern,
2068 positional_get_value, NULL,
2071 Positional *positional;
2072 const gchar *endptr;
2075 token = token_stream_get (stream);
2076 g_assert (token[0] == '%');
2078 positional = g_slice_new (Positional);
2079 positional->ast.class = &positional_class;
2080 positional->value = g_variant_new_va (token + 1, &endptr, app);
2082 if (*endptr || positional->value == NULL)
2084 token_stream_set_error (stream, error, TRUE,
2085 G_VARIANT_PARSE_ERROR_INVALID_FORMAT_STRING,
2086 "invalid GVariant format string");
2087 /* memory management doesn't matter in case of programmer error. */
2091 token_stream_next (stream);
2094 return (AST *) positional;
2106 typedecl_get_pattern (AST *ast,
2109 TypeDecl *decl = (TypeDecl *) ast;
2111 return g_variant_type_dup_string (decl->type);
2115 typedecl_get_value (AST *ast,
2116 const GVariantType *type,
2119 TypeDecl *decl = (TypeDecl *) ast;
2121 return ast_get_value (decl->child, type, error);
2125 typedecl_free (AST *ast)
2127 TypeDecl *decl = (TypeDecl *) ast;
2129 ast_free (decl->child);
2130 g_variant_type_free (decl->type);
2131 g_slice_free (TypeDecl, decl);
2135 typedecl_parse (TokenStream *stream,
2139 static const ASTClass typedecl_class = {
2140 typedecl_get_pattern,
2141 typedecl_get_value, NULL,
2148 if (token_stream_peek (stream, '@'))
2152 token = token_stream_get (stream);
2154 if (!g_variant_type_string_is_valid (token + 1))
2156 token_stream_set_error (stream, error, TRUE,
2157 G_VARIANT_PARSE_ERROR_INVALID_TYPE_STRING,
2158 "invalid type declaration");
2164 type = g_variant_type_new (token + 1);
2166 if (!g_variant_type_is_definite (type))
2168 token_stream_set_error (stream, error, TRUE,
2169 G_VARIANT_PARSE_ERROR_DEFINITE_TYPE_EXPECTED,
2170 "type declarations must be definite");
2171 g_variant_type_free (type);
2177 token_stream_next (stream);
2182 if (token_stream_consume (stream, "boolean"))
2183 type = g_variant_type_copy (G_VARIANT_TYPE_BOOLEAN);
2185 else if (token_stream_consume (stream, "byte"))
2186 type = g_variant_type_copy (G_VARIANT_TYPE_BYTE);
2188 else if (token_stream_consume (stream, "int16"))
2189 type = g_variant_type_copy (G_VARIANT_TYPE_INT16);
2191 else if (token_stream_consume (stream, "uint16"))
2192 type = g_variant_type_copy (G_VARIANT_TYPE_UINT16);
2194 else if (token_stream_consume (stream, "int32"))
2195 type = g_variant_type_copy (G_VARIANT_TYPE_INT32);
2197 else if (token_stream_consume (stream, "handle"))
2198 type = g_variant_type_copy (G_VARIANT_TYPE_HANDLE);
2200 else if (token_stream_consume (stream, "uint32"))
2201 type = g_variant_type_copy (G_VARIANT_TYPE_UINT32);
2203 else if (token_stream_consume (stream, "int64"))
2204 type = g_variant_type_copy (G_VARIANT_TYPE_INT64);
2206 else if (token_stream_consume (stream, "uint64"))
2207 type = g_variant_type_copy (G_VARIANT_TYPE_UINT64);
2209 else if (token_stream_consume (stream, "double"))
2210 type = g_variant_type_copy (G_VARIANT_TYPE_DOUBLE);
2212 else if (token_stream_consume (stream, "string"))
2213 type = g_variant_type_copy (G_VARIANT_TYPE_STRING);
2215 else if (token_stream_consume (stream, "objectpath"))
2216 type = g_variant_type_copy (G_VARIANT_TYPE_OBJECT_PATH);
2218 else if (token_stream_consume (stream, "signature"))
2219 type = g_variant_type_copy (G_VARIANT_TYPE_SIGNATURE);
2223 token_stream_set_error (stream, error, TRUE,
2224 G_VARIANT_PARSE_ERROR_UNKNOWN_KEYWORD,
2230 if ((child = parse (stream, app, error)) == NULL)
2232 g_variant_type_free (type);
2236 decl = g_slice_new (TypeDecl);
2237 decl->ast.class = &typedecl_class;
2239 decl->child = child;
2241 return (AST *) decl;
2245 parse (TokenStream *stream,
2249 SourceRef source_ref;
2252 token_stream_prepare (stream);
2253 token_stream_start_ref (stream, &source_ref);
2255 if (token_stream_peek (stream, '['))
2256 result = array_parse (stream, app, error);
2258 else if (token_stream_peek (stream, '('))
2259 result = tuple_parse (stream, app, error);
2261 else if (token_stream_peek (stream, '<'))
2262 result = variant_parse (stream, app, error);
2264 else if (token_stream_peek (stream, '{'))
2265 result = dictionary_parse (stream, app, error);
2267 else if (app && token_stream_peek (stream, '%'))
2268 result = positional_parse (stream, app, error);
2270 else if (token_stream_consume (stream, "true"))
2271 result = boolean_new (TRUE);
2273 else if (token_stream_consume (stream, "false"))
2274 result = boolean_new (FALSE);
2276 else if (token_stream_is_numeric (stream) ||
2277 token_stream_peek_string (stream, "inf") ||
2278 token_stream_peek_string (stream, "nan"))
2279 result = number_parse (stream, app, error);
2281 else if (token_stream_peek (stream, 'n') ||
2282 token_stream_peek (stream, 'j'))
2283 result = maybe_parse (stream, app, error);
2285 else if (token_stream_peek (stream, '@') ||
2286 token_stream_is_keyword (stream))
2287 result = typedecl_parse (stream, app, error);
2289 else if (token_stream_peek (stream, '\'') ||
2290 token_stream_peek (stream, '"'))
2291 result = string_parse (stream, app, error);
2293 else if (token_stream_peek2 (stream, 'b', '\'') ||
2294 token_stream_peek2 (stream, 'b', '"'))
2295 result = bytestring_parse (stream, app, error);
2299 token_stream_set_error (stream, error, FALSE,
2300 G_VARIANT_PARSE_ERROR_VALUE_EXPECTED,
2307 token_stream_end_ref (stream, &source_ref);
2308 result->source_ref = source_ref;
2316 * @type: (allow-none): a #GVariantType, or %NULL
2317 * @text: a string containing a GVariant in text form
2318 * @limit: (allow-none): a pointer to the end of @text, or %NULL
2319 * @endptr: (allow-none): a location to store the end pointer, or %NULL
2320 * @error: (allow-none): a pointer to a %NULL #GError pointer, or %NULL
2322 * Parses a #GVariant from a text representation.
2324 * A single #GVariant is parsed from the content of @text.
2326 * The format is described <link linkend='gvariant-text'>here</link>.
2328 * The memory at @limit will never be accessed and the parser behaves as
2329 * if the character at @limit is the nul terminator. This has the
2330 * effect of bounding @text.
2332 * If @endptr is non-%NULL then @text is permitted to contain data
2333 * following the value that this function parses and @endptr will be
2334 * updated to point to the first character past the end of the text
2335 * parsed by this function. If @endptr is %NULL and there is extra data
2336 * then an error is returned.
2338 * If @type is non-%NULL then the value will be parsed to have that
2339 * type. This may result in additional parse errors (in the case that
2340 * the parsed value doesn't fit the type) but may also result in fewer
2341 * errors (in the case that the type would have been ambiguous, such as
2342 * with empty arrays).
2344 * In the event that the parsing is successful, the resulting #GVariant
2347 * In case of any error, %NULL will be returned. If @error is non-%NULL
2348 * then it will be set to reflect the error that occurred.
2350 * Officially, the language understood by the parser is "any string
2351 * produced by g_variant_print()".
2353 * Returns: a reference to a #GVariant, or %NULL
2356 g_variant_parse (const GVariantType *type,
2359 const gchar **endptr,
2362 TokenStream stream = { 0, };
2363 GVariant *result = NULL;
2366 g_return_val_if_fail (text != NULL, NULL);
2367 g_return_val_if_fail (text == limit || text != NULL, NULL);
2369 stream.start = text;
2370 stream.stream = text;
2373 if ((ast = parse (&stream, NULL, error)))
2376 result = ast_resolve (ast, error);
2378 result = ast_get_value (ast, type, error);
2382 g_variant_ref_sink (result);
2386 while (stream.stream != limit &&
2387 g_ascii_isspace (*stream.stream))
2390 if (stream.stream != limit && *stream.stream != '\0')
2392 SourceRef ref = { stream.stream - text,
2393 stream.stream - text };
2395 parser_set_error (error, &ref, NULL,
2396 G_VARIANT_PARSE_ERROR_INPUT_NOT_AT_END,
2397 "expected end of input");
2398 g_variant_unref (result);
2404 *endptr = stream.stream;
2414 * g_variant_new_parsed_va:
2415 * @format: a text format #GVariant
2416 * @app: a pointer to a #va_list
2418 * Parses @format and returns the result.
2420 * This is the version of g_variant_new_parsed() intended to be used
2423 * The return value will be floating if it was a newly created GVariant
2424 * instance. In the case that @format simply specified the collection
2425 * of a #GVariant pointer (eg: @format was "%*") then the collected
2426 * #GVariant pointer will be returned unmodified, without adding any
2427 * additional references.
2429 * In order to behave correctly in all cases it is necessary for the
2430 * calling function to g_variant_ref_sink() the return result before
2431 * returning control to the user that originally provided the pointer.
2432 * At this point, the caller will have their own full reference to the
2433 * result. This can also be done by adding the result to a container,
2434 * or by passing it to another g_variant_new() call.
2436 * Returns: a new, usually floating, #GVariant
2439 g_variant_new_parsed_va (const gchar *format,
2442 TokenStream stream = { 0, };
2443 GVariant *result = NULL;
2444 GError *error = NULL;
2447 g_return_val_if_fail (format != NULL, NULL);
2448 g_return_val_if_fail (app != NULL, NULL);
2450 stream.start = format;
2451 stream.stream = format;
2454 if ((ast = parse (&stream, app, &error)))
2456 result = ast_resolve (ast, &error);
2461 g_error ("g_variant_new_parsed: %s", error->message);
2464 g_error ("g_variant_new_parsed: trailing text after value");
2470 * g_variant_new_parsed:
2471 * @format: a text format #GVariant
2472 * @...: arguments as per @format
2474 * Parses @format and returns the result.
2476 * @format must be a text format #GVariant with one extension: at any
2477 * point that a value may appear in the text, a '%' character followed
2478 * by a GVariant format string (as per g_variant_new()) may appear. In
2479 * that case, the same arguments are collected from the argument list as
2480 * g_variant_new() would have collected.
2482 * Consider this simple example:
2484 * g_variant_new_parsed ("[('one', 1), ('two', %i), (%s, 3)]", 2, "three");
2487 * In the example, the variable argument parameters are collected and
2488 * filled in as if they were part of the original string to produce the
2491 * [('one', 1), ('two', 2), ('three', 3)]
2494 * This function is intended only to be used with @format as a string
2495 * literal. Any parse error is fatal to the calling process. If you
2496 * want to parse data from untrusted sources, use g_variant_parse().
2498 * You may not use this function to return, unmodified, a single
2499 * #GVariant pointer from the argument list. ie: @format may not solely
2500 * be anything along the lines of "%*", "%?", "\%r", or anything starting
2503 * Returns: a new floating #GVariant instance
2506 g_variant_new_parsed (const gchar *format,
2512 va_start (ap, format);
2513 result = g_variant_new_parsed_va (format, &ap);
2520 * g_variant_builder_add_parsed:
2521 * @builder: a #GVariantBuilder
2522 * @format: a text format #GVariant
2523 * @...: arguments as per @format
2525 * Adds to a #GVariantBuilder.
2527 * This call is a convenience wrapper that is exactly equivalent to
2528 * calling g_variant_new_parsed() followed by
2529 * g_variant_builder_add_value().
2531 * This function might be used as follows:
2535 * make_pointless_dictionary (void)
2537 * GVariantBuilder builder;
2540 * g_variant_builder_init (&builder, G_VARIANT_TYPE_ARRAY);
2541 * g_variant_builder_add_parsed (&builder, "{'width', <%i>}", 600);
2542 * g_variant_builder_add_parsed (&builder, "{'title', <%s>}", "foo");
2543 * g_variant_builder_add_parsed (&builder, "{'transparency', <0.5>}");
2544 * return g_variant_builder_end (&builder);
2551 g_variant_builder_add_parsed (GVariantBuilder *builder,
2552 const gchar *format,
2557 va_start (ap, format);
2558 g_variant_builder_add_value (builder, g_variant_new_parsed_va (format, &ap));
2563 parse_num (const gchar *num,
2570 bignum = g_ascii_strtoll (num, &endptr, 10);
2572 if (endptr != limit)
2575 if (bignum < 0 || bignum > G_MAXINT)
2584 add_last_line (GString *err,
2587 const gchar *last_nl;
2591 /* This is an error at the end of input. If we have a file
2592 * with newlines, that's probably the empty string after the
2593 * last newline, which is not the most useful thing to show.
2595 * Instead, show the last line of non-whitespace that we have
2596 * and put the pointer at the end of it.
2598 chomped = g_strchomp (g_strdup (str));
2599 last_nl = strrchr (chomped, '\n');
2600 if (last_nl == NULL)
2605 /* Print the last line like so:
2610 g_string_append (err, " ");
2612 g_string_append (err, last_nl);
2614 g_string_append (err, "(empty input)");
2615 g_string_append (err, "\n ");
2616 for (i = 0; last_nl[i]; i++)
2617 g_string_append_c (err, ' ');
2618 g_string_append (err, "^\n");
2623 add_lines_from_range (GString *err,
2625 const gchar *start1,
2627 const gchar *start2,
2630 while (str < end1 || str < end2)
2634 nl = str + strcspn (str, "\n");
2636 if ((start1 < nl && str < end1) || (start2 < nl && str < end2))
2640 /* We're going to print this line */
2641 g_string_append (err, " ");
2642 g_string_append_len (err, str, nl - str);
2643 g_string_append (err, "\n ");
2645 /* And add underlines... */
2646 for (s = str; s < nl; s++)
2648 if ((start1 <= s && s < end1) || (start2 <= s && s < end2))
2649 g_string_append_c (err, '^');
2651 g_string_append_c (err, ' ');
2653 g_string_append_c (err, '\n');
2664 * g_variant_parse_error_print_context:
2665 * @error: a #GError from the #GVariantParseError domain
2666 * @source_str: the string that was given to the parser
2668 * Pretty-prints a message showing the context of a #GVariant parse
2669 * error within the string for which parsing was attempted.
2671 * The resulting string is suitable for output to the console or other
2672 * monospace media where newlines are treated in the usual way.
2674 * The message will typically look something like one of the following:
2677 * unterminated string constant:
2685 * unable to find a common type:
2690 * The format of the message may change in a future version.
2692 * @error must have come from a failed attempt to g_variant_parse() and
2693 * @source_str must be exactly the same string that caused the error.
2694 * If @source_str was not nul-terminated when you passed it to
2695 * g_variant_parse() then you must add nul termination before using this
2698 * Returns: (transfer full): the printed message
2703 g_variant_parse_error_print_context (GError *error,
2704 const gchar *source_str)
2706 const gchar *colon, *dash, *comma;
2707 gboolean success = FALSE;
2710 g_return_val_if_fail (error->domain == G_VARIANT_PARSE_ERROR, FALSE);
2712 /* We can only have a limited number of possible types of ranges
2713 * emitted from the parser:
2715 * - a: -- usually errors from the tokeniser (eof, invalid char, etc.)
2716 * - a-b: -- usually errors from handling one single token
2717 * - a-b,c-d: -- errors involving two tokens (ie: type inferencing)
2719 * We never see, for example "a,c".
2722 colon = strchr (error->message, ':');
2723 dash = strchr (error->message, '-');
2724 comma = strchr (error->message, ',');
2729 err = g_string_new (colon + 1);
2730 g_string_append (err, ":\n");
2732 if (dash == NULL || colon < dash)
2736 /* we have a single point */
2737 if (!parse_num (error->message, colon, &point))
2740 if (point >= strlen (source_str))
2741 /* the error is at the end of the input */
2742 add_last_line (err, source_str);
2744 /* otherwise just treat it as a error at a thin range */
2745 add_lines_from_range (err, source_str, source_str + point, source_str + point + 1, NULL, NULL);
2749 /* We have one or two ranges... */
2750 if (comma && comma < colon)
2752 gint start1, end1, start2, end2;
2756 dash2 = strchr (comma, '-');
2758 if (!parse_num (error->message, dash, &start1) || !parse_num (dash + 1, comma, &end1) ||
2759 !parse_num (comma + 1, dash2, &start2) || !parse_num (dash2 + 1, colon, &end2))
2762 add_lines_from_range (err, source_str,
2763 source_str + start1, source_str + end1,
2764 source_str + start2, source_str + end2);
2771 if (!parse_num (error->message, dash, &start) || !parse_num (dash + 1, colon, &end))
2774 add_lines_from_range (err, source_str, source_str + start, source_str + end, NULL, NULL);
2781 return g_string_free (err, !success);