Merge branch 'test-ip_mreq_source-android-only' into 'master'
[glib.git] / glib / gmarkup.c
blobf1ab94e569c09cdd6aaecd35075336f534182fa3
1 /* gmarkup.c - Simple XML-like parser
3 * Copyright 2000, 2003 Red Hat, Inc.
4 * Copyright 2007, 2008 Ryan Lortie <desrt@desrt.ca>
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public License
17 * along with this library; if not, see <http://www.gnu.org/licenses/>.
20 #include "config.h"
22 #include <stdarg.h>
23 #include <string.h>
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <errno.h>
28 #include "gmarkup.h"
30 #include "gatomic.h"
31 #include "gslice.h"
32 #include "galloca.h"
33 #include "gstrfuncs.h"
34 #include "gstring.h"
35 #include "gtestutils.h"
36 #include "glibintl.h"
37 #include "gthread.h"
39 /**
40 * SECTION:markup
41 * @Title: Simple XML Subset Parser
42 * @Short_description: parses a subset of XML
43 * @See_also: [XML Specification](http://www.w3.org/TR/REC-xml/)
45 * The "GMarkup" parser is intended to parse a simple markup format
46 * that's a subset of XML. This is a small, efficient, easy-to-use
47 * parser. It should not be used if you expect to interoperate with
48 * other applications generating full-scale XML. However, it's very
49 * useful for application data files, config files, etc. where you
50 * know your application will be the only one writing the file.
51 * Full-scale XML parsers should be able to parse the subset used by
52 * GMarkup, so you can easily migrate to full-scale XML at a later
53 * time if the need arises.
55 * GMarkup is not guaranteed to signal an error on all invalid XML;
56 * the parser may accept documents that an XML parser would not.
57 * However, XML documents which are not well-formed (which is a
58 * weaker condition than being valid. See the
59 * [XML specification](http://www.w3.org/TR/REC-xml/)
60 * for definitions of these terms.) are not considered valid GMarkup
61 * documents.
63 * Simplifications to XML include:
65 * - Only UTF-8 encoding is allowed
67 * - No user-defined entities
69 * - Processing instructions, comments and the doctype declaration
70 * are "passed through" but are not interpreted in any way
72 * - No DTD or validation
74 * The markup format does support:
76 * - Elements
78 * - Attributes
80 * - 5 standard entities: &amp; &lt; &gt; &quot; &apos;
82 * - Character references
84 * - Sections marked as CDATA
87 G_DEFINE_QUARK (g-markup-error-quark, g_markup_error)
89 typedef enum
91 STATE_START,
92 STATE_AFTER_OPEN_ANGLE,
93 STATE_AFTER_CLOSE_ANGLE,
94 STATE_AFTER_ELISION_SLASH, /* the slash that obviates need for end element */
95 STATE_INSIDE_OPEN_TAG_NAME,
96 STATE_INSIDE_ATTRIBUTE_NAME,
97 STATE_AFTER_ATTRIBUTE_NAME,
98 STATE_BETWEEN_ATTRIBUTES,
99 STATE_AFTER_ATTRIBUTE_EQUALS_SIGN,
100 STATE_INSIDE_ATTRIBUTE_VALUE_SQ,
101 STATE_INSIDE_ATTRIBUTE_VALUE_DQ,
102 STATE_INSIDE_TEXT,
103 STATE_AFTER_CLOSE_TAG_SLASH,
104 STATE_INSIDE_CLOSE_TAG_NAME,
105 STATE_AFTER_CLOSE_TAG_NAME,
106 STATE_INSIDE_PASSTHROUGH,
107 STATE_ERROR
108 } GMarkupParseState;
110 typedef struct
112 const char *prev_element;
113 const GMarkupParser *prev_parser;
114 gpointer prev_user_data;
115 } GMarkupRecursionTracker;
117 struct _GMarkupParseContext
119 const GMarkupParser *parser;
121 volatile gint ref_count;
123 GMarkupParseFlags flags;
125 gint line_number;
126 gint char_number;
128 GMarkupParseState state;
130 gpointer user_data;
131 GDestroyNotify dnotify;
133 /* A piece of character data or an element that
134 * hasn't "ended" yet so we haven't yet called
135 * the callback for it.
137 GString *partial_chunk;
138 GSList *spare_chunks;
140 GSList *tag_stack;
141 GSList *tag_stack_gstr;
142 GSList *spare_list_nodes;
144 GString **attr_names;
145 GString **attr_values;
146 gint cur_attr;
147 gint alloc_attrs;
149 const gchar *current_text;
150 gssize current_text_len;
151 const gchar *current_text_end;
153 /* used to save the start of the last interesting thingy */
154 const gchar *start;
156 const gchar *iter;
158 guint document_empty : 1;
159 guint parsing : 1;
160 guint awaiting_pop : 1;
161 gint balance;
163 /* subparser support */
164 GSList *subparser_stack; /* (GMarkupRecursionTracker *) */
165 const char *subparser_element;
166 gpointer held_user_data;
170 * Helpers to reduce our allocation overhead, we have
171 * a well defined allocation lifecycle.
173 static GSList *
174 get_list_node (GMarkupParseContext *context, gpointer data)
176 GSList *node;
177 if (context->spare_list_nodes != NULL)
179 node = context->spare_list_nodes;
180 context->spare_list_nodes = g_slist_remove_link (context->spare_list_nodes, node);
182 else
183 node = g_slist_alloc();
184 node->data = data;
185 return node;
188 static void
189 free_list_node (GMarkupParseContext *context, GSList *node)
191 node->data = NULL;
192 context->spare_list_nodes = g_slist_concat (node, context->spare_list_nodes);
195 static inline void
196 string_blank (GString *string)
198 string->str[0] = '\0';
199 string->len = 0;
203 * g_markup_parse_context_new:
204 * @parser: a #GMarkupParser
205 * @flags: one or more #GMarkupParseFlags
206 * @user_data: user data to pass to #GMarkupParser functions
207 * @user_data_dnotify: user data destroy notifier called when
208 * the parse context is freed
210 * Creates a new parse context. A parse context is used to parse
211 * marked-up documents. You can feed any number of documents into
212 * a context, as long as no errors occur; once an error occurs,
213 * the parse context can't continue to parse text (you have to
214 * free it and create a new parse context).
216 * Returns: a new #GMarkupParseContext
218 GMarkupParseContext *
219 g_markup_parse_context_new (const GMarkupParser *parser,
220 GMarkupParseFlags flags,
221 gpointer user_data,
222 GDestroyNotify user_data_dnotify)
224 GMarkupParseContext *context;
226 g_return_val_if_fail (parser != NULL, NULL);
228 context = g_new (GMarkupParseContext, 1);
230 context->ref_count = 1;
231 context->parser = parser;
232 context->flags = flags;
233 context->user_data = user_data;
234 context->dnotify = user_data_dnotify;
236 context->line_number = 1;
237 context->char_number = 1;
239 context->partial_chunk = NULL;
240 context->spare_chunks = NULL;
241 context->spare_list_nodes = NULL;
243 context->state = STATE_START;
244 context->tag_stack = NULL;
245 context->tag_stack_gstr = NULL;
246 context->attr_names = NULL;
247 context->attr_values = NULL;
248 context->cur_attr = -1;
249 context->alloc_attrs = 0;
251 context->current_text = NULL;
252 context->current_text_len = -1;
253 context->current_text_end = NULL;
255 context->start = NULL;
256 context->iter = NULL;
258 context->document_empty = TRUE;
259 context->parsing = FALSE;
261 context->awaiting_pop = FALSE;
262 context->subparser_stack = NULL;
263 context->subparser_element = NULL;
265 /* this is only looked at if awaiting_pop = TRUE. initialise anyway. */
266 context->held_user_data = NULL;
268 context->balance = 0;
270 return context;
274 * g_markup_parse_context_ref:
275 * @context: a #GMarkupParseContext
277 * Increases the reference count of @context.
279 * Returns: the same @context
281 * Since: 2.36
283 GMarkupParseContext *
284 g_markup_parse_context_ref (GMarkupParseContext *context)
286 g_return_val_if_fail (context != NULL, NULL);
287 g_return_val_if_fail (context->ref_count > 0, NULL);
289 g_atomic_int_inc (&context->ref_count);
291 return context;
295 * g_markup_parse_context_unref:
296 * @context: a #GMarkupParseContext
298 * Decreases the reference count of @context. When its reference count
299 * drops to 0, it is freed.
301 * Since: 2.36
303 void
304 g_markup_parse_context_unref (GMarkupParseContext *context)
306 g_return_if_fail (context != NULL);
307 g_return_if_fail (context->ref_count > 0);
309 if (g_atomic_int_dec_and_test (&context->ref_count))
310 g_markup_parse_context_free (context);
313 static void
314 string_full_free (gpointer ptr)
316 g_string_free (ptr, TRUE);
319 static void clear_attributes (GMarkupParseContext *context);
322 * g_markup_parse_context_free:
323 * @context: a #GMarkupParseContext
325 * Frees a #GMarkupParseContext.
327 * This function can't be called from inside one of the
328 * #GMarkupParser functions or while a subparser is pushed.
330 void
331 g_markup_parse_context_free (GMarkupParseContext *context)
333 g_return_if_fail (context != NULL);
334 g_return_if_fail (!context->parsing);
335 g_return_if_fail (!context->subparser_stack);
336 g_return_if_fail (!context->awaiting_pop);
338 if (context->dnotify)
339 (* context->dnotify) (context->user_data);
341 clear_attributes (context);
342 g_free (context->attr_names);
343 g_free (context->attr_values);
345 g_slist_free_full (context->tag_stack_gstr, string_full_free);
346 g_slist_free (context->tag_stack);
348 g_slist_free_full (context->spare_chunks, string_full_free);
349 g_slist_free (context->spare_list_nodes);
351 if (context->partial_chunk)
352 g_string_free (context->partial_chunk, TRUE);
354 g_free (context);
357 static void pop_subparser_stack (GMarkupParseContext *context);
359 static void
360 mark_error (GMarkupParseContext *context,
361 GError *error)
363 context->state = STATE_ERROR;
365 if (context->parser->error)
366 (*context->parser->error) (context, error, context->user_data);
368 /* report the error all the way up to free all the user-data */
369 while (context->subparser_stack)
371 pop_subparser_stack (context);
372 context->awaiting_pop = FALSE; /* already been freed */
374 if (context->parser->error)
375 (*context->parser->error) (context, error, context->user_data);
379 static void
380 set_error (GMarkupParseContext *context,
381 GError **error,
382 GMarkupError code,
383 const gchar *format,
384 ...) G_GNUC_PRINTF (4, 5);
386 static void
387 set_error_literal (GMarkupParseContext *context,
388 GError **error,
389 GMarkupError code,
390 const gchar *message)
392 GError *tmp_error;
394 tmp_error = g_error_new_literal (G_MARKUP_ERROR, code, message);
396 g_prefix_error (&tmp_error,
397 _("Error on line %d char %d: "),
398 context->line_number,
399 context->char_number);
401 mark_error (context, tmp_error);
403 g_propagate_error (error, tmp_error);
406 G_GNUC_PRINTF(4, 5)
407 static void
408 set_error (GMarkupParseContext *context,
409 GError **error,
410 GMarkupError code,
411 const gchar *format,
412 ...)
414 gchar *s;
415 gchar *s_valid;
416 va_list args;
418 va_start (args, format);
419 s = g_strdup_vprintf (format, args);
420 va_end (args);
422 /* Make sure that the GError message is valid UTF-8
423 * even if it is complaining about invalid UTF-8 in the markup
425 s_valid = g_utf8_make_valid (s, -1);
426 set_error_literal (context, error, code, s);
428 g_free (s);
429 g_free (s_valid);
432 static void
433 propagate_error (GMarkupParseContext *context,
434 GError **dest,
435 GError *src)
437 if (context->flags & G_MARKUP_PREFIX_ERROR_POSITION)
438 g_prefix_error (&src,
439 _("Error on line %d char %d: "),
440 context->line_number,
441 context->char_number);
443 mark_error (context, src);
445 g_propagate_error (dest, src);
448 #define IS_COMMON_NAME_END_CHAR(c) \
449 ((c) == '=' || (c) == '/' || (c) == '>' || (c) == ' ')
451 static gboolean
452 slow_name_validate (GMarkupParseContext *context,
453 const gchar *name,
454 GError **error)
456 const gchar *p = name;
458 if (!g_utf8_validate (name, strlen (name), NULL))
460 set_error (context, error, G_MARKUP_ERROR_BAD_UTF8,
461 _("Invalid UTF-8 encoded text in name — not valid “%s”"), name);
462 return FALSE;
465 if (!(g_ascii_isalpha (*p) ||
466 (!IS_COMMON_NAME_END_CHAR (*p) &&
467 (*p == '_' ||
468 *p == ':' ||
469 g_unichar_isalpha (g_utf8_get_char (p))))))
471 set_error (context, error, G_MARKUP_ERROR_PARSE,
472 _("“%s” is not a valid name"), name);
473 return FALSE;
476 for (p = g_utf8_next_char (name); *p != '\0'; p = g_utf8_next_char (p))
478 /* is_name_char */
479 if (!(g_ascii_isalnum (*p) ||
480 (!IS_COMMON_NAME_END_CHAR (*p) &&
481 (*p == '.' ||
482 *p == '-' ||
483 *p == '_' ||
484 *p == ':' ||
485 g_unichar_isalpha (g_utf8_get_char (p))))))
487 set_error (context, error, G_MARKUP_ERROR_PARSE,
488 _("“%s” is not a valid name: “%c”"), name, *p);
489 return FALSE;
492 return TRUE;
496 * Use me for elements, attributes etc.
498 static gboolean
499 name_validate (GMarkupParseContext *context,
500 const gchar *name,
501 GError **error)
503 char mask;
504 const char *p;
506 /* name start char */
507 p = name;
508 if (G_UNLIKELY (IS_COMMON_NAME_END_CHAR (*p) ||
509 !(g_ascii_isalpha (*p) || *p == '_' || *p == ':')))
510 goto slow_validate;
512 for (mask = *p++; *p != '\0'; p++)
514 mask |= *p;
516 /* is_name_char */
517 if (G_UNLIKELY (!(g_ascii_isalnum (*p) ||
518 (!IS_COMMON_NAME_END_CHAR (*p) &&
519 (*p == '.' ||
520 *p == '-' ||
521 *p == '_' ||
522 *p == ':')))))
523 goto slow_validate;
526 if (mask & 0x80) /* un-common / non-ascii */
527 goto slow_validate;
529 return TRUE;
531 slow_validate:
532 return slow_name_validate (context, name, error);
535 static gboolean
536 text_validate (GMarkupParseContext *context,
537 const gchar *p,
538 gint len,
539 GError **error)
541 if (!g_utf8_validate (p, len, NULL))
543 set_error (context, error, G_MARKUP_ERROR_BAD_UTF8,
544 _("Invalid UTF-8 encoded text in name — not valid “%s”"), p);
545 return FALSE;
547 else
548 return TRUE;
551 static gchar*
552 char_str (gunichar c,
553 gchar *buf)
555 memset (buf, 0, 8);
556 g_unichar_to_utf8 (c, buf);
557 return buf;
560 /* Format the next UTF-8 character as a gchar* for printing in error output
561 * when we encounter a syntax error. This correctly handles invalid UTF-8,
562 * emitting it as hex escapes. */
563 static gchar*
564 utf8_str (const gchar *utf8,
565 gchar *buf)
567 gunichar c = g_utf8_get_char_validated (utf8, -1);
568 if (c == (gunichar) -1 || c == (gunichar) -2)
570 gchar *temp = g_strdup_printf ("\\x%02x", (guint)(guchar)*utf8);
571 memset (buf, 0, 8);
572 memcpy (buf, temp, strlen (temp));
573 g_free (temp);
575 else
576 char_str (c, buf);
577 return buf;
580 G_GNUC_PRINTF(5, 6)
581 static void
582 set_unescape_error (GMarkupParseContext *context,
583 GError **error,
584 const gchar *remaining_text,
585 GMarkupError code,
586 const gchar *format,
587 ...)
589 GError *tmp_error;
590 gchar *s;
591 va_list args;
592 gint remaining_newlines;
593 const gchar *p;
595 remaining_newlines = 0;
596 p = remaining_text;
597 while (*p != '\0')
599 if (*p == '\n')
600 ++remaining_newlines;
601 ++p;
604 va_start (args, format);
605 s = g_strdup_vprintf (format, args);
606 va_end (args);
608 tmp_error = g_error_new (G_MARKUP_ERROR,
609 code,
610 _("Error on line %d: %s"),
611 context->line_number - remaining_newlines,
614 g_free (s);
616 mark_error (context, tmp_error);
618 g_propagate_error (error, tmp_error);
622 * re-write the GString in-place, unescaping anything that escaped.
623 * most XML does not contain entities, or escaping.
625 static gboolean
626 unescape_gstring_inplace (GMarkupParseContext *context,
627 GString *string,
628 gboolean *is_ascii,
629 GError **error)
631 char mask, *to;
632 const char *from;
633 gboolean normalize_attribute;
635 *is_ascii = FALSE;
637 /* are we unescaping an attribute or not ? */
638 if (context->state == STATE_INSIDE_ATTRIBUTE_VALUE_SQ ||
639 context->state == STATE_INSIDE_ATTRIBUTE_VALUE_DQ)
640 normalize_attribute = TRUE;
641 else
642 normalize_attribute = FALSE;
645 * Meeks' theorem: unescaping can only shrink text.
646 * for &lt; etc. this is obvious, for &#xffff; more
647 * thought is required, but this is patently so.
649 mask = 0;
650 for (from = to = string->str; *from != '\0'; from++, to++)
652 *to = *from;
654 mask |= *to;
655 if (normalize_attribute && (*to == '\t' || *to == '\n'))
656 *to = ' ';
657 if (*to == '\r')
659 *to = normalize_attribute ? ' ' : '\n';
660 if (from[1] == '\n')
661 from++;
663 if (*from == '&')
665 from++;
666 if (*from == '#')
668 gint base = 10;
669 gulong l;
670 gchar *end = NULL;
672 from++;
674 if (*from == 'x')
676 base = 16;
677 from++;
680 errno = 0;
681 l = strtoul (from, &end, base);
683 if (end == from || errno != 0)
685 set_unescape_error (context, error,
686 from, G_MARKUP_ERROR_PARSE,
687 _("Failed to parse “%-.*s”, which "
688 "should have been a digit "
689 "inside a character reference "
690 "(&#234; for example) — perhaps "
691 "the digit is too large"),
692 (int)(end - from), from);
693 return FALSE;
695 else if (*end != ';')
697 set_unescape_error (context, error,
698 from, G_MARKUP_ERROR_PARSE,
699 _("Character reference did not end with a "
700 "semicolon; "
701 "most likely you used an ampersand "
702 "character without intending to start "
703 "an entity — escape ampersand as &amp;"));
704 return FALSE;
706 else
708 /* characters XML 1.1 permits */
709 if ((0 < l && l <= 0xD7FF) ||
710 (0xE000 <= l && l <= 0xFFFD) ||
711 (0x10000 <= l && l <= 0x10FFFF))
713 gchar buf[8];
714 char_str (l, buf);
715 strcpy (to, buf);
716 to += strlen (buf) - 1;
717 from = end;
718 if (l >= 0x80) /* not ascii */
719 mask |= 0x80;
721 else
723 set_unescape_error (context, error,
724 from, G_MARKUP_ERROR_PARSE,
725 _("Character reference “%-.*s” does not "
726 "encode a permitted character"),
727 (int)(end - from), from);
728 return FALSE;
733 else if (strncmp (from, "lt;", 3) == 0)
735 *to = '<';
736 from += 2;
738 else if (strncmp (from, "gt;", 3) == 0)
740 *to = '>';
741 from += 2;
743 else if (strncmp (from, "amp;", 4) == 0)
745 *to = '&';
746 from += 3;
748 else if (strncmp (from, "quot;", 5) == 0)
750 *to = '"';
751 from += 4;
753 else if (strncmp (from, "apos;", 5) == 0)
755 *to = '\'';
756 from += 4;
758 else
760 if (*from == ';')
761 set_unescape_error (context, error,
762 from, G_MARKUP_ERROR_PARSE,
763 _("Empty entity “&;” seen; valid "
764 "entities are: &amp; &quot; &lt; &gt; &apos;"));
765 else
767 const char *end = strchr (from, ';');
768 if (end)
769 set_unescape_error (context, error,
770 from, G_MARKUP_ERROR_PARSE,
771 _("Entity name “%-.*s” is not known"),
772 (int)(end - from), from);
773 else
774 set_unescape_error (context, error,
775 from, G_MARKUP_ERROR_PARSE,
776 _("Entity did not end with a semicolon; "
777 "most likely you used an ampersand "
778 "character without intending to start "
779 "an entity — escape ampersand as &amp;"));
781 return FALSE;
786 g_assert (to - string->str <= string->len);
787 if (to - string->str != string->len)
788 g_string_truncate (string, to - string->str);
790 *is_ascii = !(mask & 0x80);
792 return TRUE;
795 static inline gboolean
796 advance_char (GMarkupParseContext *context)
798 context->iter++;
799 context->char_number++;
801 if (G_UNLIKELY (context->iter == context->current_text_end))
802 return FALSE;
804 else if (G_UNLIKELY (*context->iter == '\n'))
806 context->line_number++;
807 context->char_number = 1;
810 return TRUE;
813 static inline gboolean
814 xml_isspace (char c)
816 return c == ' ' || c == '\t' || c == '\n' || c == '\r';
819 static void
820 skip_spaces (GMarkupParseContext *context)
824 if (!xml_isspace (*context->iter))
825 return;
827 while (advance_char (context));
830 static void
831 advance_to_name_end (GMarkupParseContext *context)
835 if (IS_COMMON_NAME_END_CHAR (*(context->iter)))
836 return;
837 if (xml_isspace (*(context->iter)))
838 return;
840 while (advance_char (context));
843 static void
844 release_chunk (GMarkupParseContext *context, GString *str)
846 GSList *node;
847 if (!str)
848 return;
849 if (str->allocated_len > 256)
850 { /* large strings are unusual and worth freeing */
851 g_string_free (str, TRUE);
852 return;
854 string_blank (str);
855 node = get_list_node (context, str);
856 context->spare_chunks = g_slist_concat (node, context->spare_chunks);
859 static void
860 add_to_partial (GMarkupParseContext *context,
861 const gchar *text_start,
862 const gchar *text_end)
864 if (context->partial_chunk == NULL)
865 { /* allocate a new chunk to parse into */
867 if (context->spare_chunks != NULL)
869 GSList *node = context->spare_chunks;
870 context->spare_chunks = g_slist_remove_link (context->spare_chunks, node);
871 context->partial_chunk = node->data;
872 free_list_node (context, node);
874 else
875 context->partial_chunk = g_string_sized_new (MAX (28, text_end - text_start));
878 if (text_start != text_end)
879 g_string_insert_len (context->partial_chunk, -1,
880 text_start, text_end - text_start);
883 static inline void
884 truncate_partial (GMarkupParseContext *context)
886 if (context->partial_chunk != NULL)
887 string_blank (context->partial_chunk);
890 static inline const gchar*
891 current_element (GMarkupParseContext *context)
893 return context->tag_stack->data;
896 static void
897 pop_subparser_stack (GMarkupParseContext *context)
899 GMarkupRecursionTracker *tracker;
901 g_assert (context->subparser_stack);
903 tracker = context->subparser_stack->data;
905 context->awaiting_pop = TRUE;
906 context->held_user_data = context->user_data;
908 context->user_data = tracker->prev_user_data;
909 context->parser = tracker->prev_parser;
910 context->subparser_element = tracker->prev_element;
911 g_slice_free (GMarkupRecursionTracker, tracker);
913 context->subparser_stack = g_slist_delete_link (context->subparser_stack,
914 context->subparser_stack);
917 static void
918 push_partial_as_tag (GMarkupParseContext *context)
920 GString *str = context->partial_chunk;
921 /* sadly, this is exported by gmarkup_get_element_stack as-is */
922 context->tag_stack = g_slist_concat (get_list_node (context, str->str), context->tag_stack);
923 context->tag_stack_gstr = g_slist_concat (get_list_node (context, str), context->tag_stack_gstr);
924 context->partial_chunk = NULL;
927 static void
928 pop_tag (GMarkupParseContext *context)
930 GSList *nodea, *nodeb;
932 nodea = context->tag_stack;
933 nodeb = context->tag_stack_gstr;
934 release_chunk (context, nodeb->data);
935 context->tag_stack = g_slist_remove_link (context->tag_stack, nodea);
936 context->tag_stack_gstr = g_slist_remove_link (context->tag_stack_gstr, nodeb);
937 free_list_node (context, nodea);
938 free_list_node (context, nodeb);
941 static void
942 possibly_finish_subparser (GMarkupParseContext *context)
944 if (current_element (context) == context->subparser_element)
945 pop_subparser_stack (context);
948 static void
949 ensure_no_outstanding_subparser (GMarkupParseContext *context)
951 if (context->awaiting_pop)
952 g_critical ("During the first end_element call after invoking a "
953 "subparser you must pop the subparser stack and handle "
954 "the freeing of the subparser user_data. This can be "
955 "done by calling the end function of the subparser. "
956 "Very probably, your program just leaked memory.");
958 /* let valgrind watch the pointer disappear... */
959 context->held_user_data = NULL;
960 context->awaiting_pop = FALSE;
963 static const gchar*
964 current_attribute (GMarkupParseContext *context)
966 g_assert (context->cur_attr >= 0);
967 return context->attr_names[context->cur_attr]->str;
970 static void
971 add_attribute (GMarkupParseContext *context, GString *str)
973 if (context->cur_attr + 2 >= context->alloc_attrs)
975 context->alloc_attrs += 5; /* silly magic number */
976 context->attr_names = g_realloc (context->attr_names, sizeof(GString*)*context->alloc_attrs);
977 context->attr_values = g_realloc (context->attr_values, sizeof(GString*)*context->alloc_attrs);
979 context->cur_attr++;
980 context->attr_names[context->cur_attr] = str;
981 context->attr_values[context->cur_attr] = NULL;
982 context->attr_names[context->cur_attr+1] = NULL;
983 context->attr_values[context->cur_attr+1] = NULL;
986 static void
987 clear_attributes (GMarkupParseContext *context)
989 /* Go ahead and free the attributes. */
990 for (; context->cur_attr >= 0; context->cur_attr--)
992 int pos = context->cur_attr;
993 release_chunk (context, context->attr_names[pos]);
994 release_chunk (context, context->attr_values[pos]);
995 context->attr_names[pos] = context->attr_values[pos] = NULL;
997 g_assert (context->cur_attr == -1);
998 g_assert (context->attr_names == NULL ||
999 context->attr_names[0] == NULL);
1000 g_assert (context->attr_values == NULL ||
1001 context->attr_values[0] == NULL);
1004 /* This has to be a separate function to ensure the alloca's
1005 * are unwound on exit - otherwise we grow & blow the stack
1006 * with large documents
1008 static inline void
1009 emit_start_element (GMarkupParseContext *context,
1010 GError **error)
1012 int i, j = 0;
1013 const gchar *start_name;
1014 const gchar **attr_names;
1015 const gchar **attr_values;
1016 GError *tmp_error;
1018 /* In case we want to ignore qualified tags and we see that we have
1019 * one here, we push a subparser. This will ignore all tags inside of
1020 * the qualified tag.
1022 * We deal with the end of the subparser from emit_end_element.
1024 if ((context->flags & G_MARKUP_IGNORE_QUALIFIED) && strchr (current_element (context), ':'))
1026 static const GMarkupParser ignore_parser;
1027 g_markup_parse_context_push (context, &ignore_parser, NULL);
1028 clear_attributes (context);
1029 return;
1032 attr_names = g_newa (const gchar *, context->cur_attr + 2);
1033 attr_values = g_newa (const gchar *, context->cur_attr + 2);
1034 for (i = 0; i < context->cur_attr + 1; i++)
1036 /* Possibly omit qualified attribute names from the list */
1037 if ((context->flags & G_MARKUP_IGNORE_QUALIFIED) && strchr (context->attr_names[i]->str, ':'))
1038 continue;
1040 attr_names[j] = context->attr_names[i]->str;
1041 attr_values[j] = context->attr_values[i]->str;
1042 j++;
1044 attr_names[j] = NULL;
1045 attr_values[j] = NULL;
1047 /* Call user callback for element start */
1048 tmp_error = NULL;
1049 start_name = current_element (context);
1051 if (context->parser->start_element &&
1052 name_validate (context, start_name, error))
1053 (* context->parser->start_element) (context,
1054 start_name,
1055 (const gchar **)attr_names,
1056 (const gchar **)attr_values,
1057 context->user_data,
1058 &tmp_error);
1059 clear_attributes (context);
1061 if (tmp_error != NULL)
1062 propagate_error (context, error, tmp_error);
1065 static void
1066 emit_end_element (GMarkupParseContext *context,
1067 GError **error)
1069 /* We need to pop the tag stack and call the end_element
1070 * function, since this is the close tag
1072 GError *tmp_error = NULL;
1074 g_assert (context->tag_stack != NULL);
1076 possibly_finish_subparser (context);
1078 /* We might have just returned from our ignore subparser */
1079 if ((context->flags & G_MARKUP_IGNORE_QUALIFIED) && strchr (current_element (context), ':'))
1081 g_markup_parse_context_pop (context);
1082 pop_tag (context);
1083 return;
1086 tmp_error = NULL;
1087 if (context->parser->end_element)
1088 (* context->parser->end_element) (context,
1089 current_element (context),
1090 context->user_data,
1091 &tmp_error);
1093 ensure_no_outstanding_subparser (context);
1095 if (tmp_error)
1097 mark_error (context, tmp_error);
1098 g_propagate_error (error, tmp_error);
1101 pop_tag (context);
1105 * g_markup_parse_context_parse:
1106 * @context: a #GMarkupParseContext
1107 * @text: chunk of text to parse
1108 * @text_len: length of @text in bytes
1109 * @error: return location for a #GError
1111 * Feed some data to the #GMarkupParseContext.
1113 * The data need not be valid UTF-8; an error will be signaled if
1114 * it's invalid. The data need not be an entire document; you can
1115 * feed a document into the parser incrementally, via multiple calls
1116 * to this function. Typically, as you receive data from a network
1117 * connection or file, you feed each received chunk of data into this
1118 * function, aborting the process if an error occurs. Once an error
1119 * is reported, no further data may be fed to the #GMarkupParseContext;
1120 * all errors are fatal.
1122 * Returns: %FALSE if an error occurred, %TRUE on success
1124 gboolean
1125 g_markup_parse_context_parse (GMarkupParseContext *context,
1126 const gchar *text,
1127 gssize text_len,
1128 GError **error)
1130 g_return_val_if_fail (context != NULL, FALSE);
1131 g_return_val_if_fail (text != NULL, FALSE);
1132 g_return_val_if_fail (context->state != STATE_ERROR, FALSE);
1133 g_return_val_if_fail (!context->parsing, FALSE);
1135 if (text_len < 0)
1136 text_len = strlen (text);
1138 if (text_len == 0)
1139 return TRUE;
1141 context->parsing = TRUE;
1144 context->current_text = text;
1145 context->current_text_len = text_len;
1146 context->current_text_end = context->current_text + text_len;
1147 context->iter = context->current_text;
1148 context->start = context->iter;
1150 while (context->iter != context->current_text_end)
1152 switch (context->state)
1154 case STATE_START:
1155 /* Possible next state: AFTER_OPEN_ANGLE */
1157 g_assert (context->tag_stack == NULL);
1159 /* whitespace is ignored outside of any elements */
1160 skip_spaces (context);
1162 if (context->iter != context->current_text_end)
1164 if (*context->iter == '<')
1166 /* Move after the open angle */
1167 advance_char (context);
1169 context->state = STATE_AFTER_OPEN_ANGLE;
1171 /* this could start a passthrough */
1172 context->start = context->iter;
1174 /* document is now non-empty */
1175 context->document_empty = FALSE;
1177 else
1179 set_error_literal (context,
1180 error,
1181 G_MARKUP_ERROR_PARSE,
1182 _("Document must begin with an element (e.g. <book>)"));
1185 break;
1187 case STATE_AFTER_OPEN_ANGLE:
1188 /* Possible next states: INSIDE_OPEN_TAG_NAME,
1189 * AFTER_CLOSE_TAG_SLASH, INSIDE_PASSTHROUGH
1191 if (*context->iter == '?' ||
1192 *context->iter == '!')
1194 /* include < in the passthrough */
1195 const gchar *openangle = "<";
1196 add_to_partial (context, openangle, openangle + 1);
1197 context->start = context->iter;
1198 context->balance = 1;
1199 context->state = STATE_INSIDE_PASSTHROUGH;
1201 else if (*context->iter == '/')
1203 /* move after it */
1204 advance_char (context);
1206 context->state = STATE_AFTER_CLOSE_TAG_SLASH;
1208 else if (!IS_COMMON_NAME_END_CHAR (*(context->iter)))
1210 context->state = STATE_INSIDE_OPEN_TAG_NAME;
1212 /* start of tag name */
1213 context->start = context->iter;
1215 else
1217 gchar buf[8];
1219 set_error (context,
1220 error,
1221 G_MARKUP_ERROR_PARSE,
1222 _("“%s” is not a valid character following "
1223 "a “<” character; it may not begin an "
1224 "element name"),
1225 utf8_str (context->iter, buf));
1227 break;
1229 /* The AFTER_CLOSE_ANGLE state is actually sort of
1230 * broken, because it doesn't correspond to a range
1231 * of characters in the input stream as the others do,
1232 * and thus makes things harder to conceptualize
1234 case STATE_AFTER_CLOSE_ANGLE:
1235 /* Possible next states: INSIDE_TEXT, STATE_START */
1236 if (context->tag_stack == NULL)
1238 context->start = NULL;
1239 context->state = STATE_START;
1241 else
1243 context->start = context->iter;
1244 context->state = STATE_INSIDE_TEXT;
1246 break;
1248 case STATE_AFTER_ELISION_SLASH:
1249 /* Possible next state: AFTER_CLOSE_ANGLE */
1250 if (*context->iter == '>')
1252 /* move after the close angle */
1253 advance_char (context);
1254 context->state = STATE_AFTER_CLOSE_ANGLE;
1255 emit_end_element (context, error);
1257 else
1259 gchar buf[8];
1261 set_error (context,
1262 error,
1263 G_MARKUP_ERROR_PARSE,
1264 _("Odd character “%s”, expected a “>” character "
1265 "to end the empty-element tag “%s”"),
1266 utf8_str (context->iter, buf),
1267 current_element (context));
1269 break;
1271 case STATE_INSIDE_OPEN_TAG_NAME:
1272 /* Possible next states: BETWEEN_ATTRIBUTES */
1274 /* if there's a partial chunk then it's the first part of the
1275 * tag name. If there's a context->start then it's the start
1276 * of the tag name in current_text, the partial chunk goes
1277 * before that start though.
1279 advance_to_name_end (context);
1281 if (context->iter == context->current_text_end)
1283 /* The name hasn't necessarily ended. Merge with
1284 * partial chunk, leave state unchanged.
1286 add_to_partial (context, context->start, context->iter);
1288 else
1290 /* The name has ended. Combine it with the partial chunk
1291 * if any; push it on the stack; enter next state.
1293 add_to_partial (context, context->start, context->iter);
1294 push_partial_as_tag (context);
1296 context->state = STATE_BETWEEN_ATTRIBUTES;
1297 context->start = NULL;
1299 break;
1301 case STATE_INSIDE_ATTRIBUTE_NAME:
1302 /* Possible next states: AFTER_ATTRIBUTE_NAME */
1304 advance_to_name_end (context);
1305 add_to_partial (context, context->start, context->iter);
1307 /* read the full name, if we enter the equals sign state
1308 * then add the attribute to the list (without the value),
1309 * otherwise store a partial chunk to be prepended later.
1311 if (context->iter != context->current_text_end)
1312 context->state = STATE_AFTER_ATTRIBUTE_NAME;
1313 break;
1315 case STATE_AFTER_ATTRIBUTE_NAME:
1316 /* Possible next states: AFTER_ATTRIBUTE_EQUALS_SIGN */
1318 skip_spaces (context);
1320 if (context->iter != context->current_text_end)
1322 /* The name has ended. Combine it with the partial chunk
1323 * if any; push it on the stack; enter next state.
1325 if (!name_validate (context, context->partial_chunk->str, error))
1326 break;
1328 add_attribute (context, context->partial_chunk);
1330 context->partial_chunk = NULL;
1331 context->start = NULL;
1333 if (*context->iter == '=')
1335 advance_char (context);
1336 context->state = STATE_AFTER_ATTRIBUTE_EQUALS_SIGN;
1338 else
1340 gchar buf[8];
1342 set_error (context,
1343 error,
1344 G_MARKUP_ERROR_PARSE,
1345 _("Odd character “%s”, expected a “=” after "
1346 "attribute name “%s” of element “%s”"),
1347 utf8_str (context->iter, buf),
1348 current_attribute (context),
1349 current_element (context));
1353 break;
1355 case STATE_BETWEEN_ATTRIBUTES:
1356 /* Possible next states: AFTER_CLOSE_ANGLE,
1357 * AFTER_ELISION_SLASH, INSIDE_ATTRIBUTE_NAME
1359 skip_spaces (context);
1361 if (context->iter != context->current_text_end)
1363 if (*context->iter == '/')
1365 advance_char (context);
1366 context->state = STATE_AFTER_ELISION_SLASH;
1368 else if (*context->iter == '>')
1370 advance_char (context);
1371 context->state = STATE_AFTER_CLOSE_ANGLE;
1373 else if (!IS_COMMON_NAME_END_CHAR (*(context->iter)))
1375 context->state = STATE_INSIDE_ATTRIBUTE_NAME;
1376 /* start of attribute name */
1377 context->start = context->iter;
1379 else
1381 gchar buf[8];
1383 set_error (context,
1384 error,
1385 G_MARKUP_ERROR_PARSE,
1386 _("Odd character “%s”, expected a “>” or “/” "
1387 "character to end the start tag of "
1388 "element “%s”, or optionally an attribute; "
1389 "perhaps you used an invalid character in "
1390 "an attribute name"),
1391 utf8_str (context->iter, buf),
1392 current_element (context));
1395 /* If we're done with attributes, invoke
1396 * the start_element callback
1398 if (context->state == STATE_AFTER_ELISION_SLASH ||
1399 context->state == STATE_AFTER_CLOSE_ANGLE)
1400 emit_start_element (context, error);
1402 break;
1404 case STATE_AFTER_ATTRIBUTE_EQUALS_SIGN:
1405 /* Possible next state: INSIDE_ATTRIBUTE_VALUE_[SQ/DQ] */
1407 skip_spaces (context);
1409 if (context->iter != context->current_text_end)
1411 if (*context->iter == '"')
1413 advance_char (context);
1414 context->state = STATE_INSIDE_ATTRIBUTE_VALUE_DQ;
1415 context->start = context->iter;
1417 else if (*context->iter == '\'')
1419 advance_char (context);
1420 context->state = STATE_INSIDE_ATTRIBUTE_VALUE_SQ;
1421 context->start = context->iter;
1423 else
1425 gchar buf[8];
1427 set_error (context,
1428 error,
1429 G_MARKUP_ERROR_PARSE,
1430 _("Odd character “%s”, expected an open quote mark "
1431 "after the equals sign when giving value for "
1432 "attribute “%s” of element “%s”"),
1433 utf8_str (context->iter, buf),
1434 current_attribute (context),
1435 current_element (context));
1438 break;
1440 case STATE_INSIDE_ATTRIBUTE_VALUE_SQ:
1441 case STATE_INSIDE_ATTRIBUTE_VALUE_DQ:
1442 /* Possible next states: BETWEEN_ATTRIBUTES */
1444 gchar delim;
1446 if (context->state == STATE_INSIDE_ATTRIBUTE_VALUE_SQ)
1448 delim = '\'';
1450 else
1452 delim = '"';
1457 if (*context->iter == delim)
1458 break;
1460 while (advance_char (context));
1462 if (context->iter == context->current_text_end)
1464 /* The value hasn't necessarily ended. Merge with
1465 * partial chunk, leave state unchanged.
1467 add_to_partial (context, context->start, context->iter);
1469 else
1471 gboolean is_ascii;
1472 /* The value has ended at the quote mark. Combine it
1473 * with the partial chunk if any; set it for the current
1474 * attribute.
1476 add_to_partial (context, context->start, context->iter);
1478 g_assert (context->cur_attr >= 0);
1480 if (unescape_gstring_inplace (context, context->partial_chunk, &is_ascii, error) &&
1481 (is_ascii || text_validate (context, context->partial_chunk->str,
1482 context->partial_chunk->len, error)))
1484 /* success, advance past quote and set state. */
1485 context->attr_values[context->cur_attr] = context->partial_chunk;
1486 context->partial_chunk = NULL;
1487 advance_char (context);
1488 context->state = STATE_BETWEEN_ATTRIBUTES;
1489 context->start = NULL;
1492 truncate_partial (context);
1494 break;
1496 case STATE_INSIDE_TEXT:
1497 /* Possible next states: AFTER_OPEN_ANGLE */
1500 if (*context->iter == '<')
1501 break;
1503 while (advance_char (context));
1505 /* The text hasn't necessarily ended. Merge with
1506 * partial chunk, leave state unchanged.
1509 add_to_partial (context, context->start, context->iter);
1511 if (context->iter != context->current_text_end)
1513 gboolean is_ascii;
1515 /* The text has ended at the open angle. Call the text
1516 * callback.
1518 if (unescape_gstring_inplace (context, context->partial_chunk, &is_ascii, error) &&
1519 (is_ascii || text_validate (context, context->partial_chunk->str,
1520 context->partial_chunk->len, error)))
1522 GError *tmp_error = NULL;
1524 if (context->parser->text)
1525 (*context->parser->text) (context,
1526 context->partial_chunk->str,
1527 context->partial_chunk->len,
1528 context->user_data,
1529 &tmp_error);
1531 if (tmp_error == NULL)
1533 /* advance past open angle and set state. */
1534 advance_char (context);
1535 context->state = STATE_AFTER_OPEN_ANGLE;
1536 /* could begin a passthrough */
1537 context->start = context->iter;
1539 else
1540 propagate_error (context, error, tmp_error);
1543 truncate_partial (context);
1545 break;
1547 case STATE_AFTER_CLOSE_TAG_SLASH:
1548 /* Possible next state: INSIDE_CLOSE_TAG_NAME */
1549 if (!IS_COMMON_NAME_END_CHAR (*(context->iter)))
1551 context->state = STATE_INSIDE_CLOSE_TAG_NAME;
1553 /* start of tag name */
1554 context->start = context->iter;
1556 else
1558 gchar buf[8];
1560 set_error (context,
1561 error,
1562 G_MARKUP_ERROR_PARSE,
1563 _("“%s” is not a valid character following "
1564 "the characters “</”; “%s” may not begin an "
1565 "element name"),
1566 utf8_str (context->iter, buf),
1567 utf8_str (context->iter, buf));
1569 break;
1571 case STATE_INSIDE_CLOSE_TAG_NAME:
1572 /* Possible next state: AFTER_CLOSE_TAG_NAME */
1573 advance_to_name_end (context);
1574 add_to_partial (context, context->start, context->iter);
1576 if (context->iter != context->current_text_end)
1577 context->state = STATE_AFTER_CLOSE_TAG_NAME;
1578 break;
1580 case STATE_AFTER_CLOSE_TAG_NAME:
1581 /* Possible next state: AFTER_CLOSE_TAG_SLASH */
1583 skip_spaces (context);
1585 if (context->iter != context->current_text_end)
1587 GString *close_name;
1589 close_name = context->partial_chunk;
1590 context->partial_chunk = NULL;
1592 if (*context->iter != '>')
1594 gchar buf[8];
1596 set_error (context,
1597 error,
1598 G_MARKUP_ERROR_PARSE,
1599 _("“%s” is not a valid character following "
1600 "the close element name “%s”; the allowed "
1601 "character is “>”"),
1602 utf8_str (context->iter, buf),
1603 close_name->str);
1605 else if (context->tag_stack == NULL)
1607 set_error (context,
1608 error,
1609 G_MARKUP_ERROR_PARSE,
1610 _("Element “%s” was closed, no element "
1611 "is currently open"),
1612 close_name->str);
1614 else if (strcmp (close_name->str, current_element (context)) != 0)
1616 set_error (context,
1617 error,
1618 G_MARKUP_ERROR_PARSE,
1619 _("Element “%s” was closed, but the currently "
1620 "open element is “%s”"),
1621 close_name->str,
1622 current_element (context));
1624 else
1626 advance_char (context);
1627 context->state = STATE_AFTER_CLOSE_ANGLE;
1628 context->start = NULL;
1630 emit_end_element (context, error);
1632 context->partial_chunk = close_name;
1633 truncate_partial (context);
1635 break;
1637 case STATE_INSIDE_PASSTHROUGH:
1638 /* Possible next state: AFTER_CLOSE_ANGLE */
1641 if (*context->iter == '<')
1642 context->balance++;
1643 if (*context->iter == '>')
1645 gchar *str;
1646 gsize len;
1648 context->balance--;
1649 add_to_partial (context, context->start, context->iter);
1650 context->start = context->iter;
1652 str = context->partial_chunk->str;
1653 len = context->partial_chunk->len;
1655 if (str[1] == '?' && str[len - 1] == '?')
1656 break;
1657 if (strncmp (str, "<!--", 4) == 0 &&
1658 strcmp (str + len - 2, "--") == 0)
1659 break;
1660 if (strncmp (str, "<![CDATA[", 9) == 0 &&
1661 strcmp (str + len - 2, "]]") == 0)
1662 break;
1663 if (strncmp (str, "<!DOCTYPE", 9) == 0 &&
1664 context->balance == 0)
1665 break;
1668 while (advance_char (context));
1670 if (context->iter == context->current_text_end)
1672 /* The passthrough hasn't necessarily ended. Merge with
1673 * partial chunk, leave state unchanged.
1675 add_to_partial (context, context->start, context->iter);
1677 else
1679 /* The passthrough has ended at the close angle. Combine
1680 * it with the partial chunk if any. Call the passthrough
1681 * callback. Note that the open/close angles are
1682 * included in the text of the passthrough.
1684 GError *tmp_error = NULL;
1686 advance_char (context); /* advance past close angle */
1687 add_to_partial (context, context->start, context->iter);
1689 if (context->flags & G_MARKUP_TREAT_CDATA_AS_TEXT &&
1690 strncmp (context->partial_chunk->str, "<![CDATA[", 9) == 0)
1692 if (context->parser->text &&
1693 text_validate (context,
1694 context->partial_chunk->str + 9,
1695 context->partial_chunk->len - 12,
1696 error))
1697 (*context->parser->text) (context,
1698 context->partial_chunk->str + 9,
1699 context->partial_chunk->len - 12,
1700 context->user_data,
1701 &tmp_error);
1703 else if (context->parser->passthrough &&
1704 text_validate (context,
1705 context->partial_chunk->str,
1706 context->partial_chunk->len,
1707 error))
1708 (*context->parser->passthrough) (context,
1709 context->partial_chunk->str,
1710 context->partial_chunk->len,
1711 context->user_data,
1712 &tmp_error);
1714 truncate_partial (context);
1716 if (tmp_error == NULL)
1718 context->state = STATE_AFTER_CLOSE_ANGLE;
1719 context->start = context->iter; /* could begin text */
1721 else
1722 propagate_error (context, error, tmp_error);
1724 break;
1726 case STATE_ERROR:
1727 goto finished;
1728 break;
1730 default:
1731 g_assert_not_reached ();
1732 break;
1736 finished:
1737 context->parsing = FALSE;
1739 return context->state != STATE_ERROR;
1743 * g_markup_parse_context_end_parse:
1744 * @context: a #GMarkupParseContext
1745 * @error: return location for a #GError
1747 * Signals to the #GMarkupParseContext that all data has been
1748 * fed into the parse context with g_markup_parse_context_parse().
1750 * This function reports an error if the document isn't complete,
1751 * for example if elements are still open.
1753 * Returns: %TRUE on success, %FALSE if an error was set
1755 gboolean
1756 g_markup_parse_context_end_parse (GMarkupParseContext *context,
1757 GError **error)
1759 g_return_val_if_fail (context != NULL, FALSE);
1760 g_return_val_if_fail (!context->parsing, FALSE);
1761 g_return_val_if_fail (context->state != STATE_ERROR, FALSE);
1763 if (context->partial_chunk != NULL)
1765 g_string_free (context->partial_chunk, TRUE);
1766 context->partial_chunk = NULL;
1769 if (context->document_empty)
1771 set_error_literal (context, error, G_MARKUP_ERROR_EMPTY,
1772 _("Document was empty or contained only whitespace"));
1773 return FALSE;
1776 context->parsing = TRUE;
1778 switch (context->state)
1780 case STATE_START:
1781 /* Nothing to do */
1782 break;
1784 case STATE_AFTER_OPEN_ANGLE:
1785 set_error_literal (context, error, G_MARKUP_ERROR_PARSE,
1786 _("Document ended unexpectedly just after an open angle bracket “<”"));
1787 break;
1789 case STATE_AFTER_CLOSE_ANGLE:
1790 if (context->tag_stack != NULL)
1792 /* Error message the same as for INSIDE_TEXT */
1793 set_error (context, error, G_MARKUP_ERROR_PARSE,
1794 _("Document ended unexpectedly with elements still open — "
1795 "“%s” was the last element opened"),
1796 current_element (context));
1798 break;
1800 case STATE_AFTER_ELISION_SLASH:
1801 set_error (context, error, G_MARKUP_ERROR_PARSE,
1802 _("Document ended unexpectedly, expected to see a close angle "
1803 "bracket ending the tag <%s/>"), current_element (context));
1804 break;
1806 case STATE_INSIDE_OPEN_TAG_NAME:
1807 set_error_literal (context, error, G_MARKUP_ERROR_PARSE,
1808 _("Document ended unexpectedly inside an element name"));
1809 break;
1811 case STATE_INSIDE_ATTRIBUTE_NAME:
1812 case STATE_AFTER_ATTRIBUTE_NAME:
1813 set_error_literal (context, error, G_MARKUP_ERROR_PARSE,
1814 _("Document ended unexpectedly inside an attribute name"));
1815 break;
1817 case STATE_BETWEEN_ATTRIBUTES:
1818 set_error_literal (context, error, G_MARKUP_ERROR_PARSE,
1819 _("Document ended unexpectedly inside an element-opening "
1820 "tag."));
1821 break;
1823 case STATE_AFTER_ATTRIBUTE_EQUALS_SIGN:
1824 set_error_literal (context, error, G_MARKUP_ERROR_PARSE,
1825 _("Document ended unexpectedly after the equals sign "
1826 "following an attribute name; no attribute value"));
1827 break;
1829 case STATE_INSIDE_ATTRIBUTE_VALUE_SQ:
1830 case STATE_INSIDE_ATTRIBUTE_VALUE_DQ:
1831 set_error_literal (context, error, G_MARKUP_ERROR_PARSE,
1832 _("Document ended unexpectedly while inside an attribute "
1833 "value"));
1834 break;
1836 case STATE_INSIDE_TEXT:
1837 g_assert (context->tag_stack != NULL);
1838 set_error (context, error, G_MARKUP_ERROR_PARSE,
1839 _("Document ended unexpectedly with elements still open — "
1840 "“%s” was the last element opened"),
1841 current_element (context));
1842 break;
1844 case STATE_AFTER_CLOSE_TAG_SLASH:
1845 case STATE_INSIDE_CLOSE_TAG_NAME:
1846 case STATE_AFTER_CLOSE_TAG_NAME:
1847 if (context->tag_stack != NULL)
1848 set_error (context, error, G_MARKUP_ERROR_PARSE,
1849 _("Document ended unexpectedly inside the close tag for "
1850 "element “%s”"), current_element (context));
1851 else
1852 set_error (context, error, G_MARKUP_ERROR_PARSE,
1853 _("Document ended unexpectedly inside the close tag for an "
1854 "unopened element"));
1855 break;
1857 case STATE_INSIDE_PASSTHROUGH:
1858 set_error_literal (context, error, G_MARKUP_ERROR_PARSE,
1859 _("Document ended unexpectedly inside a comment or "
1860 "processing instruction"));
1861 break;
1863 case STATE_ERROR:
1864 default:
1865 g_assert_not_reached ();
1866 break;
1869 context->parsing = FALSE;
1871 return context->state != STATE_ERROR;
1875 * g_markup_parse_context_get_element:
1876 * @context: a #GMarkupParseContext
1878 * Retrieves the name of the currently open element.
1880 * If called from the start_element or end_element handlers this will
1881 * give the element_name as passed to those functions. For the parent
1882 * elements, see g_markup_parse_context_get_element_stack().
1884 * Returns: the name of the currently open element, or %NULL
1886 * Since: 2.2
1888 const gchar *
1889 g_markup_parse_context_get_element (GMarkupParseContext *context)
1891 g_return_val_if_fail (context != NULL, NULL);
1893 if (context->tag_stack == NULL)
1894 return NULL;
1895 else
1896 return current_element (context);
1900 * g_markup_parse_context_get_element_stack:
1901 * @context: a #GMarkupParseContext
1903 * Retrieves the element stack from the internal state of the parser.
1905 * The returned #GSList is a list of strings where the first item is
1906 * the currently open tag (as would be returned by
1907 * g_markup_parse_context_get_element()) and the next item is its
1908 * immediate parent.
1910 * This function is intended to be used in the start_element and
1911 * end_element handlers where g_markup_parse_context_get_element()
1912 * would merely return the name of the element that is being
1913 * processed.
1915 * Returns: the element stack, which must not be modified
1917 * Since: 2.16
1919 const GSList *
1920 g_markup_parse_context_get_element_stack (GMarkupParseContext *context)
1922 g_return_val_if_fail (context != NULL, NULL);
1923 return context->tag_stack;
1927 * g_markup_parse_context_get_position:
1928 * @context: a #GMarkupParseContext
1929 * @line_number: (nullable): return location for a line number, or %NULL
1930 * @char_number: (nullable): return location for a char-on-line number, or %NULL
1932 * Retrieves the current line number and the number of the character on
1933 * that line. Intended for use in error messages; there are no strict
1934 * semantics for what constitutes the "current" line number other than
1935 * "the best number we could come up with for error messages."
1937 void
1938 g_markup_parse_context_get_position (GMarkupParseContext *context,
1939 gint *line_number,
1940 gint *char_number)
1942 g_return_if_fail (context != NULL);
1944 if (line_number)
1945 *line_number = context->line_number;
1947 if (char_number)
1948 *char_number = context->char_number;
1952 * g_markup_parse_context_get_user_data:
1953 * @context: a #GMarkupParseContext
1955 * Returns the user_data associated with @context.
1957 * This will either be the user_data that was provided to
1958 * g_markup_parse_context_new() or to the most recent call
1959 * of g_markup_parse_context_push().
1961 * Returns: the provided user_data. The returned data belongs to
1962 * the markup context and will be freed when
1963 * g_markup_parse_context_free() is called.
1965 * Since: 2.18
1967 gpointer
1968 g_markup_parse_context_get_user_data (GMarkupParseContext *context)
1970 return context->user_data;
1974 * g_markup_parse_context_push:
1975 * @context: a #GMarkupParseContext
1976 * @parser: a #GMarkupParser
1977 * @user_data: user data to pass to #GMarkupParser functions
1979 * Temporarily redirects markup data to a sub-parser.
1981 * This function may only be called from the start_element handler of
1982 * a #GMarkupParser. It must be matched with a corresponding call to
1983 * g_markup_parse_context_pop() in the matching end_element handler
1984 * (except in the case that the parser aborts due to an error).
1986 * All tags, text and other data between the matching tags is
1987 * redirected to the subparser given by @parser. @user_data is used
1988 * as the user_data for that parser. @user_data is also passed to the
1989 * error callback in the event that an error occurs. This includes
1990 * errors that occur in subparsers of the subparser.
1992 * The end tag matching the start tag for which this call was made is
1993 * handled by the previous parser (which is given its own user_data)
1994 * which is why g_markup_parse_context_pop() is provided to allow "one
1995 * last access" to the @user_data provided to this function. In the
1996 * case of error, the @user_data provided here is passed directly to
1997 * the error callback of the subparser and g_markup_parse_context_pop()
1998 * should not be called. In either case, if @user_data was allocated
1999 * then it ought to be freed from both of these locations.
2001 * This function is not intended to be directly called by users
2002 * interested in invoking subparsers. Instead, it is intended to be
2003 * used by the subparsers themselves to implement a higher-level
2004 * interface.
2006 * As an example, see the following implementation of a simple
2007 * parser that counts the number of tags encountered.
2009 * |[<!-- language="C" -->
2010 * typedef struct
2012 * gint tag_count;
2013 * } CounterData;
2015 * static void
2016 * counter_start_element (GMarkupParseContext *context,
2017 * const gchar *element_name,
2018 * const gchar **attribute_names,
2019 * const gchar **attribute_values,
2020 * gpointer user_data,
2021 * GError **error)
2023 * CounterData *data = user_data;
2025 * data->tag_count++;
2028 * static void
2029 * counter_error (GMarkupParseContext *context,
2030 * GError *error,
2031 * gpointer user_data)
2033 * CounterData *data = user_data;
2035 * g_slice_free (CounterData, data);
2038 * static GMarkupParser counter_subparser =
2040 * counter_start_element,
2041 * NULL,
2042 * NULL,
2043 * NULL,
2044 * counter_error
2045 * };
2046 * ]|
2048 * In order to allow this parser to be easily used as a subparser, the
2049 * following interface is provided:
2051 * |[<!-- language="C" -->
2052 * void
2053 * start_counting (GMarkupParseContext *context)
2055 * CounterData *data = g_slice_new (CounterData);
2057 * data->tag_count = 0;
2058 * g_markup_parse_context_push (context, &counter_subparser, data);
2061 * gint
2062 * end_counting (GMarkupParseContext *context)
2064 * CounterData *data = g_markup_parse_context_pop (context);
2065 * int result;
2067 * result = data->tag_count;
2068 * g_slice_free (CounterData, data);
2070 * return result;
2072 * ]|
2074 * The subparser would then be used as follows:
2076 * |[<!-- language="C" -->
2077 * static void start_element (context, element_name, ...)
2079 * if (strcmp (element_name, "count-these") == 0)
2080 * start_counting (context);
2082 * // else, handle other tags...
2085 * static void end_element (context, element_name, ...)
2087 * if (strcmp (element_name, "count-these") == 0)
2088 * g_print ("Counted %d tags\n", end_counting (context));
2090 * // else, handle other tags...
2092 * ]|
2094 * Since: 2.18
2096 void
2097 g_markup_parse_context_push (GMarkupParseContext *context,
2098 const GMarkupParser *parser,
2099 gpointer user_data)
2101 GMarkupRecursionTracker *tracker;
2103 tracker = g_slice_new (GMarkupRecursionTracker);
2104 tracker->prev_element = context->subparser_element;
2105 tracker->prev_parser = context->parser;
2106 tracker->prev_user_data = context->user_data;
2108 context->subparser_element = current_element (context);
2109 context->parser = parser;
2110 context->user_data = user_data;
2112 context->subparser_stack = g_slist_prepend (context->subparser_stack,
2113 tracker);
2117 * g_markup_parse_context_pop:
2118 * @context: a #GMarkupParseContext
2120 * Completes the process of a temporary sub-parser redirection.
2122 * This function exists to collect the user_data allocated by a
2123 * matching call to g_markup_parse_context_push(). It must be called
2124 * in the end_element handler corresponding to the start_element
2125 * handler during which g_markup_parse_context_push() was called.
2126 * You must not call this function from the error callback -- the
2127 * @user_data is provided directly to the callback in that case.
2129 * This function is not intended to be directly called by users
2130 * interested in invoking subparsers. Instead, it is intended to
2131 * be used by the subparsers themselves to implement a higher-level
2132 * interface.
2134 * Returns: the user data passed to g_markup_parse_context_push()
2136 * Since: 2.18
2138 gpointer
2139 g_markup_parse_context_pop (GMarkupParseContext *context)
2141 gpointer user_data;
2143 if (!context->awaiting_pop)
2144 possibly_finish_subparser (context);
2146 g_assert (context->awaiting_pop);
2148 context->awaiting_pop = FALSE;
2150 /* valgrind friendliness */
2151 user_data = context->held_user_data;
2152 context->held_user_data = NULL;
2154 return user_data;
2157 static void
2158 append_escaped_text (GString *str,
2159 const gchar *text,
2160 gssize length)
2162 const gchar *p;
2163 const gchar *end;
2164 gunichar c;
2166 p = text;
2167 end = text + length;
2169 while (p < end)
2171 const gchar *next;
2172 next = g_utf8_next_char (p);
2174 switch (*p)
2176 case '&':
2177 g_string_append (str, "&amp;");
2178 break;
2180 case '<':
2181 g_string_append (str, "&lt;");
2182 break;
2184 case '>':
2185 g_string_append (str, "&gt;");
2186 break;
2188 case '\'':
2189 g_string_append (str, "&apos;");
2190 break;
2192 case '"':
2193 g_string_append (str, "&quot;");
2194 break;
2196 default:
2197 c = g_utf8_get_char (p);
2198 if ((0x1 <= c && c <= 0x8) ||
2199 (0xb <= c && c <= 0xc) ||
2200 (0xe <= c && c <= 0x1f) ||
2201 (0x7f <= c && c <= 0x84) ||
2202 (0x86 <= c && c <= 0x9f))
2203 g_string_append_printf (str, "&#x%x;", c);
2204 else
2205 g_string_append_len (str, p, next - p);
2206 break;
2209 p = next;
2214 * g_markup_escape_text:
2215 * @text: some valid UTF-8 text
2216 * @length: length of @text in bytes, or -1 if the text is nul-terminated
2218 * Escapes text so that the markup parser will parse it verbatim.
2219 * Less than, greater than, ampersand, etc. are replaced with the
2220 * corresponding entities. This function would typically be used
2221 * when writing out a file to be parsed with the markup parser.
2223 * Note that this function doesn't protect whitespace and line endings
2224 * from being processed according to the XML rules for normalization
2225 * of line endings and attribute values.
2227 * Note also that this function will produce character references in
2228 * the range of &#x1; ... &#x1f; for all control sequences
2229 * except for tabstop, newline and carriage return. The character
2230 * references in this range are not valid XML 1.0, but they are
2231 * valid XML 1.1 and will be accepted by the GMarkup parser.
2233 * Returns: a newly allocated string with the escaped text
2235 gchar*
2236 g_markup_escape_text (const gchar *text,
2237 gssize length)
2239 GString *str;
2241 g_return_val_if_fail (text != NULL, NULL);
2243 if (length < 0)
2244 length = strlen (text);
2246 /* prealloc at least as long as original text */
2247 str = g_string_sized_new (length);
2248 append_escaped_text (str, text, length);
2250 return g_string_free (str, FALSE);
2254 * find_conversion:
2255 * @format: a printf-style format string
2256 * @after: location to store a pointer to the character after
2257 * the returned conversion. On a %NULL return, returns the
2258 * pointer to the trailing NUL in the string
2260 * Find the next conversion in a printf-style format string.
2261 * Partially based on code from printf-parser.c,
2262 * Copyright (C) 1999-2000, 2002-2003 Free Software Foundation, Inc.
2264 * Returns: pointer to the next conversion in @format,
2265 * or %NULL, if none.
2267 static const char *
2268 find_conversion (const char *format,
2269 const char **after)
2271 const char *start = format;
2272 const char *cp;
2274 while (*start != '\0' && *start != '%')
2275 start++;
2277 if (*start == '\0')
2279 *after = start;
2280 return NULL;
2283 cp = start + 1;
2285 if (*cp == '\0')
2287 *after = cp;
2288 return NULL;
2291 /* Test for positional argument. */
2292 if (*cp >= '0' && *cp <= '9')
2294 const char *np;
2296 for (np = cp; *np >= '0' && *np <= '9'; np++)
2298 if (*np == '$')
2299 cp = np + 1;
2302 /* Skip the flags. */
2303 for (;;)
2305 if (*cp == '\'' ||
2306 *cp == '-' ||
2307 *cp == '+' ||
2308 *cp == ' ' ||
2309 *cp == '#' ||
2310 *cp == '0')
2311 cp++;
2312 else
2313 break;
2316 /* Skip the field width. */
2317 if (*cp == '*')
2319 cp++;
2321 /* Test for positional argument. */
2322 if (*cp >= '0' && *cp <= '9')
2324 const char *np;
2326 for (np = cp; *np >= '0' && *np <= '9'; np++)
2328 if (*np == '$')
2329 cp = np + 1;
2332 else
2334 for (; *cp >= '0' && *cp <= '9'; cp++)
2338 /* Skip the precision. */
2339 if (*cp == '.')
2341 cp++;
2342 if (*cp == '*')
2344 /* Test for positional argument. */
2345 if (*cp >= '0' && *cp <= '9')
2347 const char *np;
2349 for (np = cp; *np >= '0' && *np <= '9'; np++)
2351 if (*np == '$')
2352 cp = np + 1;
2355 else
2357 for (; *cp >= '0' && *cp <= '9'; cp++)
2362 /* Skip argument type/size specifiers. */
2363 while (*cp == 'h' ||
2364 *cp == 'L' ||
2365 *cp == 'l' ||
2366 *cp == 'j' ||
2367 *cp == 'z' ||
2368 *cp == 'Z' ||
2369 *cp == 't')
2370 cp++;
2372 /* Skip the conversion character. */
2373 cp++;
2375 *after = cp;
2376 return start;
2380 * g_markup_vprintf_escaped:
2381 * @format: printf() style format string
2382 * @args: variable argument list, similar to vprintf()
2384 * Formats the data in @args according to @format, escaping
2385 * all string and character arguments in the fashion
2386 * of g_markup_escape_text(). See g_markup_printf_escaped().
2388 * Returns: newly allocated result from formatting
2389 * operation. Free with g_free().
2391 * Since: 2.4
2393 #pragma GCC diagnostic push
2394 #pragma GCC diagnostic ignored "-Wformat-nonliteral"
2396 gchar *
2397 g_markup_vprintf_escaped (const gchar *format,
2398 va_list args)
2400 GString *format1;
2401 GString *format2;
2402 GString *result = NULL;
2403 gchar *output1 = NULL;
2404 gchar *output2 = NULL;
2405 const char *p, *op1, *op2;
2406 va_list args2;
2408 /* The technique here, is that we make two format strings that
2409 * have the identical conversions in the identical order to the
2410 * original strings, but differ in the text in-between. We
2411 * then use the normal g_strdup_vprintf() to format the arguments
2412 * with the two new format strings. By comparing the results,
2413 * we can figure out what segments of the output come from
2414 * the original format string, and what from the arguments,
2415 * and thus know what portions of the string to escape.
2417 * For instance, for:
2419 * g_markup_printf_escaped ("%s ate %d apples", "Susan & Fred", 5);
2421 * We form the two format strings "%sX%dX" and %sY%sY". The results
2422 * of formatting with those two strings are
2424 * "%sX%dX" => "Susan & FredX5X"
2425 * "%sY%dY" => "Susan & FredY5Y"
2427 * To find the span of the first argument, we find the first position
2428 * where the two arguments differ, which tells us that the first
2429 * argument formatted to "Susan & Fred". We then escape that
2430 * to "Susan & Fred" and join up with the intermediate portions
2431 * of the format string and the second argument to get
2432 * "Susan & Fred ate 5 apples".
2435 /* Create the two modified format strings
2437 format1 = g_string_new (NULL);
2438 format2 = g_string_new (NULL);
2439 p = format;
2440 while (TRUE)
2442 const char *after;
2443 const char *conv = find_conversion (p, &after);
2444 if (!conv)
2445 break;
2447 g_string_append_len (format1, conv, after - conv);
2448 g_string_append_c (format1, 'X');
2449 g_string_append_len (format2, conv, after - conv);
2450 g_string_append_c (format2, 'Y');
2452 p = after;
2455 /* Use them to format the arguments
2457 G_VA_COPY (args2, args);
2459 output1 = g_strdup_vprintf (format1->str, args);
2461 if (!output1)
2463 va_end (args2);
2464 goto cleanup;
2467 output2 = g_strdup_vprintf (format2->str, args2);
2468 va_end (args2);
2469 if (!output2)
2470 goto cleanup;
2471 result = g_string_new (NULL);
2473 /* Iterate through the original format string again,
2474 * copying the non-conversion portions and the escaped
2475 * converted arguments to the output string.
2477 op1 = output1;
2478 op2 = output2;
2479 p = format;
2480 while (TRUE)
2482 const char *after;
2483 const char *output_start;
2484 const char *conv = find_conversion (p, &after);
2485 char *escaped;
2487 if (!conv) /* The end, after points to the trailing \0 */
2489 g_string_append_len (result, p, after - p);
2490 break;
2493 g_string_append_len (result, p, conv - p);
2494 output_start = op1;
2495 while (*op1 == *op2)
2497 op1++;
2498 op2++;
2501 escaped = g_markup_escape_text (output_start, op1 - output_start);
2502 g_string_append (result, escaped);
2503 g_free (escaped);
2505 p = after;
2506 op1++;
2507 op2++;
2510 cleanup:
2511 g_string_free (format1, TRUE);
2512 g_string_free (format2, TRUE);
2513 g_free (output1);
2514 g_free (output2);
2516 if (result)
2517 return g_string_free (result, FALSE);
2518 else
2519 return NULL;
2522 #pragma GCC diagnostic pop
2525 * g_markup_printf_escaped:
2526 * @format: printf() style format string
2527 * @...: the arguments to insert in the format string
2529 * Formats arguments according to @format, escaping
2530 * all string and character arguments in the fashion
2531 * of g_markup_escape_text(). This is useful when you
2532 * want to insert literal strings into XML-style markup
2533 * output, without having to worry that the strings
2534 * might themselves contain markup.
2536 * |[<!-- language="C" -->
2537 * const char *store = "Fortnum & Mason";
2538 * const char *item = "Tea";
2539 * char *output;
2541 * output = g_markup_printf_escaped ("<purchase>"
2542 * "<store>%s</store>"
2543 * "<item>%s</item>"
2544 * "</purchase>",
2545 * store, item);
2546 * ]|
2548 * Returns: newly allocated result from formatting
2549 * operation. Free with g_free().
2551 * Since: 2.4
2553 gchar *
2554 g_markup_printf_escaped (const gchar *format, ...)
2556 char *result;
2557 va_list args;
2559 va_start (args, format);
2560 result = g_markup_vprintf_escaped (format, args);
2561 va_end (args);
2563 return result;
2566 static gboolean
2567 g_markup_parse_boolean (const char *string,
2568 gboolean *value)
2570 char const * const falses[] = { "false", "f", "no", "n", "0" };
2571 char const * const trues[] = { "true", "t", "yes", "y", "1" };
2572 int i;
2574 for (i = 0; i < G_N_ELEMENTS (falses); i++)
2576 if (g_ascii_strcasecmp (string, falses[i]) == 0)
2578 if (value != NULL)
2579 *value = FALSE;
2581 return TRUE;
2585 for (i = 0; i < G_N_ELEMENTS (trues); i++)
2587 if (g_ascii_strcasecmp (string, trues[i]) == 0)
2589 if (value != NULL)
2590 *value = TRUE;
2592 return TRUE;
2596 return FALSE;
2600 * GMarkupCollectType:
2601 * @G_MARKUP_COLLECT_INVALID: used to terminate the list of attributes
2602 * to collect
2603 * @G_MARKUP_COLLECT_STRING: collect the string pointer directly from
2604 * the attribute_values[] array. Expects a parameter of type (const
2605 * char **). If %G_MARKUP_COLLECT_OPTIONAL is specified and the
2606 * attribute isn't present then the pointer will be set to %NULL
2607 * @G_MARKUP_COLLECT_STRDUP: as with %G_MARKUP_COLLECT_STRING, but
2608 * expects a parameter of type (char **) and g_strdup()s the
2609 * returned pointer. The pointer must be freed with g_free()
2610 * @G_MARKUP_COLLECT_BOOLEAN: expects a parameter of type (gboolean *)
2611 * and parses the attribute value as a boolean. Sets %FALSE if the
2612 * attribute isn't present. Valid boolean values consist of
2613 * (case-insensitive) "false", "f", "no", "n", "0" and "true", "t",
2614 * "yes", "y", "1"
2615 * @G_MARKUP_COLLECT_TRISTATE: as with %G_MARKUP_COLLECT_BOOLEAN, but
2616 * in the case of a missing attribute a value is set that compares
2617 * equal to neither %FALSE nor %TRUE G_MARKUP_COLLECT_OPTIONAL is
2618 * implied
2619 * @G_MARKUP_COLLECT_OPTIONAL: can be bitwise ORed with the other fields.
2620 * If present, allows the attribute not to appear. A default value
2621 * is set depending on what value type is used
2623 * A mixed enumerated type and flags field. You must specify one type
2624 * (string, strdup, boolean, tristate). Additionally, you may optionally
2625 * bitwise OR the type with the flag %G_MARKUP_COLLECT_OPTIONAL.
2627 * It is likely that this enum will be extended in the future to
2628 * support other types.
2632 * g_markup_collect_attributes:
2633 * @element_name: the current tag name
2634 * @attribute_names: the attribute names
2635 * @attribute_values: the attribute values
2636 * @error: a pointer to a #GError or %NULL
2637 * @first_type: the #GMarkupCollectType of the first attribute
2638 * @first_attr: the name of the first attribute
2639 * @...: a pointer to the storage location of the first attribute
2640 * (or %NULL), followed by more types names and pointers, ending
2641 * with %G_MARKUP_COLLECT_INVALID
2643 * Collects the attributes of the element from the data passed to the
2644 * #GMarkupParser start_element function, dealing with common error
2645 * conditions and supporting boolean values.
2647 * This utility function is not required to write a parser but can save
2648 * a lot of typing.
2650 * The @element_name, @attribute_names, @attribute_values and @error
2651 * parameters passed to the start_element callback should be passed
2652 * unmodified to this function.
2654 * Following these arguments is a list of "supported" attributes to collect.
2655 * It is an error to specify multiple attributes with the same name. If any
2656 * attribute not in the list appears in the @attribute_names array then an
2657 * unknown attribute error will result.
2659 * The #GMarkupCollectType field allows specifying the type of collection
2660 * to perform and if a given attribute must appear or is optional.
2662 * The attribute name is simply the name of the attribute to collect.
2664 * The pointer should be of the appropriate type (see the descriptions
2665 * under #GMarkupCollectType) and may be %NULL in case a particular
2666 * attribute is to be allowed but ignored.
2668 * This function deals with issuing errors for missing attributes
2669 * (of type %G_MARKUP_ERROR_MISSING_ATTRIBUTE), unknown attributes
2670 * (of type %G_MARKUP_ERROR_UNKNOWN_ATTRIBUTE) and duplicate
2671 * attributes (of type %G_MARKUP_ERROR_INVALID_CONTENT) as well
2672 * as parse errors for boolean-valued attributes (again of type
2673 * %G_MARKUP_ERROR_INVALID_CONTENT). In all of these cases %FALSE
2674 * will be returned and @error will be set as appropriate.
2676 * Returns: %TRUE if successful
2678 * Since: 2.16
2680 gboolean
2681 g_markup_collect_attributes (const gchar *element_name,
2682 const gchar **attribute_names,
2683 const gchar **attribute_values,
2684 GError **error,
2685 GMarkupCollectType first_type,
2686 const gchar *first_attr,
2687 ...)
2689 GMarkupCollectType type;
2690 const gchar *attr;
2691 guint64 collected;
2692 int written;
2693 va_list ap;
2694 int i;
2696 type = first_type;
2697 attr = first_attr;
2698 collected = 0;
2699 written = 0;
2701 va_start (ap, first_attr);
2702 while (type != G_MARKUP_COLLECT_INVALID)
2704 gboolean mandatory;
2705 const gchar *value;
2707 mandatory = !(type & G_MARKUP_COLLECT_OPTIONAL);
2708 type &= (G_MARKUP_COLLECT_OPTIONAL - 1);
2710 /* tristate records a value != TRUE and != FALSE
2711 * for the case where the attribute is missing
2713 if (type == G_MARKUP_COLLECT_TRISTATE)
2714 mandatory = FALSE;
2716 for (i = 0; attribute_names[i]; i++)
2717 if (i >= 40 || !(collected & (G_GUINT64_CONSTANT(1) << i)))
2718 if (!strcmp (attribute_names[i], attr))
2719 break;
2721 /* ISO C99 only promises that the user can pass up to 127 arguments.
2722 * Subtracting the first 4 arguments plus the final NULL and dividing
2723 * by 3 arguments per collected attribute, we are left with a maximum
2724 * number of supported attributes of (127 - 5) / 3 = 40.
2726 * In reality, nobody is ever going to call us with anywhere close to
2727 * 40 attributes to collect, so it is safe to assume that if i > 40
2728 * then the user has given some invalid or repeated arguments. These
2729 * problems will be caught and reported at the end of the function.
2731 * We know at this point that we have an error, but we don't know
2732 * what error it is, so just continue...
2734 if (i < 40)
2735 collected |= (G_GUINT64_CONSTANT(1) << i);
2737 value = attribute_values[i];
2739 if (value == NULL && mandatory)
2741 g_set_error (error, G_MARKUP_ERROR,
2742 G_MARKUP_ERROR_MISSING_ATTRIBUTE,
2743 "element '%s' requires attribute '%s'",
2744 element_name, attr);
2746 va_end (ap);
2747 goto failure;
2750 switch (type)
2752 case G_MARKUP_COLLECT_STRING:
2754 const char **str_ptr;
2756 str_ptr = va_arg (ap, const char **);
2758 if (str_ptr != NULL)
2759 *str_ptr = value;
2761 break;
2763 case G_MARKUP_COLLECT_STRDUP:
2765 char **str_ptr;
2767 str_ptr = va_arg (ap, char **);
2769 if (str_ptr != NULL)
2770 *str_ptr = g_strdup (value);
2772 break;
2774 case G_MARKUP_COLLECT_BOOLEAN:
2775 case G_MARKUP_COLLECT_TRISTATE:
2776 if (value == NULL)
2778 gboolean *bool_ptr;
2780 bool_ptr = va_arg (ap, gboolean *);
2782 if (bool_ptr != NULL)
2784 if (type == G_MARKUP_COLLECT_TRISTATE)
2785 /* constructivists rejoice!
2786 * neither false nor true...
2788 *bool_ptr = -1;
2790 else /* G_MARKUP_COLLECT_BOOLEAN */
2791 *bool_ptr = FALSE;
2794 else
2796 if (!g_markup_parse_boolean (value, va_arg (ap, gboolean *)))
2798 g_set_error (error, G_MARKUP_ERROR,
2799 G_MARKUP_ERROR_INVALID_CONTENT,
2800 "element '%s', attribute '%s', value '%s' "
2801 "cannot be parsed as a boolean value",
2802 element_name, attr, value);
2804 va_end (ap);
2805 goto failure;
2809 break;
2811 default:
2812 g_assert_not_reached ();
2815 type = va_arg (ap, GMarkupCollectType);
2816 attr = va_arg (ap, const char *);
2817 written++;
2819 va_end (ap);
2821 /* ensure we collected all the arguments */
2822 for (i = 0; attribute_names[i]; i++)
2823 if ((collected & (G_GUINT64_CONSTANT(1) << i)) == 0)
2825 /* attribute not collected: could be caused by two things.
2827 * 1) it doesn't exist in our list of attributes
2828 * 2) it existed but was matched by a duplicate attribute earlier
2830 * find out.
2832 int j;
2834 for (j = 0; j < i; j++)
2835 if (strcmp (attribute_names[i], attribute_names[j]) == 0)
2836 /* duplicate! */
2837 break;
2839 /* j is now the first occurrence of attribute_names[i] */
2840 if (i == j)
2841 g_set_error (error, G_MARKUP_ERROR,
2842 G_MARKUP_ERROR_UNKNOWN_ATTRIBUTE,
2843 "attribute '%s' invalid for element '%s'",
2844 attribute_names[i], element_name);
2845 else
2846 g_set_error (error, G_MARKUP_ERROR,
2847 G_MARKUP_ERROR_INVALID_CONTENT,
2848 "attribute '%s' given multiple times for element '%s'",
2849 attribute_names[i], element_name);
2851 goto failure;
2854 return TRUE;
2856 failure:
2857 /* replay the above to free allocations */
2858 type = first_type;
2859 attr = first_attr;
2861 va_start (ap, first_attr);
2862 while (type != G_MARKUP_COLLECT_INVALID)
2864 gpointer ptr;
2866 ptr = va_arg (ap, gpointer);
2868 if (ptr != NULL)
2870 switch (type & (G_MARKUP_COLLECT_OPTIONAL - 1))
2872 case G_MARKUP_COLLECT_STRDUP:
2873 if (written)
2874 g_free (*(char **) ptr);
2876 case G_MARKUP_COLLECT_STRING:
2877 *(char **) ptr = NULL;
2878 break;
2880 case G_MARKUP_COLLECT_BOOLEAN:
2881 *(gboolean *) ptr = FALSE;
2882 break;
2884 case G_MARKUP_COLLECT_TRISTATE:
2885 *(gboolean *) ptr = -1;
2886 break;
2890 type = va_arg (ap, GMarkupCollectType);
2891 attr = va_arg (ap, const char *);
2893 va_end (ap);
2895 return FALSE;