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 * g_variant_parser_get_error_quark:
77 * Deprecated: Use g_variant_parse_error_quark() instead.
80 g_variant_parser_get_error_quark (void)
82 return g_variant_parse_error_quark ();
92 parser_set_error_va (GError **error,
99 GString *msg = g_string_new (NULL);
101 if (location->start == location->end)
102 g_string_append_printf (msg, "%d", location->start);
104 g_string_append_printf (msg, "%d-%d", location->start, location->end);
108 g_assert (other->start != other->end);
109 g_string_append_printf (msg, ",%d-%d", other->start, other->end);
111 g_string_append_c (msg, ':');
113 g_string_append_vprintf (msg, format, ap);
114 g_set_error_literal (error, G_VARIANT_PARSE_ERROR, code, msg->str);
115 g_string_free (msg, TRUE);
120 parser_set_error (GError **error,
129 va_start (ap, format);
130 parser_set_error_va (error, location, other, code, format, ap);
146 token_stream_set_error (TokenStream *stream,
156 ref.start = stream->this - stream->start;
159 ref.end = stream->stream - stream->start;
163 va_start (ap, format);
164 parser_set_error_va (error, &ref, NULL, code, format, ap);
169 token_stream_prepare (TokenStream *stream)
174 if (stream->this != NULL)
177 while (stream->stream != stream->end && g_ascii_isspace (*stream->stream))
180 if (stream->stream == stream->end || *stream->stream == '\0')
182 stream->this = stream->stream;
186 switch (stream->stream[0])
188 case '-': case '+': case '.': case '0': case '1': case '2':
189 case '3': case '4': case '5': case '6': case '7': case '8':
191 for (end = stream->stream; end != stream->end; end++)
192 if (!g_ascii_isalnum (*end) &&
193 *end != '-' && *end != '+' && *end != '.')
198 if (stream->stream[1] == '\'' || stream->stream[1] == '"')
200 for (end = stream->stream + 2; end != stream->end; end++)
201 if (*end == stream->stream[1] || *end == '\0' ||
202 (*end == '\\' && (++end == stream->end || *end == '\0')))
205 if (end != stream->end && *end)
212 case 'a': /* 'b' */ case 'c': case 'd': case 'e': case 'f':
213 case 'g': case 'h': case 'i': case 'j': case 'k': case 'l':
214 case 'm': case 'n': case 'o': case 'p': case 'q': case 'r':
215 case 's': case 't': case 'u': case 'v': case 'w': case 'x':
217 for (end = stream->stream; end != stream->end; end++)
218 if (!g_ascii_isalnum (*end))
223 for (end = stream->stream + 1; end != stream->end; end++)
224 if (*end == stream->stream[0] || *end == '\0' ||
225 (*end == '\\' && (++end == stream->end || *end == '\0')))
228 if (end != stream->end && *end)
233 /* stop at the first space, comma, colon or unmatched bracket.
234 * deals nicely with cases like (%i, %i) or {%i: %i}.
235 * Also: ] and > are never in format strings.
237 for (end = stream->stream + 1;
238 end != stream->end && *end != ',' &&
239 *end != ':' && *end != '>' && *end != ']' && !g_ascii_isspace (*end);
242 if (*end == '(' || *end == '{')
245 else if ((*end == ')' || *end == '}') && !brackets--)
251 end = stream->stream + 1;
255 stream->this = stream->stream;
256 stream->stream = end;
262 token_stream_next (TokenStream *stream)
268 token_stream_peek (TokenStream *stream,
271 if (!token_stream_prepare (stream))
274 return stream->this[0] == first_char;
278 token_stream_peek2 (TokenStream *stream,
282 if (!token_stream_prepare (stream))
285 return stream->this[0] == first_char &&
286 stream->this[1] == second_char;
290 token_stream_is_keyword (TokenStream *stream)
292 if (!token_stream_prepare (stream))
295 return g_ascii_isalpha (stream->this[0]) &&
296 g_ascii_isalpha (stream->this[1]);
300 token_stream_is_numeric (TokenStream *stream)
302 if (!token_stream_prepare (stream))
305 return (g_ascii_isdigit (stream->this[0]) ||
306 stream->this[0] == '-' ||
307 stream->this[0] == '+' ||
308 stream->this[0] == '.');
312 token_stream_peek_string (TokenStream *stream,
315 gint length = strlen (token);
317 return token_stream_prepare (stream) &&
318 stream->stream - stream->this == length &&
319 memcmp (stream->this, token, length) == 0;
323 token_stream_consume (TokenStream *stream,
326 if (!token_stream_peek_string (stream, token))
329 token_stream_next (stream);
334 token_stream_require (TokenStream *stream,
336 const gchar *purpose,
340 if (!token_stream_consume (stream, token))
342 token_stream_set_error (stream, error, FALSE,
343 G_VARIANT_PARSE_ERROR_UNEXPECTED_TOKEN,
344 "expected '%s'%s", token, purpose);
352 token_stream_assert (TokenStream *stream,
355 gboolean correct_token;
357 correct_token = token_stream_consume (stream, token);
358 g_assert (correct_token);
362 token_stream_get (TokenStream *stream)
366 if (!token_stream_prepare (stream))
369 result = g_strndup (stream->this, stream->stream - stream->this);
375 token_stream_start_ref (TokenStream *stream,
378 token_stream_prepare (stream);
379 ref->start = stream->this - stream->start;
383 token_stream_end_ref (TokenStream *stream,
386 ref->end = stream->stream - stream->start;
390 pattern_copy (gchar **out,
395 while (**in == 'a' || **in == 'm' || **in == 'M')
396 *(*out)++ = *(*in)++;
400 if (**in == '(' || **in == '{')
403 else if (**in == ')' || **in == '}')
406 *(*out)++ = *(*in)++;
412 pattern_coalesce (const gchar *left,
418 /* the length of the output is loosely bound by the sum of the input
419 * lengths, not simply the greater of the two lengths.
421 * (*(iii)) + ((iii)*) ((iii)(iii))
425 out = result = g_malloc (strlen (left) + strlen (right));
427 while (*left && *right)
437 const gchar **one = &left, **the_other = &right;
440 if (**one == '*' && **the_other != ')')
442 pattern_copy (&out, the_other);
446 else if (**one == 'M' && **the_other == 'm')
448 *out++ = *(*the_other)++;
451 else if (**one == 'M' && **the_other != 'm')
456 else if (**one == 'N' && strchr ("ynqiuxthd", **the_other))
458 *out++ = *(*the_other)++;
462 else if (**one == 'S' && strchr ("sog", **the_other))
464 *out++ = *(*the_other)++;
468 else if (one == &left)
470 one = &right, the_other = &left;
490 typedef struct _AST AST;
491 typedef gchar * (*get_pattern_func) (AST *ast,
493 typedef GVariant * (*get_value_func) (AST *ast,
494 const GVariantType *type,
496 typedef GVariant * (*get_base_value_func) (AST *ast,
497 const GVariantType *type,
499 typedef void (*free_func) (AST *ast);
503 gchar * (* get_pattern) (AST *ast,
505 GVariant * (* get_value) (AST *ast,
506 const GVariantType *type,
508 GVariant * (* get_base_value) (AST *ast,
509 const GVariantType *type,
511 void (* free) (AST *ast);
516 const ASTClass *class;
517 SourceRef source_ref;
521 ast_get_pattern (AST *ast,
524 return ast->class->get_pattern (ast, error);
528 ast_get_value (AST *ast,
529 const GVariantType *type,
532 return ast->class->get_value (ast, type, error);
538 ast->class->free (ast);
543 ast_set_error (AST *ast,
552 va_start (ap, format);
553 parser_set_error_va (error, &ast->source_ref,
554 other_ast ? & other_ast->source_ref : NULL,
561 ast_type_error (AST *ast,
562 const GVariantType *type,
567 typestr = g_variant_type_dup_string (type);
568 ast_set_error (ast, error, NULL,
569 G_VARIANT_PARSE_ERROR_TYPE_ERROR,
570 "can not parse as value of type '%s'",
578 ast_resolve (AST *ast,
585 pattern = ast_get_pattern (ast, error);
590 /* choose reasonable defaults
592 * 1) favour non-maybe values where possible
593 * 2) default type for strings is 's'
594 * 3) default type for integers is 'i'
596 for (i = 0; pattern[i]; i++)
600 ast_set_error (ast, error, NULL,
601 G_VARIANT_PARSE_ERROR_CANNOT_INFER_TYPE,
602 "unable to infer type");
618 pattern[j++] = pattern[i];
623 value = ast_get_value (ast, G_VARIANT_TYPE (pattern), error);
630 static AST *parse (TokenStream *stream,
635 ast_array_append (AST ***array,
639 if ((*n_items & (*n_items - 1)) == 0)
640 *array = g_renew (AST *, *array, *n_items ? 2 ** n_items : 1);
642 (*array)[(*n_items)++] = ast;
646 ast_array_free (AST **array,
651 for (i = 0; i < n_items; i++)
657 ast_array_get_pattern (AST **array,
664 pattern = ast_get_pattern (array[0], error);
669 for (i = 1; i < n_items; i++)
673 tmp = ast_get_pattern (array[i], error);
681 merged = pattern_coalesce (pattern, tmp);
686 /* set coalescence implies pairwise coalescence (i think).
687 * we should therefore be able to trace the failure to a single
698 /* if 'j' reaches 'i' then we failed to find the pair */
701 tmp2 = ast_get_pattern (array[j], NULL);
702 g_assert (tmp2 != NULL);
704 m = pattern_coalesce (tmp, tmp2);
710 /* we found a conflict between 'i' and 'j'.
712 * report the error. note: 'j' is first.
714 ast_set_error (array[j], error, array[i],
715 G_VARIANT_PARSE_ERROR_NO_COMMON_TYPE,
716 "unable to find a common type");
740 maybe_get_pattern (AST *ast,
743 Maybe *maybe = (Maybe *) ast;
745 if (maybe->child != NULL)
747 gchar *child_pattern;
750 child_pattern = ast_get_pattern (maybe->child, error);
752 if (child_pattern == NULL)
755 pattern = g_strdup_printf ("m%s", child_pattern);
756 g_free (child_pattern);
761 return g_strdup ("m*");
765 maybe_get_value (AST *ast,
766 const GVariantType *type,
769 Maybe *maybe = (Maybe *) ast;
772 if (!g_variant_type_is_maybe (type))
773 return ast_type_error (ast, type, error);
775 type = g_variant_type_element (type);
779 value = ast_get_value (maybe->child, type, error);
787 return g_variant_new_maybe (type, value);
791 maybe_free (AST *ast)
793 Maybe *maybe = (Maybe *) ast;
795 if (maybe->child != NULL)
796 ast_free (maybe->child);
798 g_slice_free (Maybe, maybe);
802 maybe_parse (TokenStream *stream,
806 static const ASTClass maybe_class = {
808 maybe_get_value, NULL,
814 if (token_stream_consume (stream, "just"))
816 child = parse (stream, app, error);
821 else if (!token_stream_consume (stream, "nothing"))
823 token_stream_set_error (stream, error, TRUE,
824 G_VARIANT_PARSE_ERROR_UNKNOWN_KEYWORD,
829 maybe = g_slice_new (Maybe);
830 maybe->ast.class = &maybe_class;
831 maybe->child = child;
833 return (AST *) maybe;
837 maybe_wrapper (AST *ast,
838 const GVariantType *type,
841 const GVariantType *t;
845 for (depth = 0, t = type;
846 g_variant_type_is_maybe (t);
847 depth++, t = g_variant_type_element (t));
849 value = ast->class->get_base_value (ast, t, error);
855 value = g_variant_new_maybe (NULL, value);
869 array_get_pattern (AST *ast,
872 Array *array = (Array *) ast;
876 if (array->n_children == 0)
877 return g_strdup ("Ma*");
879 pattern = ast_array_get_pattern (array->children, array->n_children, error);
884 result = g_strdup_printf ("Ma%s", pattern);
891 array_get_value (AST *ast,
892 const GVariantType *type,
895 Array *array = (Array *) ast;
896 const GVariantType *childtype;
897 GVariantBuilder builder;
900 if (!g_variant_type_is_array (type))
901 return ast_type_error (ast, type, error);
903 g_variant_builder_init (&builder, type);
904 childtype = g_variant_type_element (type);
906 for (i = 0; i < array->n_children; i++)
910 if (!(child = ast_get_value (array->children[i], childtype, error)))
912 g_variant_builder_clear (&builder);
916 g_variant_builder_add_value (&builder, child);
919 return g_variant_builder_end (&builder);
923 array_free (AST *ast)
925 Array *array = (Array *) ast;
927 ast_array_free (array->children, array->n_children);
928 g_slice_free (Array, array);
932 array_parse (TokenStream *stream,
936 static const ASTClass array_class = {
938 maybe_wrapper, array_get_value,
941 gboolean need_comma = FALSE;
944 array = g_slice_new (Array);
945 array->ast.class = &array_class;
946 array->children = NULL;
947 array->n_children = 0;
949 token_stream_assert (stream, "[");
950 while (!token_stream_consume (stream, "]"))
955 !token_stream_require (stream, ",",
956 " or ']' to follow array element",
960 child = parse (stream, app, error);
965 ast_array_append (&array->children, &array->n_children, child);
969 return (AST *) array;
972 ast_array_free (array->children, array->n_children);
973 g_slice_free (Array, array);
987 tuple_get_pattern (AST *ast,
990 Tuple *tuple = (Tuple *) ast;
991 gchar *result = NULL;
995 parts = g_new (gchar *, tuple->n_children + 4);
996 parts[tuple->n_children + 1] = (gchar *) ")";
997 parts[tuple->n_children + 2] = NULL;
998 parts[0] = (gchar *) "M(";
1000 for (i = 0; i < tuple->n_children; i++)
1001 if (!(parts[i + 1] = ast_get_pattern (tuple->children[i], error)))
1004 if (i == tuple->n_children)
1005 result = g_strjoinv ("", parts);
1007 /* parts[0] should not be freed */
1009 g_free (parts[i--]);
1016 tuple_get_value (AST *ast,
1017 const GVariantType *type,
1020 Tuple *tuple = (Tuple *) ast;
1021 const GVariantType *childtype;
1022 GVariantBuilder builder;
1025 if (!g_variant_type_is_tuple (type))
1026 return ast_type_error (ast, type, error);
1028 g_variant_builder_init (&builder, type);
1029 childtype = g_variant_type_first (type);
1031 for (i = 0; i < tuple->n_children; i++)
1035 if (childtype == NULL)
1037 g_variant_builder_clear (&builder);
1038 return ast_type_error (ast, type, error);
1041 if (!(child = ast_get_value (tuple->children[i], childtype, error)))
1043 g_variant_builder_clear (&builder);
1047 g_variant_builder_add_value (&builder, child);
1048 childtype = g_variant_type_next (childtype);
1051 if (childtype != NULL)
1053 g_variant_builder_clear (&builder);
1054 return ast_type_error (ast, type, error);
1057 return g_variant_builder_end (&builder);
1061 tuple_free (AST *ast)
1063 Tuple *tuple = (Tuple *) ast;
1065 ast_array_free (tuple->children, tuple->n_children);
1066 g_slice_free (Tuple, tuple);
1070 tuple_parse (TokenStream *stream,
1074 static const ASTClass tuple_class = {
1076 maybe_wrapper, tuple_get_value,
1079 gboolean need_comma = FALSE;
1080 gboolean first = TRUE;
1083 tuple = g_slice_new (Tuple);
1084 tuple->ast.class = &tuple_class;
1085 tuple->children = NULL;
1086 tuple->n_children = 0;
1088 token_stream_assert (stream, "(");
1089 while (!token_stream_consume (stream, ")"))
1094 !token_stream_require (stream, ",",
1095 " or ')' to follow tuple element",
1099 child = parse (stream, app, error);
1104 ast_array_append (&tuple->children, &tuple->n_children, child);
1106 /* the first time, we absolutely require a comma, so grab it here
1107 * and leave need_comma = FALSE so that the code above doesn't
1108 * require a second comma.
1110 * the second and remaining times, we set need_comma = TRUE.
1114 if (!token_stream_require (stream, ",",
1115 " after first tuple element", error))
1124 return (AST *) tuple;
1127 ast_array_free (tuple->children, tuple->n_children);
1128 g_slice_free (Tuple, tuple);
1141 variant_get_pattern (AST *ast,
1144 return g_strdup ("Mv");
1148 variant_get_value (AST *ast,
1149 const GVariantType *type,
1152 Variant *variant = (Variant *) ast;
1155 if (!g_variant_type_equal (type, G_VARIANT_TYPE_VARIANT))
1156 return ast_type_error (ast, type, error);
1158 child = ast_resolve (variant->value, error);
1163 return g_variant_new_variant (child);
1167 variant_free (AST *ast)
1169 Variant *variant = (Variant *) ast;
1171 ast_free (variant->value);
1172 g_slice_free (Variant, variant);
1176 variant_parse (TokenStream *stream,
1180 static const ASTClass variant_class = {
1181 variant_get_pattern,
1182 maybe_wrapper, variant_get_value,
1188 token_stream_assert (stream, "<");
1189 value = parse (stream, app, error);
1194 if (!token_stream_require (stream, ">", " to follow variant value", error))
1200 variant = g_slice_new (Variant);
1201 variant->ast.class = &variant_class;
1202 variant->value = value;
1204 return (AST *) variant;
1217 dictionary_get_pattern (AST *ast,
1220 Dictionary *dict = (Dictionary *) ast;
1221 gchar *value_pattern;
1226 if (dict->n_children == 0)
1227 return g_strdup ("Ma{**}");
1229 key_pattern = ast_array_get_pattern (dict->keys,
1230 abs (dict->n_children),
1233 if (key_pattern == NULL)
1236 /* we can not have maybe keys */
1237 if (key_pattern[0] == 'M')
1238 key_char = key_pattern[1];
1240 key_char = key_pattern[0];
1242 g_free (key_pattern);
1245 * plus undetermined number type and undetermined string type.
1247 if (!strchr ("bynqiuxthdsogNS", key_char))
1249 ast_set_error (ast, error, NULL,
1250 G_VARIANT_PARSE_ERROR_BASIC_TYPE_EXPECTED,
1251 "dictionary keys must have basic types");
1255 value_pattern = ast_get_pattern (dict->values[0], error);
1257 if (value_pattern == NULL)
1260 result = g_strdup_printf ("M%s{%c%s}",
1261 dict->n_children > 0 ? "a" : "",
1262 key_char, value_pattern);
1263 g_free (value_pattern);
1269 dictionary_get_value (AST *ast,
1270 const GVariantType *type,
1273 Dictionary *dict = (Dictionary *) ast;
1275 if (dict->n_children == -1)
1277 const GVariantType *subtype;
1278 GVariantBuilder builder;
1281 if (!g_variant_type_is_dict_entry (type))
1282 return ast_type_error (ast, type, error);
1284 g_variant_builder_init (&builder, type);
1286 subtype = g_variant_type_key (type);
1287 if (!(subvalue = ast_get_value (dict->keys[0], subtype, error)))
1289 g_variant_builder_clear (&builder);
1292 g_variant_builder_add_value (&builder, subvalue);
1294 subtype = g_variant_type_value (type);
1295 if (!(subvalue = ast_get_value (dict->values[0], subtype, error)))
1297 g_variant_builder_clear (&builder);
1300 g_variant_builder_add_value (&builder, subvalue);
1302 return g_variant_builder_end (&builder);
1306 const GVariantType *entry, *key, *val;
1307 GVariantBuilder builder;
1310 if (!g_variant_type_is_subtype_of (type, G_VARIANT_TYPE_DICTIONARY))
1311 return ast_type_error (ast, type, error);
1313 entry = g_variant_type_element (type);
1314 key = g_variant_type_key (entry);
1315 val = g_variant_type_value (entry);
1317 g_variant_builder_init (&builder, type);
1319 for (i = 0; i < dict->n_children; i++)
1323 g_variant_builder_open (&builder, entry);
1325 if (!(subvalue = ast_get_value (dict->keys[i], key, error)))
1327 g_variant_builder_clear (&builder);
1330 g_variant_builder_add_value (&builder, subvalue);
1332 if (!(subvalue = ast_get_value (dict->values[i], val, error)))
1334 g_variant_builder_clear (&builder);
1337 g_variant_builder_add_value (&builder, subvalue);
1338 g_variant_builder_close (&builder);
1341 return g_variant_builder_end (&builder);
1346 dictionary_free (AST *ast)
1348 Dictionary *dict = (Dictionary *) ast;
1351 if (dict->n_children > -1)
1352 n_children = dict->n_children;
1356 ast_array_free (dict->keys, n_children);
1357 ast_array_free (dict->values, n_children);
1358 g_slice_free (Dictionary, dict);
1362 dictionary_parse (TokenStream *stream,
1366 static const ASTClass dictionary_class = {
1367 dictionary_get_pattern,
1368 maybe_wrapper, dictionary_get_value,
1371 gint n_keys, n_values;
1376 dict = g_slice_new (Dictionary);
1377 dict->ast.class = &dictionary_class;
1379 dict->values = NULL;
1380 n_keys = n_values = 0;
1382 token_stream_assert (stream, "{");
1384 if (token_stream_consume (stream, "}"))
1386 dict->n_children = 0;
1387 return (AST *) dict;
1390 if ((first = parse (stream, app, error)) == NULL)
1393 ast_array_append (&dict->keys, &n_keys, first);
1395 only_one = token_stream_consume (stream, ",");
1397 !token_stream_require (stream, ":",
1398 " or ',' to follow dictionary entry key",
1402 if ((first = parse (stream, app, error)) == NULL)
1405 ast_array_append (&dict->values, &n_values, first);
1409 if (!token_stream_require (stream, "}", " at end of dictionary entry",
1413 g_assert (n_keys == 1 && n_values == 1);
1414 dict->n_children = -1;
1416 return (AST *) dict;
1419 while (!token_stream_consume (stream, "}"))
1423 if (!token_stream_require (stream, ",",
1424 " or '}' to follow dictionary entry", error))
1427 child = parse (stream, app, error);
1432 ast_array_append (&dict->keys, &n_keys, child);
1434 if (!token_stream_require (stream, ":",
1435 " to follow dictionary entry key", error))
1438 child = parse (stream, app, error);
1443 ast_array_append (&dict->values, &n_values, child);
1446 g_assert (n_keys == n_values);
1447 dict->n_children = n_keys;
1449 return (AST *) dict;
1452 ast_array_free (dict->keys, n_keys);
1453 ast_array_free (dict->values, n_values);
1454 g_slice_free (Dictionary, dict);
1466 string_get_pattern (AST *ast,
1469 return g_strdup ("MS");
1473 string_get_value (AST *ast,
1474 const GVariantType *type,
1477 String *string = (String *) ast;
1479 if (g_variant_type_equal (type, G_VARIANT_TYPE_STRING))
1480 return g_variant_new_string (string->string);
1482 else if (g_variant_type_equal (type, G_VARIANT_TYPE_OBJECT_PATH))
1484 if (!g_variant_is_object_path (string->string))
1486 ast_set_error (ast, error, NULL,
1487 G_VARIANT_PARSE_ERROR_INVALID_OBJECT_PATH,
1488 "not a valid object path");
1492 return g_variant_new_object_path (string->string);
1495 else if (g_variant_type_equal (type, G_VARIANT_TYPE_SIGNATURE))
1497 if (!g_variant_is_signature (string->string))
1499 ast_set_error (ast, error, NULL,
1500 G_VARIANT_PARSE_ERROR_INVALID_SIGNATURE,
1501 "not a valid signature");
1505 return g_variant_new_signature (string->string);
1509 return ast_type_error (ast, type, error);
1513 string_free (AST *ast)
1515 String *string = (String *) ast;
1517 g_free (string->string);
1518 g_slice_free (String, string);
1522 unicode_unescape (const gchar *src,
1536 g_assert (length < sizeof (buffer));
1537 strncpy (buffer, src + *src_ofs, length);
1538 buffer[length] = '\0';
1540 value = g_ascii_strtoull (buffer, &end, 0x10);
1542 if (value == 0 || end != buffer + length)
1544 parser_set_error (error, ref, NULL,
1545 G_VARIANT_PARSE_ERROR_INVALID_CHARACTER,
1546 "invalid %d-character unicode escape", length);
1550 g_assert (value <= G_MAXUINT32);
1552 *dest_ofs += g_unichar_to_utf8 (value, dest + *dest_ofs);
1559 string_parse (TokenStream *stream,
1563 static const ASTClass string_class = {
1565 maybe_wrapper, string_get_value,
1576 token_stream_start_ref (stream, &ref);
1577 token = token_stream_get (stream);
1578 token_stream_end_ref (stream, &ref);
1579 length = strlen (token);
1582 str = g_malloc (length);
1583 g_assert (quote == '"' || quote == '\'');
1586 while (token[i] != quote)
1590 parser_set_error (error, &ref, NULL,
1591 G_VARIANT_PARSE_ERROR_UNTERMINATED_STRING_CONSTANT,
1592 "unterminated string constant");
1601 parser_set_error (error, &ref, NULL,
1602 G_VARIANT_PARSE_ERROR_UNTERMINATED_STRING_CONSTANT,
1603 "unterminated string constant");
1609 if (!unicode_unescape (token, &i, str, &j, 4, &ref, error))
1618 if (!unicode_unescape (token, &i, str, &j, 8, &ref, error))
1626 case 'a': str[j++] = '\a'; i++; continue;
1627 case 'b': str[j++] = '\b'; i++; continue;
1628 case 'f': str[j++] = '\f'; i++; continue;
1629 case 'n': str[j++] = '\n'; i++; continue;
1630 case 'r': str[j++] = '\r'; i++; continue;
1631 case 't': str[j++] = '\t'; i++; continue;
1632 case 'v': str[j++] = '\v'; i++; continue;
1633 case '\n': i++; continue;
1637 str[j++] = token[i++];
1642 string = g_slice_new (String);
1643 string->ast.class = &string_class;
1644 string->string = str;
1646 token_stream_next (stream);
1648 return (AST *) string;
1658 bytestring_get_pattern (AST *ast,
1661 return g_strdup ("May");
1665 bytestring_get_value (AST *ast,
1666 const GVariantType *type,
1669 ByteString *string = (ByteString *) ast;
1671 if (!g_variant_type_equal (type, G_VARIANT_TYPE_BYTESTRING))
1672 return ast_type_error (ast, type, error);
1674 return g_variant_new_bytestring (string->string);
1678 bytestring_free (AST *ast)
1680 ByteString *string = (ByteString *) ast;
1682 g_free (string->string);
1683 g_slice_free (ByteString, string);
1687 bytestring_parse (TokenStream *stream,
1691 static const ASTClass bytestring_class = {
1692 bytestring_get_pattern,
1693 maybe_wrapper, bytestring_get_value,
1704 token_stream_start_ref (stream, &ref);
1705 token = token_stream_get (stream);
1706 token_stream_end_ref (stream, &ref);
1707 g_assert (token[0] == 'b');
1708 length = strlen (token);
1711 str = g_malloc (length);
1712 g_assert (quote == '"' || quote == '\'');
1715 while (token[i] != quote)
1719 parser_set_error (error, &ref, NULL,
1720 G_VARIANT_PARSE_ERROR_UNTERMINATED_STRING_CONSTANT,
1721 "unterminated string constant");
1729 parser_set_error (error, &ref, NULL,
1730 G_VARIANT_PARSE_ERROR_UNTERMINATED_STRING_CONSTANT,
1731 "unterminated string constant");
1735 case '0': case '1': case '2': case '3':
1736 case '4': case '5': case '6': case '7':
1738 /* up to 3 characters */
1739 guchar val = token[i++] - '0';
1741 if ('0' <= token[i] && token[i] < '8')
1742 val = (val << 3) | (token[i++] - '0');
1744 if ('0' <= token[i] && token[i] < '8')
1745 val = (val << 3) | (token[i++] - '0');
1751 case 'a': str[j++] = '\a'; i++; continue;
1752 case 'b': str[j++] = '\b'; i++; continue;
1753 case 'f': str[j++] = '\f'; i++; continue;
1754 case 'n': str[j++] = '\n'; i++; continue;
1755 case 'r': str[j++] = '\r'; i++; continue;
1756 case 't': str[j++] = '\t'; i++; continue;
1757 case 'v': str[j++] = '\v'; i++; continue;
1758 case '\n': i++; continue;
1762 str[j++] = token[i++];
1767 string = g_slice_new (ByteString);
1768 string->ast.class = &bytestring_class;
1769 string->string = str;
1771 token_stream_next (stream);
1773 return (AST *) string;
1784 number_get_pattern (AST *ast,
1787 Number *number = (Number *) ast;
1789 if (strchr (number->token, '.') ||
1790 (!g_str_has_prefix (number->token, "0x") && strchr (number->token, 'e')) ||
1791 strstr (number->token, "inf") ||
1792 strstr (number->token, "nan"))
1793 return g_strdup ("Md");
1795 return g_strdup ("MN");
1799 number_overflow (AST *ast,
1800 const GVariantType *type,
1803 ast_set_error (ast, error, NULL,
1804 G_VARIANT_PARSE_ERROR_NUMBER_OUT_OF_RANGE,
1805 "number out of range for type '%c'",
1806 g_variant_type_peek_string (type)[0]);
1811 number_get_value (AST *ast,
1812 const GVariantType *type,
1815 Number *number = (Number *) ast;
1823 token = number->token;
1825 if (g_variant_type_equal (type, G_VARIANT_TYPE_DOUBLE))
1830 dbl_val = g_ascii_strtod (token, &end);
1831 if (dbl_val != 0.0 && errno == ERANGE)
1833 ast_set_error (ast, error, NULL,
1834 G_VARIANT_PARSE_ERROR_NUMBER_TOO_BIG,
1835 "number too big for any type");
1839 /* silence uninitialised warnings... */
1846 negative = token[0] == '-';
1847 if (token[0] == '-')
1851 abs_val = g_ascii_strtoull (token, &end, 0);
1852 if (abs_val == G_MAXUINT64 && errno == ERANGE)
1854 ast_set_error (ast, error, NULL,
1855 G_VARIANT_PARSE_ERROR_NUMBER_TOO_BIG,
1856 "integer too big for any type");
1863 /* silence uninitialised warning... */
1871 ref = ast->source_ref;
1872 ref.start += end - number->token;
1873 ref.end = ref.start + 1;
1875 parser_set_error (error, &ref, NULL,
1876 G_VARIANT_PARSE_ERROR_INVALID_CHARACTER,
1877 "invalid character in number");
1882 return g_variant_new_double (dbl_val);
1884 switch (*g_variant_type_peek_string (type))
1887 if (negative || abs_val > G_MAXUINT8)
1888 return number_overflow (ast, type, error);
1889 return g_variant_new_byte (abs_val);
1892 if (abs_val - negative > G_MAXINT16)
1893 return number_overflow (ast, type, error);
1894 return g_variant_new_int16 (negative ? -abs_val : abs_val);
1897 if (negative || abs_val > G_MAXUINT16)
1898 return number_overflow (ast, type, error);
1899 return g_variant_new_uint16 (abs_val);
1902 if (abs_val - negative > G_MAXINT32)
1903 return number_overflow (ast, type, error);
1904 return g_variant_new_int32 (negative ? -abs_val : abs_val);
1907 if (negative || abs_val > G_MAXUINT32)
1908 return number_overflow (ast, type, error);
1909 return g_variant_new_uint32 (abs_val);
1912 if (abs_val - negative > G_MAXINT64)
1913 return number_overflow (ast, type, error);
1914 return g_variant_new_int64 (negative ? -abs_val : abs_val);
1918 return number_overflow (ast, type, error);
1919 return g_variant_new_uint64 (abs_val);
1922 if (abs_val - negative > G_MAXINT32)
1923 return number_overflow (ast, type, error);
1924 return g_variant_new_handle (negative ? -abs_val : abs_val);
1927 return ast_type_error (ast, type, error);
1932 number_free (AST *ast)
1934 Number *number = (Number *) ast;
1936 g_free (number->token);
1937 g_slice_free (Number, number);
1941 number_parse (TokenStream *stream,
1945 static const ASTClass number_class = {
1947 maybe_wrapper, number_get_value,
1952 number = g_slice_new (Number);
1953 number->ast.class = &number_class;
1954 number->token = token_stream_get (stream);
1955 token_stream_next (stream);
1957 return (AST *) number;
1967 boolean_get_pattern (AST *ast,
1970 return g_strdup ("Mb");
1974 boolean_get_value (AST *ast,
1975 const GVariantType *type,
1978 Boolean *boolean = (Boolean *) ast;
1980 if (!g_variant_type_equal (type, G_VARIANT_TYPE_BOOLEAN))
1981 return ast_type_error (ast, type, error);
1983 return g_variant_new_boolean (boolean->value);
1987 boolean_free (AST *ast)
1989 Boolean *boolean = (Boolean *) ast;
1991 g_slice_free (Boolean, boolean);
1995 boolean_new (gboolean value)
1997 static const ASTClass boolean_class = {
1998 boolean_get_pattern,
1999 maybe_wrapper, boolean_get_value,
2004 boolean = g_slice_new (Boolean);
2005 boolean->ast.class = &boolean_class;
2006 boolean->value = value;
2008 return (AST *) boolean;
2019 positional_get_pattern (AST *ast,
2022 Positional *positional = (Positional *) ast;
2024 return g_strdup (g_variant_get_type_string (positional->value));
2028 positional_get_value (AST *ast,
2029 const GVariantType *type,
2032 Positional *positional = (Positional *) ast;
2035 g_assert (positional->value != NULL);
2037 if G_UNLIKELY (!g_variant_is_of_type (positional->value, type))
2038 return ast_type_error (ast, type, error);
2040 /* NOTE: if _get is called more than once then
2041 * things get messed up with respect to floating refs.
2043 * fortunately, this function should only ever get called once.
2045 g_assert (positional->value != NULL);
2046 value = positional->value;
2047 positional->value = NULL;
2053 positional_free (AST *ast)
2055 Positional *positional = (Positional *) ast;
2057 /* if positional->value is set, just leave it.
2058 * memory management doesn't matter in case of programmer error.
2060 g_slice_free (Positional, positional);
2064 positional_parse (TokenStream *stream,
2068 static const ASTClass positional_class = {
2069 positional_get_pattern,
2070 positional_get_value, NULL,
2073 Positional *positional;
2074 const gchar *endptr;
2077 token = token_stream_get (stream);
2078 g_assert (token[0] == '%');
2080 positional = g_slice_new (Positional);
2081 positional->ast.class = &positional_class;
2082 positional->value = g_variant_new_va (token + 1, &endptr, app);
2084 if (*endptr || positional->value == NULL)
2086 token_stream_set_error (stream, error, TRUE,
2087 G_VARIANT_PARSE_ERROR_INVALID_FORMAT_STRING,
2088 "invalid GVariant format string");
2089 /* memory management doesn't matter in case of programmer error. */
2093 token_stream_next (stream);
2096 return (AST *) positional;
2108 typedecl_get_pattern (AST *ast,
2111 TypeDecl *decl = (TypeDecl *) ast;
2113 return g_variant_type_dup_string (decl->type);
2117 typedecl_get_value (AST *ast,
2118 const GVariantType *type,
2121 TypeDecl *decl = (TypeDecl *) ast;
2123 return ast_get_value (decl->child, type, error);
2127 typedecl_free (AST *ast)
2129 TypeDecl *decl = (TypeDecl *) ast;
2131 ast_free (decl->child);
2132 g_variant_type_free (decl->type);
2133 g_slice_free (TypeDecl, decl);
2137 typedecl_parse (TokenStream *stream,
2141 static const ASTClass typedecl_class = {
2142 typedecl_get_pattern,
2143 typedecl_get_value, NULL,
2150 if (token_stream_peek (stream, '@'))
2154 token = token_stream_get (stream);
2156 if (!g_variant_type_string_is_valid (token + 1))
2158 token_stream_set_error (stream, error, TRUE,
2159 G_VARIANT_PARSE_ERROR_INVALID_TYPE_STRING,
2160 "invalid type declaration");
2166 type = g_variant_type_new (token + 1);
2168 if (!g_variant_type_is_definite (type))
2170 token_stream_set_error (stream, error, TRUE,
2171 G_VARIANT_PARSE_ERROR_DEFINITE_TYPE_EXPECTED,
2172 "type declarations must be definite");
2173 g_variant_type_free (type);
2179 token_stream_next (stream);
2184 if (token_stream_consume (stream, "boolean"))
2185 type = g_variant_type_copy (G_VARIANT_TYPE_BOOLEAN);
2187 else if (token_stream_consume (stream, "byte"))
2188 type = g_variant_type_copy (G_VARIANT_TYPE_BYTE);
2190 else if (token_stream_consume (stream, "int16"))
2191 type = g_variant_type_copy (G_VARIANT_TYPE_INT16);
2193 else if (token_stream_consume (stream, "uint16"))
2194 type = g_variant_type_copy (G_VARIANT_TYPE_UINT16);
2196 else if (token_stream_consume (stream, "int32"))
2197 type = g_variant_type_copy (G_VARIANT_TYPE_INT32);
2199 else if (token_stream_consume (stream, "handle"))
2200 type = g_variant_type_copy (G_VARIANT_TYPE_HANDLE);
2202 else if (token_stream_consume (stream, "uint32"))
2203 type = g_variant_type_copy (G_VARIANT_TYPE_UINT32);
2205 else if (token_stream_consume (stream, "int64"))
2206 type = g_variant_type_copy (G_VARIANT_TYPE_INT64);
2208 else if (token_stream_consume (stream, "uint64"))
2209 type = g_variant_type_copy (G_VARIANT_TYPE_UINT64);
2211 else if (token_stream_consume (stream, "double"))
2212 type = g_variant_type_copy (G_VARIANT_TYPE_DOUBLE);
2214 else if (token_stream_consume (stream, "string"))
2215 type = g_variant_type_copy (G_VARIANT_TYPE_STRING);
2217 else if (token_stream_consume (stream, "objectpath"))
2218 type = g_variant_type_copy (G_VARIANT_TYPE_OBJECT_PATH);
2220 else if (token_stream_consume (stream, "signature"))
2221 type = g_variant_type_copy (G_VARIANT_TYPE_SIGNATURE);
2225 token_stream_set_error (stream, error, TRUE,
2226 G_VARIANT_PARSE_ERROR_UNKNOWN_KEYWORD,
2232 if ((child = parse (stream, app, error)) == NULL)
2234 g_variant_type_free (type);
2238 decl = g_slice_new (TypeDecl);
2239 decl->ast.class = &typedecl_class;
2241 decl->child = child;
2243 return (AST *) decl;
2247 parse (TokenStream *stream,
2251 SourceRef source_ref;
2254 token_stream_prepare (stream);
2255 token_stream_start_ref (stream, &source_ref);
2257 if (token_stream_peek (stream, '['))
2258 result = array_parse (stream, app, error);
2260 else if (token_stream_peek (stream, '('))
2261 result = tuple_parse (stream, app, error);
2263 else if (token_stream_peek (stream, '<'))
2264 result = variant_parse (stream, app, error);
2266 else if (token_stream_peek (stream, '{'))
2267 result = dictionary_parse (stream, app, error);
2269 else if (app && token_stream_peek (stream, '%'))
2270 result = positional_parse (stream, app, error);
2272 else if (token_stream_consume (stream, "true"))
2273 result = boolean_new (TRUE);
2275 else if (token_stream_consume (stream, "false"))
2276 result = boolean_new (FALSE);
2278 else if (token_stream_is_numeric (stream) ||
2279 token_stream_peek_string (stream, "inf") ||
2280 token_stream_peek_string (stream, "nan"))
2281 result = number_parse (stream, app, error);
2283 else if (token_stream_peek (stream, 'n') ||
2284 token_stream_peek (stream, 'j'))
2285 result = maybe_parse (stream, app, error);
2287 else if (token_stream_peek (stream, '@') ||
2288 token_stream_is_keyword (stream))
2289 result = typedecl_parse (stream, app, error);
2291 else if (token_stream_peek (stream, '\'') ||
2292 token_stream_peek (stream, '"'))
2293 result = string_parse (stream, app, error);
2295 else if (token_stream_peek2 (stream, 'b', '\'') ||
2296 token_stream_peek2 (stream, 'b', '"'))
2297 result = bytestring_parse (stream, app, error);
2301 token_stream_set_error (stream, error, FALSE,
2302 G_VARIANT_PARSE_ERROR_VALUE_EXPECTED,
2309 token_stream_end_ref (stream, &source_ref);
2310 result->source_ref = source_ref;
2318 * @type: (allow-none): a #GVariantType, or %NULL
2319 * @text: a string containing a GVariant in text form
2320 * @limit: (allow-none): a pointer to the end of @text, or %NULL
2321 * @endptr: (allow-none): a location to store the end pointer, or %NULL
2322 * @error: (allow-none): a pointer to a %NULL #GError pointer, or %NULL
2324 * Parses a #GVariant from a text representation.
2326 * A single #GVariant is parsed from the content of @text.
2328 * The format is described [here][gvariant-text].
2330 * The memory at @limit will never be accessed and the parser behaves as
2331 * if the character at @limit is the nul terminator. This has the
2332 * effect of bounding @text.
2334 * If @endptr is non-%NULL then @text is permitted to contain data
2335 * following the value that this function parses and @endptr will be
2336 * updated to point to the first character past the end of the text
2337 * parsed by this function. If @endptr is %NULL and there is extra data
2338 * then an error is returned.
2340 * If @type is non-%NULL then the value will be parsed to have that
2341 * type. This may result in additional parse errors (in the case that
2342 * the parsed value doesn't fit the type) but may also result in fewer
2343 * errors (in the case that the type would have been ambiguous, such as
2344 * with empty arrays).
2346 * In the event that the parsing is successful, the resulting #GVariant
2349 * In case of any error, %NULL will be returned. If @error is non-%NULL
2350 * then it will be set to reflect the error that occurred.
2352 * Officially, the language understood by the parser is "any string
2353 * produced by g_variant_print()".
2355 * Returns: a reference to a #GVariant, or %NULL
2358 g_variant_parse (const GVariantType *type,
2361 const gchar **endptr,
2364 TokenStream stream = { 0, };
2365 GVariant *result = NULL;
2368 g_return_val_if_fail (text != NULL, NULL);
2369 g_return_val_if_fail (text == limit || text != NULL, NULL);
2371 stream.start = text;
2372 stream.stream = text;
2375 if ((ast = parse (&stream, NULL, error)))
2378 result = ast_resolve (ast, error);
2380 result = ast_get_value (ast, type, error);
2384 g_variant_ref_sink (result);
2388 while (stream.stream != limit &&
2389 g_ascii_isspace (*stream.stream))
2392 if (stream.stream != limit && *stream.stream != '\0')
2394 SourceRef ref = { stream.stream - text,
2395 stream.stream - text };
2397 parser_set_error (error, &ref, NULL,
2398 G_VARIANT_PARSE_ERROR_INPUT_NOT_AT_END,
2399 "expected end of input");
2400 g_variant_unref (result);
2406 *endptr = stream.stream;
2416 * g_variant_new_parsed_va:
2417 * @format: a text format #GVariant
2418 * @app: a pointer to a #va_list
2420 * Parses @format and returns the result.
2422 * This is the version of g_variant_new_parsed() intended to be used
2425 * The return value will be floating if it was a newly created GVariant
2426 * instance. In the case that @format simply specified the collection
2427 * of a #GVariant pointer (eg: @format was "%*") then the collected
2428 * #GVariant pointer will be returned unmodified, without adding any
2429 * additional references.
2431 * Note that the arguments in @app must be of the correct width for their types
2432 * specified in @format when collected into the #va_list. See
2433 * the [GVariant varargs documentation][gvariant-varargs].
2435 * In order to behave correctly in all cases it is necessary for the
2436 * calling function to g_variant_ref_sink() the return result before
2437 * returning control to the user that originally provided the pointer.
2438 * At this point, the caller will have their own full reference to the
2439 * result. This can also be done by adding the result to a container,
2440 * or by passing it to another g_variant_new() call.
2442 * Returns: a new, usually floating, #GVariant
2445 g_variant_new_parsed_va (const gchar *format,
2448 TokenStream stream = { 0, };
2449 GVariant *result = NULL;
2450 GError *error = NULL;
2453 g_return_val_if_fail (format != NULL, NULL);
2454 g_return_val_if_fail (app != NULL, NULL);
2456 stream.start = format;
2457 stream.stream = format;
2460 if ((ast = parse (&stream, app, &error)))
2462 result = ast_resolve (ast, &error);
2467 g_error ("g_variant_new_parsed: %s", error->message);
2470 g_error ("g_variant_new_parsed: trailing text after value");
2476 * g_variant_new_parsed:
2477 * @format: a text format #GVariant
2478 * @...: arguments as per @format
2480 * Parses @format and returns the result.
2482 * @format must be a text format #GVariant with one extension: at any
2483 * point that a value may appear in the text, a '%' character followed
2484 * by a GVariant format string (as per g_variant_new()) may appear. In
2485 * that case, the same arguments are collected from the argument list as
2486 * g_variant_new() would have collected.
2488 * Note that the arguments must be of the correct width for their types
2489 * specified in @format. This can be achieved by casting them. See
2490 * the [GVariant varargs documentation][gvariant-varargs].
2492 * Consider this simple example:
2493 * |[<!-- language="C" -->
2494 * g_variant_new_parsed ("[('one', 1), ('two', %i), (%s, 3)]", 2, "three");
2497 * In the example, the variable argument parameters are collected and
2498 * filled in as if they were part of the original string to produce the
2500 * |[<!-- language="C" -->
2501 * [('one', 1), ('two', 2), ('three', 3)]
2504 * This function is intended only to be used with @format as a string
2505 * literal. Any parse error is fatal to the calling process. If you
2506 * want to parse data from untrusted sources, use g_variant_parse().
2508 * You may not use this function to return, unmodified, a single
2509 * #GVariant pointer from the argument list. ie: @format may not solely
2510 * be anything along the lines of "%*", "%?", "\%r", or anything starting
2513 * Returns: a new floating #GVariant instance
2516 g_variant_new_parsed (const gchar *format,
2522 va_start (ap, format);
2523 result = g_variant_new_parsed_va (format, &ap);
2530 * g_variant_builder_add_parsed:
2531 * @builder: a #GVariantBuilder
2532 * @format: a text format #GVariant
2533 * @...: arguments as per @format
2535 * Adds to a #GVariantBuilder.
2537 * This call is a convenience wrapper that is exactly equivalent to
2538 * calling g_variant_new_parsed() followed by
2539 * g_variant_builder_add_value().
2541 * Note that the arguments must be of the correct width for their types
2542 * specified in @format_string. This can be achieved by casting them. See
2543 * the [GVariant varargs documentation][gvariant-varargs].
2545 * This function might be used as follows:
2547 * |[<!-- language="C" -->
2549 * make_pointless_dictionary (void)
2551 * GVariantBuilder builder;
2554 * g_variant_builder_init (&builder, G_VARIANT_TYPE_ARRAY);
2555 * g_variant_builder_add_parsed (&builder, "{'width', <%i>}", 600);
2556 * g_variant_builder_add_parsed (&builder, "{'title', <%s>}", "foo");
2557 * g_variant_builder_add_parsed (&builder, "{'transparency', <0.5>}");
2558 * return g_variant_builder_end (&builder);
2565 g_variant_builder_add_parsed (GVariantBuilder *builder,
2566 const gchar *format,
2571 va_start (ap, format);
2572 g_variant_builder_add_value (builder, g_variant_new_parsed_va (format, &ap));
2577 parse_num (const gchar *num,
2584 bignum = g_ascii_strtoll (num, &endptr, 10);
2586 if (endptr != limit)
2589 if (bignum < 0 || bignum > G_MAXINT)
2598 add_last_line (GString *err,
2601 const gchar *last_nl;
2605 /* This is an error at the end of input. If we have a file
2606 * with newlines, that's probably the empty string after the
2607 * last newline, which is not the most useful thing to show.
2609 * Instead, show the last line of non-whitespace that we have
2610 * and put the pointer at the end of it.
2612 chomped = g_strchomp (g_strdup (str));
2613 last_nl = strrchr (chomped, '\n');
2614 if (last_nl == NULL)
2619 /* Print the last line like so:
2624 g_string_append (err, " ");
2626 g_string_append (err, last_nl);
2628 g_string_append (err, "(empty input)");
2629 g_string_append (err, "\n ");
2630 for (i = 0; last_nl[i]; i++)
2631 g_string_append_c (err, ' ');
2632 g_string_append (err, "^\n");
2637 add_lines_from_range (GString *err,
2639 const gchar *start1,
2641 const gchar *start2,
2644 while (str < end1 || str < end2)
2648 nl = str + strcspn (str, "\n");
2650 if ((start1 < nl && str < end1) || (start2 < nl && str < end2))
2654 /* We're going to print this line */
2655 g_string_append (err, " ");
2656 g_string_append_len (err, str, nl - str);
2657 g_string_append (err, "\n ");
2659 /* And add underlines... */
2660 for (s = str; s < nl; s++)
2662 if ((start1 <= s && s < end1) || (start2 <= s && s < end2))
2663 g_string_append_c (err, '^');
2665 g_string_append_c (err, ' ');
2667 g_string_append_c (err, '\n');
2678 * g_variant_parse_error_print_context:
2679 * @error: a #GError from the #GVariantParseError domain
2680 * @source_str: the string that was given to the parser
2682 * Pretty-prints a message showing the context of a #GVariant parse
2683 * error within the string for which parsing was attempted.
2685 * The resulting string is suitable for output to the console or other
2686 * monospace media where newlines are treated in the usual way.
2688 * The message will typically look something like one of the following:
2691 * unterminated string constant:
2699 * unable to find a common type:
2704 * The format of the message may change in a future version.
2706 * @error must have come from a failed attempt to g_variant_parse() and
2707 * @source_str must be exactly the same string that caused the error.
2708 * If @source_str was not nul-terminated when you passed it to
2709 * g_variant_parse() then you must add nul termination before using this
2712 * Returns: (transfer full): the printed message
2717 g_variant_parse_error_print_context (GError *error,
2718 const gchar *source_str)
2720 const gchar *colon, *dash, *comma;
2721 gboolean success = FALSE;
2724 g_return_val_if_fail (error->domain == G_VARIANT_PARSE_ERROR, FALSE);
2726 /* We can only have a limited number of possible types of ranges
2727 * emitted from the parser:
2729 * - a: -- usually errors from the tokeniser (eof, invalid char, etc.)
2730 * - a-b: -- usually errors from handling one single token
2731 * - a-b,c-d: -- errors involving two tokens (ie: type inferencing)
2733 * We never see, for example "a,c".
2736 colon = strchr (error->message, ':');
2737 dash = strchr (error->message, '-');
2738 comma = strchr (error->message, ',');
2743 err = g_string_new (colon + 1);
2744 g_string_append (err, ":\n");
2746 if (dash == NULL || colon < dash)
2750 /* we have a single point */
2751 if (!parse_num (error->message, colon, &point))
2754 if (point >= strlen (source_str))
2755 /* the error is at the end of the input */
2756 add_last_line (err, source_str);
2758 /* otherwise just treat it as a error at a thin range */
2759 add_lines_from_range (err, source_str, source_str + point, source_str + point + 1, NULL, NULL);
2763 /* We have one or two ranges... */
2764 if (comma && comma < colon)
2766 gint start1, end1, start2, end2;
2770 dash2 = strchr (comma, '-');
2772 if (!parse_num (error->message, dash, &start1) || !parse_num (dash + 1, comma, &end1) ||
2773 !parse_num (comma + 1, dash2, &start2) || !parse_num (dash2 + 1, colon, &end2))
2776 add_lines_from_range (err, source_str,
2777 source_str + start1, source_str + end1,
2778 source_str + start2, source_str + end2);
2785 if (!parse_num (error->message, dash, &start) || !parse_num (dash + 1, colon, &end))
2788 add_lines_from_range (err, source_str, source_str + start, source_str + end, NULL, NULL);
2795 return g_string_free (err, !success);