Simplify glib/glib/tests setup
[glib.git] / glib / gmarkup.c
blob552773fd815e530f33e53974363bc60b94626f43
1 /* gmarkup.c - Simple XML-like parser
3 * Copyright 2000, 2003 Red Hat, Inc.
4 * Copyright 2007, 2008 Ryan Lortie <desrt@desrt.ca>
6 * GLib is free software; you can redistribute it and/or modify it
7 * under the terms of the GNU Lesser General Public License as
8 * published by the Free Software Foundation; either version 2 of the
9 * License, or (at your option) any later version.
11 * GLib 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
17 * License along with GLib; see the file COPYING.LIB. If not,
18 * write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
19 * Boston, MA 02111-1307, USA.
22 #include "config.h"
24 #include <stdarg.h>
25 #include <string.h>
26 #include <stdio.h>
27 #include <stdlib.h>
28 #include <errno.h>
30 #include "gmarkup.h"
32 #include "gatomic.h"
33 #include "gslice.h"
34 #include "galloca.h"
35 #include "gstrfuncs.h"
36 #include "gstring.h"
37 #include "gtestutils.h"
38 #include "glibintl.h"
39 #include "gthread.h"
41 /**
42 * SECTION:markup
43 * @Title: Simple XML Subset Parser
44 * @Short_description: parses a subset of XML
45 * @See_also: <ulink url="http://www.w3.org/TR/REC-xml/">XML
46 * Specification</ulink>
48 * The "GMarkup" parser is intended to parse a simple markup format
49 * that's a subset of XML. This is a small, efficient, easy-to-use
50 * parser. It should not be used if you expect to interoperate with
51 * other applications generating full-scale XML. However, it's very
52 * useful for application data files, config files, etc. where you
53 * know your application will be the only one writing the file.
54 * Full-scale XML parsers should be able to parse the subset used by
55 * GMarkup, so you can easily migrate to full-scale XML at a later
56 * time if the need arises.
58 * GMarkup is not guaranteed to signal an error on all invalid XML;
59 * the parser may accept documents that an XML parser would not.
60 * However, XML documents which are not well-formed<footnote
61 * id="wellformed">Being wellformed is a weaker condition than being
62 * valid. See the <ulink url="http://www.w3.org/TR/REC-xml/">XML
63 * specification</ulink> for definitions of these terms.</footnote>
64 * are not considered valid GMarkup documents.
66 * Simplifications to XML include:
67 * <itemizedlist>
68 * <listitem>Only UTF-8 encoding is allowed</listitem>
69 * <listitem>No user-defined entities</listitem>
70 * <listitem>Processing instructions, comments and the doctype declaration
71 * are "passed through" but are not interpreted in any way</listitem>
72 * <listitem>No DTD or validation.</listitem>
73 * </itemizedlist>
75 * The markup format does support:
76 * <itemizedlist>
77 * <listitem>Elements</listitem>
78 * <listitem>Attributes</listitem>
79 * <listitem>5 standard entities:
80 * <literal>&amp;amp; &amp;lt; &amp;gt; &amp;quot; &amp;apos;</literal>
81 * </listitem>
82 * <listitem>Character references</listitem>
83 * <listitem>Sections marked as CDATA</listitem>
84 * </itemizedlist>
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 * Return value: 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);
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 static gchar*
561 utf8_str (const gchar *utf8,
562 gchar *buf)
564 char_str (g_utf8_get_char (utf8), buf);
565 return buf;
568 G_GNUC_PRINTF(5, 6)
569 static void
570 set_unescape_error (GMarkupParseContext *context,
571 GError **error,
572 const gchar *remaining_text,
573 GMarkupError code,
574 const gchar *format,
575 ...)
577 GError *tmp_error;
578 gchar *s;
579 va_list args;
580 gint remaining_newlines;
581 const gchar *p;
583 remaining_newlines = 0;
584 p = remaining_text;
585 while (*p != '\0')
587 if (*p == '\n')
588 ++remaining_newlines;
589 ++p;
592 va_start (args, format);
593 s = g_strdup_vprintf (format, args);
594 va_end (args);
596 tmp_error = g_error_new (G_MARKUP_ERROR,
597 code,
598 _("Error on line %d: %s"),
599 context->line_number - remaining_newlines,
602 g_free (s);
604 mark_error (context, tmp_error);
606 g_propagate_error (error, tmp_error);
610 * re-write the GString in-place, unescaping anything that escaped.
611 * most XML does not contain entities, or escaping.
613 static gboolean
614 unescape_gstring_inplace (GMarkupParseContext *context,
615 GString *string,
616 gboolean *is_ascii,
617 GError **error)
619 char mask, *to;
620 int line_num = 1;
621 const char *from;
622 gboolean normalize_attribute;
624 *is_ascii = FALSE;
626 /* are we unescaping an attribute or not ? */
627 if (context->state == STATE_INSIDE_ATTRIBUTE_VALUE_SQ ||
628 context->state == STATE_INSIDE_ATTRIBUTE_VALUE_DQ)
629 normalize_attribute = TRUE;
630 else
631 normalize_attribute = FALSE;
634 * Meeks' theorum: unescaping can only shrink text.
635 * for &lt; etc. this is obvious, for &#xffff; more
636 * thought is required, but this is patently so.
638 mask = 0;
639 for (from = to = string->str; *from != '\0'; from++, to++)
641 *to = *from;
643 mask |= *to;
644 if (*to == '\n')
645 line_num++;
646 if (normalize_attribute && (*to == '\t' || *to == '\n'))
647 *to = ' ';
648 if (*to == '\r')
650 *to = normalize_attribute ? ' ' : '\n';
651 if (from[1] == '\n')
652 from++;
654 if (*from == '&')
656 from++;
657 if (*from == '#')
659 gboolean is_hex = FALSE;
660 gulong l;
661 gchar *end = NULL;
663 from++;
665 if (*from == 'x')
667 is_hex = TRUE;
668 from++;
671 /* digit is between start and p */
672 errno = 0;
673 if (is_hex)
674 l = strtoul (from, &end, 16);
675 else
676 l = strtoul (from, &end, 10);
678 if (end == from || errno != 0)
680 set_unescape_error (context, error,
681 from, G_MARKUP_ERROR_PARSE,
682 _("Failed to parse '%-.*s', which "
683 "should have been a digit "
684 "inside a character reference "
685 "(&#234; for example) - perhaps "
686 "the digit is too large"),
687 (int)(end - from), from);
688 return FALSE;
690 else if (*end != ';')
692 set_unescape_error (context, error,
693 from, G_MARKUP_ERROR_PARSE,
694 _("Character reference did not end with a "
695 "semicolon; "
696 "most likely you used an ampersand "
697 "character without intending to start "
698 "an entity - escape ampersand as &amp;"));
699 return FALSE;
701 else
703 /* characters XML 1.1 permits */
704 if ((0 < l && l <= 0xD7FF) ||
705 (0xE000 <= l && l <= 0xFFFD) ||
706 (0x10000 <= l && l <= 0x10FFFF))
708 gchar buf[8];
709 char_str (l, buf);
710 strcpy (to, buf);
711 to += strlen (buf) - 1;
712 from = end;
713 if (l >= 0x80) /* not ascii */
714 mask |= 0x80;
716 else
718 set_unescape_error (context, error,
719 from, G_MARKUP_ERROR_PARSE,
720 _("Character reference '%-.*s' does not "
721 "encode a permitted character"),
722 (int)(end - from), from);
723 return FALSE;
728 else if (strncmp (from, "lt;", 3) == 0)
730 *to = '<';
731 from += 2;
733 else if (strncmp (from, "gt;", 3) == 0)
735 *to = '>';
736 from += 2;
738 else if (strncmp (from, "amp;", 4) == 0)
740 *to = '&';
741 from += 3;
743 else if (strncmp (from, "quot;", 5) == 0)
745 *to = '"';
746 from += 4;
748 else if (strncmp (from, "apos;", 5) == 0)
750 *to = '\'';
751 from += 4;
753 else
755 if (*from == ';')
756 set_unescape_error (context, error,
757 from, G_MARKUP_ERROR_PARSE,
758 _("Empty entity '&;' seen; valid "
759 "entities are: &amp; &quot; &lt; &gt; &apos;"));
760 else
762 const char *end = strchr (from, ';');
763 if (end)
764 set_unescape_error (context, error,
765 from, G_MARKUP_ERROR_PARSE,
766 _("Entity name '%-.*s' is not known"),
767 (int)(end - from), from);
768 else
769 set_unescape_error (context, error,
770 from, G_MARKUP_ERROR_PARSE,
771 _("Entity did not end with a semicolon; "
772 "most likely you used an ampersand "
773 "character without intending to start "
774 "an entity - escape ampersand as &amp;"));
776 return FALSE;
781 g_assert (to - string->str <= string->len);
782 if (to - string->str != string->len)
783 g_string_truncate (string, to - string->str);
785 *is_ascii = !(mask & 0x80);
787 return TRUE;
790 static inline gboolean
791 advance_char (GMarkupParseContext *context)
793 context->iter++;
794 context->char_number++;
796 if (G_UNLIKELY (context->iter == context->current_text_end))
797 return FALSE;
799 else if (G_UNLIKELY (*context->iter == '\n'))
801 context->line_number++;
802 context->char_number = 1;
805 return TRUE;
808 static inline gboolean
809 xml_isspace (char c)
811 return c == ' ' || c == '\t' || c == '\n' || c == '\r';
814 static void
815 skip_spaces (GMarkupParseContext *context)
819 if (!xml_isspace (*context->iter))
820 return;
822 while (advance_char (context));
825 static void
826 advance_to_name_end (GMarkupParseContext *context)
830 if (IS_COMMON_NAME_END_CHAR (*(context->iter)))
831 return;
832 if (xml_isspace (*(context->iter)))
833 return;
835 while (advance_char (context));
838 static void
839 release_chunk (GMarkupParseContext *context, GString *str)
841 GSList *node;
842 if (!str)
843 return;
844 if (str->allocated_len > 256)
845 { /* large strings are unusual and worth freeing */
846 g_string_free (str, TRUE);
847 return;
849 string_blank (str);
850 node = get_list_node (context, str);
851 context->spare_chunks = g_slist_concat (node, context->spare_chunks);
854 static void
855 add_to_partial (GMarkupParseContext *context,
856 const gchar *text_start,
857 const gchar *text_end)
859 if (context->partial_chunk == NULL)
860 { /* allocate a new chunk to parse into */
862 if (context->spare_chunks != NULL)
864 GSList *node = context->spare_chunks;
865 context->spare_chunks = g_slist_remove_link (context->spare_chunks, node);
866 context->partial_chunk = node->data;
867 free_list_node (context, node);
869 else
870 context->partial_chunk = g_string_sized_new (MAX (28, text_end - text_start));
873 if (text_start != text_end)
874 g_string_insert_len (context->partial_chunk, -1,
875 text_start, text_end - text_start);
878 static inline void
879 truncate_partial (GMarkupParseContext *context)
881 if (context->partial_chunk != NULL)
882 string_blank (context->partial_chunk);
885 static inline const gchar*
886 current_element (GMarkupParseContext *context)
888 return context->tag_stack->data;
891 static void
892 pop_subparser_stack (GMarkupParseContext *context)
894 GMarkupRecursionTracker *tracker;
896 g_assert (context->subparser_stack);
898 tracker = context->subparser_stack->data;
900 context->awaiting_pop = TRUE;
901 context->held_user_data = context->user_data;
903 context->user_data = tracker->prev_user_data;
904 context->parser = tracker->prev_parser;
905 context->subparser_element = tracker->prev_element;
906 g_slice_free (GMarkupRecursionTracker, tracker);
908 context->subparser_stack = g_slist_delete_link (context->subparser_stack,
909 context->subparser_stack);
912 static void
913 push_partial_as_tag (GMarkupParseContext *context)
915 GString *str = context->partial_chunk;
916 /* sadly, this is exported by gmarkup_get_element_stack as-is */
917 context->tag_stack = g_slist_concat (get_list_node (context, str->str), context->tag_stack);
918 context->tag_stack_gstr = g_slist_concat (get_list_node (context, str), context->tag_stack_gstr);
919 context->partial_chunk = NULL;
922 static void
923 pop_tag (GMarkupParseContext *context)
925 GSList *nodea, *nodeb;
927 nodea = context->tag_stack;
928 nodeb = context->tag_stack_gstr;
929 release_chunk (context, nodeb->data);
930 context->tag_stack = g_slist_remove_link (context->tag_stack, nodea);
931 context->tag_stack_gstr = g_slist_remove_link (context->tag_stack_gstr, nodeb);
932 free_list_node (context, nodea);
933 free_list_node (context, nodeb);
936 static void
937 possibly_finish_subparser (GMarkupParseContext *context)
939 if (current_element (context) == context->subparser_element)
940 pop_subparser_stack (context);
943 static void
944 ensure_no_outstanding_subparser (GMarkupParseContext *context)
946 if (context->awaiting_pop)
947 g_critical ("During the first end_element call after invoking a "
948 "subparser you must pop the subparser stack and handle "
949 "the freeing of the subparser user_data. This can be "
950 "done by calling the end function of the subparser. "
951 "Very probably, your program just leaked memory.");
953 /* let valgrind watch the pointer disappear... */
954 context->held_user_data = NULL;
955 context->awaiting_pop = FALSE;
958 static const gchar*
959 current_attribute (GMarkupParseContext *context)
961 g_assert (context->cur_attr >= 0);
962 return context->attr_names[context->cur_attr]->str;
965 static void
966 add_attribute (GMarkupParseContext *context, GString *str)
968 if (context->cur_attr + 2 >= context->alloc_attrs)
970 context->alloc_attrs += 5; /* silly magic number */
971 context->attr_names = g_realloc (context->attr_names, sizeof(GString*)*context->alloc_attrs);
972 context->attr_values = g_realloc (context->attr_values, sizeof(GString*)*context->alloc_attrs);
974 context->cur_attr++;
975 context->attr_names[context->cur_attr] = str;
976 context->attr_values[context->cur_attr] = NULL;
977 context->attr_names[context->cur_attr+1] = NULL;
978 context->attr_values[context->cur_attr+1] = NULL;
981 static void
982 clear_attributes (GMarkupParseContext *context)
984 /* Go ahead and free the attributes. */
985 for (; context->cur_attr >= 0; context->cur_attr--)
987 int pos = context->cur_attr;
988 release_chunk (context, context->attr_names[pos]);
989 release_chunk (context, context->attr_values[pos]);
990 context->attr_names[pos] = context->attr_values[pos] = NULL;
992 g_assert (context->cur_attr == -1);
993 g_assert (context->attr_names == NULL ||
994 context->attr_names[0] == NULL);
995 g_assert (context->attr_values == NULL ||
996 context->attr_values[0] == NULL);
999 /* This has to be a separate function to ensure the alloca's
1000 * are unwound on exit - otherwise we grow & blow the stack
1001 * with large documents
1003 static inline void
1004 emit_start_element (GMarkupParseContext *context,
1005 GError **error)
1007 int i;
1008 const gchar *start_name;
1009 const gchar **attr_names;
1010 const gchar **attr_values;
1011 GError *tmp_error;
1013 attr_names = g_newa (const gchar *, context->cur_attr + 2);
1014 attr_values = g_newa (const gchar *, context->cur_attr + 2);
1015 for (i = 0; i < context->cur_attr + 1; i++)
1017 attr_names[i] = context->attr_names[i]->str;
1018 attr_values[i] = context->attr_values[i]->str;
1020 attr_names[i] = NULL;
1021 attr_values[i] = NULL;
1023 /* Call user callback for element start */
1024 tmp_error = NULL;
1025 start_name = current_element (context);
1027 if (context->parser->start_element &&
1028 name_validate (context, start_name, error))
1029 (* context->parser->start_element) (context,
1030 start_name,
1031 (const gchar **)attr_names,
1032 (const gchar **)attr_values,
1033 context->user_data,
1034 &tmp_error);
1035 clear_attributes (context);
1037 if (tmp_error != NULL)
1038 propagate_error (context, error, tmp_error);
1042 * g_markup_parse_context_parse:
1043 * @context: a #GMarkupParseContext
1044 * @text: chunk of text to parse
1045 * @text_len: length of @text in bytes
1046 * @error: return location for a #GError
1048 * Feed some data to the #GMarkupParseContext.
1050 * The data need not be valid UTF-8; an error will be signaled if
1051 * it's invalid. The data need not be an entire document; you can
1052 * feed a document into the parser incrementally, via multiple calls
1053 * to this function. Typically, as you receive data from a network
1054 * connection or file, you feed each received chunk of data into this
1055 * function, aborting the process if an error occurs. Once an error
1056 * is reported, no further data may be fed to the #GMarkupParseContext;
1057 * all errors are fatal.
1059 * Return value: %FALSE if an error occurred, %TRUE on success
1061 gboolean
1062 g_markup_parse_context_parse (GMarkupParseContext *context,
1063 const gchar *text,
1064 gssize text_len,
1065 GError **error)
1067 g_return_val_if_fail (context != NULL, FALSE);
1068 g_return_val_if_fail (text != NULL, FALSE);
1069 g_return_val_if_fail (context->state != STATE_ERROR, FALSE);
1070 g_return_val_if_fail (!context->parsing, FALSE);
1072 if (text_len < 0)
1073 text_len = strlen (text);
1075 if (text_len == 0)
1076 return TRUE;
1078 context->parsing = TRUE;
1081 context->current_text = text;
1082 context->current_text_len = text_len;
1083 context->current_text_end = context->current_text + text_len;
1084 context->iter = context->current_text;
1085 context->start = context->iter;
1087 while (context->iter != context->current_text_end)
1089 switch (context->state)
1091 case STATE_START:
1092 /* Possible next state: AFTER_OPEN_ANGLE */
1094 g_assert (context->tag_stack == NULL);
1096 /* whitespace is ignored outside of any elements */
1097 skip_spaces (context);
1099 if (context->iter != context->current_text_end)
1101 if (*context->iter == '<')
1103 /* Move after the open angle */
1104 advance_char (context);
1106 context->state = STATE_AFTER_OPEN_ANGLE;
1108 /* this could start a passthrough */
1109 context->start = context->iter;
1111 /* document is now non-empty */
1112 context->document_empty = FALSE;
1114 else
1116 set_error_literal (context,
1117 error,
1118 G_MARKUP_ERROR_PARSE,
1119 _("Document must begin with an element (e.g. <book>)"));
1122 break;
1124 case STATE_AFTER_OPEN_ANGLE:
1125 /* Possible next states: INSIDE_OPEN_TAG_NAME,
1126 * AFTER_CLOSE_TAG_SLASH, INSIDE_PASSTHROUGH
1128 if (*context->iter == '?' ||
1129 *context->iter == '!')
1131 /* include < in the passthrough */
1132 const gchar *openangle = "<";
1133 add_to_partial (context, openangle, openangle + 1);
1134 context->start = context->iter;
1135 context->balance = 1;
1136 context->state = STATE_INSIDE_PASSTHROUGH;
1138 else if (*context->iter == '/')
1140 /* move after it */
1141 advance_char (context);
1143 context->state = STATE_AFTER_CLOSE_TAG_SLASH;
1145 else if (!IS_COMMON_NAME_END_CHAR (*(context->iter)))
1147 context->state = STATE_INSIDE_OPEN_TAG_NAME;
1149 /* start of tag name */
1150 context->start = context->iter;
1152 else
1154 gchar buf[8];
1156 set_error (context,
1157 error,
1158 G_MARKUP_ERROR_PARSE,
1159 _("'%s' is not a valid character following "
1160 "a '<' character; it may not begin an "
1161 "element name"),
1162 utf8_str (context->iter, buf));
1164 break;
1166 /* The AFTER_CLOSE_ANGLE state is actually sort of
1167 * broken, because it doesn't correspond to a range
1168 * of characters in the input stream as the others do,
1169 * and thus makes things harder to conceptualize
1171 case STATE_AFTER_CLOSE_ANGLE:
1172 /* Possible next states: INSIDE_TEXT, STATE_START */
1173 if (context->tag_stack == NULL)
1175 context->start = NULL;
1176 context->state = STATE_START;
1178 else
1180 context->start = context->iter;
1181 context->state = STATE_INSIDE_TEXT;
1183 break;
1185 case STATE_AFTER_ELISION_SLASH:
1186 /* Possible next state: AFTER_CLOSE_ANGLE */
1189 /* We need to pop the tag stack and call the end_element
1190 * function, since this is the close tag
1192 GError *tmp_error = NULL;
1194 g_assert (context->tag_stack != NULL);
1196 possibly_finish_subparser (context);
1198 tmp_error = NULL;
1199 if (context->parser->end_element)
1200 (* context->parser->end_element) (context,
1201 current_element (context),
1202 context->user_data,
1203 &tmp_error);
1205 ensure_no_outstanding_subparser (context);
1207 if (tmp_error)
1209 mark_error (context, tmp_error);
1210 g_propagate_error (error, tmp_error);
1212 else
1214 if (*context->iter == '>')
1216 /* move after the close angle */
1217 advance_char (context);
1218 context->state = STATE_AFTER_CLOSE_ANGLE;
1220 else
1222 gchar buf[8];
1224 set_error (context,
1225 error,
1226 G_MARKUP_ERROR_PARSE,
1227 _("Odd character '%s', expected a '>' character "
1228 "to end the empty-element tag '%s'"),
1229 utf8_str (context->iter, buf),
1230 current_element (context));
1233 pop_tag (context);
1235 break;
1237 case STATE_INSIDE_OPEN_TAG_NAME:
1238 /* Possible next states: BETWEEN_ATTRIBUTES */
1240 /* if there's a partial chunk then it's the first part of the
1241 * tag name. If there's a context->start then it's the start
1242 * of the tag name in current_text, the partial chunk goes
1243 * before that start though.
1245 advance_to_name_end (context);
1247 if (context->iter == context->current_text_end)
1249 /* The name hasn't necessarily ended. Merge with
1250 * partial chunk, leave state unchanged.
1252 add_to_partial (context, context->start, context->iter);
1254 else
1256 /* The name has ended. Combine it with the partial chunk
1257 * if any; push it on the stack; enter next state.
1259 add_to_partial (context, context->start, context->iter);
1260 push_partial_as_tag (context);
1262 context->state = STATE_BETWEEN_ATTRIBUTES;
1263 context->start = NULL;
1265 break;
1267 case STATE_INSIDE_ATTRIBUTE_NAME:
1268 /* Possible next states: AFTER_ATTRIBUTE_NAME */
1270 advance_to_name_end (context);
1271 add_to_partial (context, context->start, context->iter);
1273 /* read the full name, if we enter the equals sign state
1274 * then add the attribute to the list (without the value),
1275 * otherwise store a partial chunk to be prepended later.
1277 if (context->iter != context->current_text_end)
1278 context->state = STATE_AFTER_ATTRIBUTE_NAME;
1279 break;
1281 case STATE_AFTER_ATTRIBUTE_NAME:
1282 /* Possible next states: AFTER_ATTRIBUTE_EQUALS_SIGN */
1284 skip_spaces (context);
1286 if (context->iter != context->current_text_end)
1288 /* The name has ended. Combine it with the partial chunk
1289 * if any; push it on the stack; enter next state.
1291 if (!name_validate (context, context->partial_chunk->str, error))
1292 break;
1294 add_attribute (context, context->partial_chunk);
1296 context->partial_chunk = NULL;
1297 context->start = NULL;
1299 if (*context->iter == '=')
1301 advance_char (context);
1302 context->state = STATE_AFTER_ATTRIBUTE_EQUALS_SIGN;
1304 else
1306 gchar buf[8];
1308 set_error (context,
1309 error,
1310 G_MARKUP_ERROR_PARSE,
1311 _("Odd character '%s', expected a '=' after "
1312 "attribute name '%s' of element '%s'"),
1313 utf8_str (context->iter, buf),
1314 current_attribute (context),
1315 current_element (context));
1319 break;
1321 case STATE_BETWEEN_ATTRIBUTES:
1322 /* Possible next states: AFTER_CLOSE_ANGLE,
1323 * AFTER_ELISION_SLASH, INSIDE_ATTRIBUTE_NAME
1325 skip_spaces (context);
1327 if (context->iter != context->current_text_end)
1329 if (*context->iter == '/')
1331 advance_char (context);
1332 context->state = STATE_AFTER_ELISION_SLASH;
1334 else if (*context->iter == '>')
1336 advance_char (context);
1337 context->state = STATE_AFTER_CLOSE_ANGLE;
1339 else if (!IS_COMMON_NAME_END_CHAR (*(context->iter)))
1341 context->state = STATE_INSIDE_ATTRIBUTE_NAME;
1342 /* start of attribute name */
1343 context->start = context->iter;
1345 else
1347 gchar buf[8];
1349 set_error (context,
1350 error,
1351 G_MARKUP_ERROR_PARSE,
1352 _("Odd character '%s', expected a '>' or '/' "
1353 "character to end the start tag of "
1354 "element '%s', or optionally an attribute; "
1355 "perhaps you used an invalid character in "
1356 "an attribute name"),
1357 utf8_str (context->iter, buf),
1358 current_element (context));
1361 /* If we're done with attributes, invoke
1362 * the start_element callback
1364 if (context->state == STATE_AFTER_ELISION_SLASH ||
1365 context->state == STATE_AFTER_CLOSE_ANGLE)
1366 emit_start_element (context, error);
1368 break;
1370 case STATE_AFTER_ATTRIBUTE_EQUALS_SIGN:
1371 /* Possible next state: INSIDE_ATTRIBUTE_VALUE_[SQ/DQ] */
1373 skip_spaces (context);
1375 if (context->iter != context->current_text_end)
1377 if (*context->iter == '"')
1379 advance_char (context);
1380 context->state = STATE_INSIDE_ATTRIBUTE_VALUE_DQ;
1381 context->start = context->iter;
1383 else if (*context->iter == '\'')
1385 advance_char (context);
1386 context->state = STATE_INSIDE_ATTRIBUTE_VALUE_SQ;
1387 context->start = context->iter;
1389 else
1391 gchar buf[8];
1393 set_error (context,
1394 error,
1395 G_MARKUP_ERROR_PARSE,
1396 _("Odd character '%s', expected an open quote mark "
1397 "after the equals sign when giving value for "
1398 "attribute '%s' of element '%s'"),
1399 utf8_str (context->iter, buf),
1400 current_attribute (context),
1401 current_element (context));
1404 break;
1406 case STATE_INSIDE_ATTRIBUTE_VALUE_SQ:
1407 case STATE_INSIDE_ATTRIBUTE_VALUE_DQ:
1408 /* Possible next states: BETWEEN_ATTRIBUTES */
1410 gchar delim;
1412 if (context->state == STATE_INSIDE_ATTRIBUTE_VALUE_SQ)
1414 delim = '\'';
1416 else
1418 delim = '"';
1423 if (*context->iter == delim)
1424 break;
1426 while (advance_char (context));
1428 if (context->iter == context->current_text_end)
1430 /* The value hasn't necessarily ended. Merge with
1431 * partial chunk, leave state unchanged.
1433 add_to_partial (context, context->start, context->iter);
1435 else
1437 gboolean is_ascii;
1438 /* The value has ended at the quote mark. Combine it
1439 * with the partial chunk if any; set it for the current
1440 * attribute.
1442 add_to_partial (context, context->start, context->iter);
1444 g_assert (context->cur_attr >= 0);
1446 if (unescape_gstring_inplace (context, context->partial_chunk, &is_ascii, error) &&
1447 (is_ascii || text_validate (context, context->partial_chunk->str,
1448 context->partial_chunk->len, error)))
1450 /* success, advance past quote and set state. */
1451 context->attr_values[context->cur_attr] = context->partial_chunk;
1452 context->partial_chunk = NULL;
1453 advance_char (context);
1454 context->state = STATE_BETWEEN_ATTRIBUTES;
1455 context->start = NULL;
1458 truncate_partial (context);
1460 break;
1462 case STATE_INSIDE_TEXT:
1463 /* Possible next states: AFTER_OPEN_ANGLE */
1466 if (*context->iter == '<')
1467 break;
1469 while (advance_char (context));
1471 /* The text hasn't necessarily ended. Merge with
1472 * partial chunk, leave state unchanged.
1475 add_to_partial (context, context->start, context->iter);
1477 if (context->iter != context->current_text_end)
1479 gboolean is_ascii;
1481 /* The text has ended at the open angle. Call the text
1482 * callback.
1484 if (unescape_gstring_inplace (context, context->partial_chunk, &is_ascii, error) &&
1485 (is_ascii || text_validate (context, context->partial_chunk->str,
1486 context->partial_chunk->len, error)))
1488 GError *tmp_error = NULL;
1490 if (context->parser->text)
1491 (*context->parser->text) (context,
1492 context->partial_chunk->str,
1493 context->partial_chunk->len,
1494 context->user_data,
1495 &tmp_error);
1497 if (tmp_error == NULL)
1499 /* advance past open angle and set state. */
1500 advance_char (context);
1501 context->state = STATE_AFTER_OPEN_ANGLE;
1502 /* could begin a passthrough */
1503 context->start = context->iter;
1505 else
1506 propagate_error (context, error, tmp_error);
1509 truncate_partial (context);
1511 break;
1513 case STATE_AFTER_CLOSE_TAG_SLASH:
1514 /* Possible next state: INSIDE_CLOSE_TAG_NAME */
1515 if (!IS_COMMON_NAME_END_CHAR (*(context->iter)))
1517 context->state = STATE_INSIDE_CLOSE_TAG_NAME;
1519 /* start of tag name */
1520 context->start = context->iter;
1522 else
1524 gchar buf[8];
1526 set_error (context,
1527 error,
1528 G_MARKUP_ERROR_PARSE,
1529 _("'%s' is not a valid character following "
1530 "the characters '</'; '%s' may not begin an "
1531 "element name"),
1532 utf8_str (context->iter, buf),
1533 utf8_str (context->iter, buf));
1535 break;
1537 case STATE_INSIDE_CLOSE_TAG_NAME:
1538 /* Possible next state: AFTER_CLOSE_TAG_NAME */
1539 advance_to_name_end (context);
1540 add_to_partial (context, context->start, context->iter);
1542 if (context->iter != context->current_text_end)
1543 context->state = STATE_AFTER_CLOSE_TAG_NAME;
1544 break;
1546 case STATE_AFTER_CLOSE_TAG_NAME:
1547 /* Possible next state: AFTER_CLOSE_TAG_SLASH */
1549 skip_spaces (context);
1551 if (context->iter != context->current_text_end)
1553 GString *close_name;
1555 close_name = context->partial_chunk;
1556 context->partial_chunk = NULL;
1558 if (*context->iter != '>')
1560 gchar buf[8];
1562 set_error (context,
1563 error,
1564 G_MARKUP_ERROR_PARSE,
1565 _("'%s' is not a valid character following "
1566 "the close element name '%s'; the allowed "
1567 "character is '>'"),
1568 utf8_str (context->iter, buf),
1569 close_name->str);
1571 else if (context->tag_stack == NULL)
1573 set_error (context,
1574 error,
1575 G_MARKUP_ERROR_PARSE,
1576 _("Element '%s' was closed, no element "
1577 "is currently open"),
1578 close_name->str);
1580 else if (strcmp (close_name->str, current_element (context)) != 0)
1582 set_error (context,
1583 error,
1584 G_MARKUP_ERROR_PARSE,
1585 _("Element '%s' was closed, but the currently "
1586 "open element is '%s'"),
1587 close_name->str,
1588 current_element (context));
1590 else
1592 GError *tmp_error;
1593 advance_char (context);
1594 context->state = STATE_AFTER_CLOSE_ANGLE;
1595 context->start = NULL;
1597 possibly_finish_subparser (context);
1599 /* call the end_element callback */
1600 tmp_error = NULL;
1601 if (context->parser->end_element)
1602 (* context->parser->end_element) (context,
1603 close_name->str,
1604 context->user_data,
1605 &tmp_error);
1607 ensure_no_outstanding_subparser (context);
1608 pop_tag (context);
1610 if (tmp_error)
1611 propagate_error (context, error, tmp_error);
1613 context->partial_chunk = close_name;
1614 truncate_partial (context);
1616 break;
1618 case STATE_INSIDE_PASSTHROUGH:
1619 /* Possible next state: AFTER_CLOSE_ANGLE */
1622 if (*context->iter == '<')
1623 context->balance++;
1624 if (*context->iter == '>')
1626 gchar *str;
1627 gsize len;
1629 context->balance--;
1630 add_to_partial (context, context->start, context->iter);
1631 context->start = context->iter;
1633 str = context->partial_chunk->str;
1634 len = context->partial_chunk->len;
1636 if (str[1] == '?' && str[len - 1] == '?')
1637 break;
1638 if (strncmp (str, "<!--", 4) == 0 &&
1639 strcmp (str + len - 2, "--") == 0)
1640 break;
1641 if (strncmp (str, "<![CDATA[", 9) == 0 &&
1642 strcmp (str + len - 2, "]]") == 0)
1643 break;
1644 if (strncmp (str, "<!DOCTYPE", 9) == 0 &&
1645 context->balance == 0)
1646 break;
1649 while (advance_char (context));
1651 if (context->iter == context->current_text_end)
1653 /* The passthrough hasn't necessarily ended. Merge with
1654 * partial chunk, leave state unchanged.
1656 add_to_partial (context, context->start, context->iter);
1658 else
1660 /* The passthrough has ended at the close angle. Combine
1661 * it with the partial chunk if any. Call the passthrough
1662 * callback. Note that the open/close angles are
1663 * included in the text of the passthrough.
1665 GError *tmp_error = NULL;
1667 advance_char (context); /* advance past close angle */
1668 add_to_partial (context, context->start, context->iter);
1670 if (context->flags & G_MARKUP_TREAT_CDATA_AS_TEXT &&
1671 strncmp (context->partial_chunk->str, "<![CDATA[", 9) == 0)
1673 if (context->parser->text &&
1674 text_validate (context,
1675 context->partial_chunk->str + 9,
1676 context->partial_chunk->len - 12,
1677 error))
1678 (*context->parser->text) (context,
1679 context->partial_chunk->str + 9,
1680 context->partial_chunk->len - 12,
1681 context->user_data,
1682 &tmp_error);
1684 else if (context->parser->passthrough &&
1685 text_validate (context,
1686 context->partial_chunk->str,
1687 context->partial_chunk->len,
1688 error))
1689 (*context->parser->passthrough) (context,
1690 context->partial_chunk->str,
1691 context->partial_chunk->len,
1692 context->user_data,
1693 &tmp_error);
1695 truncate_partial (context);
1697 if (tmp_error == NULL)
1699 context->state = STATE_AFTER_CLOSE_ANGLE;
1700 context->start = context->iter; /* could begin text */
1702 else
1703 propagate_error (context, error, tmp_error);
1705 break;
1707 case STATE_ERROR:
1708 goto finished;
1709 break;
1711 default:
1712 g_assert_not_reached ();
1713 break;
1717 finished:
1718 context->parsing = FALSE;
1720 return context->state != STATE_ERROR;
1724 * g_markup_parse_context_end_parse:
1725 * @context: a #GMarkupParseContext
1726 * @error: return location for a #GError
1728 * Signals to the #GMarkupParseContext that all data has been
1729 * fed into the parse context with g_markup_parse_context_parse().
1731 * This function reports an error if the document isn't complete,
1732 * for example if elements are still open.
1734 * Return value: %TRUE on success, %FALSE if an error was set
1736 gboolean
1737 g_markup_parse_context_end_parse (GMarkupParseContext *context,
1738 GError **error)
1740 g_return_val_if_fail (context != NULL, FALSE);
1741 g_return_val_if_fail (!context->parsing, FALSE);
1742 g_return_val_if_fail (context->state != STATE_ERROR, FALSE);
1744 if (context->partial_chunk != NULL)
1746 g_string_free (context->partial_chunk, TRUE);
1747 context->partial_chunk = NULL;
1750 if (context->document_empty)
1752 set_error_literal (context, error, G_MARKUP_ERROR_EMPTY,
1753 _("Document was empty or contained only whitespace"));
1754 return FALSE;
1757 context->parsing = TRUE;
1759 switch (context->state)
1761 case STATE_START:
1762 /* Nothing to do */
1763 break;
1765 case STATE_AFTER_OPEN_ANGLE:
1766 set_error_literal (context, error, G_MARKUP_ERROR_PARSE,
1767 _("Document ended unexpectedly just after an open angle bracket '<'"));
1768 break;
1770 case STATE_AFTER_CLOSE_ANGLE:
1771 if (context->tag_stack != NULL)
1773 /* Error message the same as for INSIDE_TEXT */
1774 set_error (context, error, G_MARKUP_ERROR_PARSE,
1775 _("Document ended unexpectedly with elements still open - "
1776 "'%s' was the last element opened"),
1777 current_element (context));
1779 break;
1781 case STATE_AFTER_ELISION_SLASH:
1782 set_error (context, error, G_MARKUP_ERROR_PARSE,
1783 _("Document ended unexpectedly, expected to see a close angle "
1784 "bracket ending the tag <%s/>"), current_element (context));
1785 break;
1787 case STATE_INSIDE_OPEN_TAG_NAME:
1788 set_error_literal (context, error, G_MARKUP_ERROR_PARSE,
1789 _("Document ended unexpectedly inside an element name"));
1790 break;
1792 case STATE_INSIDE_ATTRIBUTE_NAME:
1793 case STATE_AFTER_ATTRIBUTE_NAME:
1794 set_error_literal (context, error, G_MARKUP_ERROR_PARSE,
1795 _("Document ended unexpectedly inside an attribute name"));
1796 break;
1798 case STATE_BETWEEN_ATTRIBUTES:
1799 set_error_literal (context, error, G_MARKUP_ERROR_PARSE,
1800 _("Document ended unexpectedly inside an element-opening "
1801 "tag."));
1802 break;
1804 case STATE_AFTER_ATTRIBUTE_EQUALS_SIGN:
1805 set_error_literal (context, error, G_MARKUP_ERROR_PARSE,
1806 _("Document ended unexpectedly after the equals sign "
1807 "following an attribute name; no attribute value"));
1808 break;
1810 case STATE_INSIDE_ATTRIBUTE_VALUE_SQ:
1811 case STATE_INSIDE_ATTRIBUTE_VALUE_DQ:
1812 set_error_literal (context, error, G_MARKUP_ERROR_PARSE,
1813 _("Document ended unexpectedly while inside an attribute "
1814 "value"));
1815 break;
1817 case STATE_INSIDE_TEXT:
1818 g_assert (context->tag_stack != NULL);
1819 set_error (context, error, G_MARKUP_ERROR_PARSE,
1820 _("Document ended unexpectedly with elements still open - "
1821 "'%s' was the last element opened"),
1822 current_element (context));
1823 break;
1825 case STATE_AFTER_CLOSE_TAG_SLASH:
1826 case STATE_INSIDE_CLOSE_TAG_NAME:
1827 case STATE_AFTER_CLOSE_TAG_NAME:
1828 set_error (context, error, G_MARKUP_ERROR_PARSE,
1829 _("Document ended unexpectedly inside the close tag for "
1830 "element '%s'"), current_element (context));
1831 break;
1833 case STATE_INSIDE_PASSTHROUGH:
1834 set_error_literal (context, error, G_MARKUP_ERROR_PARSE,
1835 _("Document ended unexpectedly inside a comment or "
1836 "processing instruction"));
1837 break;
1839 case STATE_ERROR:
1840 default:
1841 g_assert_not_reached ();
1842 break;
1845 context->parsing = FALSE;
1847 return context->state != STATE_ERROR;
1851 * g_markup_parse_context_get_element:
1852 * @context: a #GMarkupParseContext
1854 * Retrieves the name of the currently open element.
1856 * If called from the start_element or end_element handlers this will
1857 * give the element_name as passed to those functions. For the parent
1858 * elements, see g_markup_parse_context_get_element_stack().
1860 * Returns: the name of the currently open element, or %NULL
1862 * Since: 2.2
1864 const gchar *
1865 g_markup_parse_context_get_element (GMarkupParseContext *context)
1867 g_return_val_if_fail (context != NULL, NULL);
1869 if (context->tag_stack == NULL)
1870 return NULL;
1871 else
1872 return current_element (context);
1876 * g_markup_parse_context_get_element_stack:
1877 * @context: a #GMarkupParseContext
1879 * Retrieves the element stack from the internal state of the parser.
1881 * The returned #GSList is a list of strings where the first item is
1882 * the currently open tag (as would be returned by
1883 * g_markup_parse_context_get_element()) and the next item is its
1884 * immediate parent.
1886 * This function is intended to be used in the start_element and
1887 * end_element handlers where g_markup_parse_context_get_element()
1888 * would merely return the name of the element that is being
1889 * processed.
1891 * Returns: the element stack, which must not be modified
1893 * Since: 2.16
1895 const GSList *
1896 g_markup_parse_context_get_element_stack (GMarkupParseContext *context)
1898 g_return_val_if_fail (context != NULL, NULL);
1899 return context->tag_stack;
1903 * g_markup_parse_context_get_position:
1904 * @context: a #GMarkupParseContext
1905 * @line_number: (allow-none): return location for a line number, or %NULL
1906 * @char_number: (allow-none): return location for a char-on-line number, or %NULL
1908 * Retrieves the current line number and the number of the character on
1909 * that line. Intended for use in error messages; there are no strict
1910 * semantics for what constitutes the "current" line number other than
1911 * "the best number we could come up with for error messages."
1913 void
1914 g_markup_parse_context_get_position (GMarkupParseContext *context,
1915 gint *line_number,
1916 gint *char_number)
1918 g_return_if_fail (context != NULL);
1920 if (line_number)
1921 *line_number = context->line_number;
1923 if (char_number)
1924 *char_number = context->char_number;
1928 * g_markup_parse_context_get_user_data:
1929 * @context: a #GMarkupParseContext
1931 * Returns the user_data associated with @context.
1933 * This will either be the user_data that was provided to
1934 * g_markup_parse_context_new() or to the most recent call
1935 * of g_markup_parse_context_push().
1937 * Returns: the provided user_data. The returned data belongs to
1938 * the markup context and will be freed when
1939 * g_markup_parse_context_free() is called.
1941 * Since: 2.18
1943 gpointer
1944 g_markup_parse_context_get_user_data (GMarkupParseContext *context)
1946 return context->user_data;
1950 * g_markup_parse_context_push:
1951 * @context: a #GMarkupParseContext
1952 * @parser: a #GMarkupParser
1953 * @user_data: user data to pass to #GMarkupParser functions
1955 * Temporarily redirects markup data to a sub-parser.
1957 * This function may only be called from the start_element handler of
1958 * a #GMarkupParser. It must be matched with a corresponding call to
1959 * g_markup_parse_context_pop() in the matching end_element handler
1960 * (except in the case that the parser aborts due to an error).
1962 * All tags, text and other data between the matching tags is
1963 * redirected to the subparser given by @parser. @user_data is used
1964 * as the user_data for that parser. @user_data is also passed to the
1965 * error callback in the event that an error occurs. This includes
1966 * errors that occur in subparsers of the subparser.
1968 * The end tag matching the start tag for which this call was made is
1969 * handled by the previous parser (which is given its own user_data)
1970 * which is why g_markup_parse_context_pop() is provided to allow "one
1971 * last access" to the @user_data provided to this function. In the
1972 * case of error, the @user_data provided here is passed directly to
1973 * the error callback of the subparser and g_markup_parse_context_pop()
1974 * should not be called. In either case, if @user_data was allocated
1975 * then it ought to be freed from both of these locations.
1977 * This function is not intended to be directly called by users
1978 * interested in invoking subparsers. Instead, it is intended to be
1979 * used by the subparsers themselves to implement a higher-level
1980 * interface.
1982 * As an example, see the following implementation of a simple
1983 * parser that counts the number of tags encountered.
1985 * |[
1986 * typedef struct
1988 * gint tag_count;
1989 * } CounterData;
1991 * static void
1992 * counter_start_element (GMarkupParseContext *context,
1993 * const gchar *element_name,
1994 * const gchar **attribute_names,
1995 * const gchar **attribute_values,
1996 * gpointer user_data,
1997 * GError **error)
1999 * CounterData *data = user_data;
2001 * data->tag_count++;
2004 * static void
2005 * counter_error (GMarkupParseContext *context,
2006 * GError *error,
2007 * gpointer user_data)
2009 * CounterData *data = user_data;
2011 * g_slice_free (CounterData, data);
2014 * static GMarkupParser counter_subparser =
2016 * counter_start_element,
2017 * NULL,
2018 * NULL,
2019 * NULL,
2020 * counter_error
2021 * };
2022 * ]|
2024 * In order to allow this parser to be easily used as a subparser, the
2025 * following interface is provided:
2027 * |[
2028 * void
2029 * start_counting (GMarkupParseContext *context)
2031 * CounterData *data = g_slice_new (CounterData);
2033 * data->tag_count = 0;
2034 * g_markup_parse_context_push (context, &counter_subparser, data);
2037 * gint
2038 * end_counting (GMarkupParseContext *context)
2040 * CounterData *data = g_markup_parse_context_pop (context);
2041 * int result;
2043 * result = data->tag_count;
2044 * g_slice_free (CounterData, data);
2046 * return result;
2048 * ]|
2050 * The subparser would then be used as follows:
2052 * |[
2053 * static void start_element (context, element_name, ...)
2055 * if (strcmp (element_name, "count-these") == 0)
2056 * start_counting (context);
2058 * /&ast; else, handle other tags... &ast;/
2061 * static void end_element (context, element_name, ...)
2063 * if (strcmp (element_name, "count-these") == 0)
2064 * g_print ("Counted %d tags\n", end_counting (context));
2066 * /&ast; else, handle other tags... &ast;/
2068 * ]|
2070 * Since: 2.18
2072 void
2073 g_markup_parse_context_push (GMarkupParseContext *context,
2074 const GMarkupParser *parser,
2075 gpointer user_data)
2077 GMarkupRecursionTracker *tracker;
2079 tracker = g_slice_new (GMarkupRecursionTracker);
2080 tracker->prev_element = context->subparser_element;
2081 tracker->prev_parser = context->parser;
2082 tracker->prev_user_data = context->user_data;
2084 context->subparser_element = current_element (context);
2085 context->parser = parser;
2086 context->user_data = user_data;
2088 context->subparser_stack = g_slist_prepend (context->subparser_stack,
2089 tracker);
2093 * g_markup_parse_context_pop:
2094 * @context: a #GMarkupParseContext
2096 * Completes the process of a temporary sub-parser redirection.
2098 * This function exists to collect the user_data allocated by a
2099 * matching call to g_markup_parse_context_push(). It must be called
2100 * in the end_element handler corresponding to the start_element
2101 * handler during which g_markup_parse_context_push() was called.
2102 * You must not call this function from the error callback -- the
2103 * @user_data is provided directly to the callback in that case.
2105 * This function is not intended to be directly called by users
2106 * interested in invoking subparsers. Instead, it is intended to
2107 * be used by the subparsers themselves to implement a higher-level
2108 * interface.
2110 * Returns: the user data passed to g_markup_parse_context_push()
2112 * Since: 2.18
2114 gpointer
2115 g_markup_parse_context_pop (GMarkupParseContext *context)
2117 gpointer user_data;
2119 if (!context->awaiting_pop)
2120 possibly_finish_subparser (context);
2122 g_assert (context->awaiting_pop);
2124 context->awaiting_pop = FALSE;
2126 /* valgrind friendliness */
2127 user_data = context->held_user_data;
2128 context->held_user_data = NULL;
2130 return user_data;
2133 static void
2134 append_escaped_text (GString *str,
2135 const gchar *text,
2136 gssize length)
2138 const gchar *p;
2139 const gchar *end;
2140 gunichar c;
2142 p = text;
2143 end = text + length;
2145 while (p != end)
2147 const gchar *next;
2148 next = g_utf8_next_char (p);
2150 switch (*p)
2152 case '&':
2153 g_string_append (str, "&amp;");
2154 break;
2156 case '<':
2157 g_string_append (str, "&lt;");
2158 break;
2160 case '>':
2161 g_string_append (str, "&gt;");
2162 break;
2164 case '\'':
2165 g_string_append (str, "&apos;");
2166 break;
2168 case '"':
2169 g_string_append (str, "&quot;");
2170 break;
2172 default:
2173 c = g_utf8_get_char (p);
2174 if ((0x1 <= c && c <= 0x8) ||
2175 (0xb <= c && c <= 0xc) ||
2176 (0xe <= c && c <= 0x1f) ||
2177 (0x7f <= c && c <= 0x84) ||
2178 (0x86 <= c && c <= 0x9f))
2179 g_string_append_printf (str, "&#x%x;", c);
2180 else
2181 g_string_append_len (str, p, next - p);
2182 break;
2185 p = next;
2190 * g_markup_escape_text:
2191 * @text: some valid UTF-8 text
2192 * @length: length of @text in bytes, or -1 if the text is nul-terminated
2194 * Escapes text so that the markup parser will parse it verbatim.
2195 * Less than, greater than, ampersand, etc. are replaced with the
2196 * corresponding entities. This function would typically be used
2197 * when writing out a file to be parsed with the markup parser.
2199 * Note that this function doesn't protect whitespace and line endings
2200 * from being processed according to the XML rules for normalization
2201 * of line endings and attribute values.
2203 * Note also that this function will produce character references in
2204 * the range of &amp;#x1; ... &amp;#x1f; for all control sequences
2205 * except for tabstop, newline and carriage return. The character
2206 * references in this range are not valid XML 1.0, but they are
2207 * valid XML 1.1 and will be accepted by the GMarkup parser.
2209 * Return value: a newly allocated string with the escaped text
2211 gchar*
2212 g_markup_escape_text (const gchar *text,
2213 gssize length)
2215 GString *str;
2217 g_return_val_if_fail (text != NULL, NULL);
2219 if (length < 0)
2220 length = strlen (text);
2222 /* prealloc at least as long as original text */
2223 str = g_string_sized_new (length);
2224 append_escaped_text (str, text, length);
2226 return g_string_free (str, FALSE);
2230 * find_conversion:
2231 * @format: a printf-style format string
2232 * @after: location to store a pointer to the character after
2233 * the returned conversion. On a %NULL return, returns the
2234 * pointer to the trailing NUL in the string
2236 * Find the next conversion in a printf-style format string.
2237 * Partially based on code from printf-parser.c,
2238 * Copyright (C) 1999-2000, 2002-2003 Free Software Foundation, Inc.
2240 * Return value: pointer to the next conversion in @format,
2241 * or %NULL, if none.
2243 static const char *
2244 find_conversion (const char *format,
2245 const char **after)
2247 const char *start = format;
2248 const char *cp;
2250 while (*start != '\0' && *start != '%')
2251 start++;
2253 if (*start == '\0')
2255 *after = start;
2256 return NULL;
2259 cp = start + 1;
2261 if (*cp == '\0')
2263 *after = cp;
2264 return NULL;
2267 /* Test for positional argument. */
2268 if (*cp >= '0' && *cp <= '9')
2270 const char *np;
2272 for (np = cp; *np >= '0' && *np <= '9'; np++)
2274 if (*np == '$')
2275 cp = np + 1;
2278 /* Skip the flags. */
2279 for (;;)
2281 if (*cp == '\'' ||
2282 *cp == '-' ||
2283 *cp == '+' ||
2284 *cp == ' ' ||
2285 *cp == '#' ||
2286 *cp == '0')
2287 cp++;
2288 else
2289 break;
2292 /* Skip the field width. */
2293 if (*cp == '*')
2295 cp++;
2297 /* Test for positional argument. */
2298 if (*cp >= '0' && *cp <= '9')
2300 const char *np;
2302 for (np = cp; *np >= '0' && *np <= '9'; np++)
2304 if (*np == '$')
2305 cp = np + 1;
2308 else
2310 for (; *cp >= '0' && *cp <= '9'; cp++)
2314 /* Skip the precision. */
2315 if (*cp == '.')
2317 cp++;
2318 if (*cp == '*')
2320 /* Test for positional argument. */
2321 if (*cp >= '0' && *cp <= '9')
2323 const char *np;
2325 for (np = cp; *np >= '0' && *np <= '9'; np++)
2327 if (*np == '$')
2328 cp = np + 1;
2331 else
2333 for (; *cp >= '0' && *cp <= '9'; cp++)
2338 /* Skip argument type/size specifiers. */
2339 while (*cp == 'h' ||
2340 *cp == 'L' ||
2341 *cp == 'l' ||
2342 *cp == 'j' ||
2343 *cp == 'z' ||
2344 *cp == 'Z' ||
2345 *cp == 't')
2346 cp++;
2348 /* Skip the conversion character. */
2349 cp++;
2351 *after = cp;
2352 return start;
2356 * g_markup_vprintf_escaped:
2357 * @format: printf() style format string
2358 * @args: variable argument list, similar to vprintf()
2360 * Formats the data in @args according to @format, escaping
2361 * all string and character arguments in the fashion
2362 * of g_markup_escape_text(). See g_markup_printf_escaped().
2364 * Return value: newly allocated result from formatting
2365 * operation. Free with g_free().
2367 * Since: 2.4
2369 gchar *
2370 g_markup_vprintf_escaped (const gchar *format,
2371 va_list args)
2373 GString *format1;
2374 GString *format2;
2375 GString *result = NULL;
2376 gchar *output1 = NULL;
2377 gchar *output2 = NULL;
2378 const char *p, *op1, *op2;
2379 va_list args2;
2381 /* The technique here, is that we make two format strings that
2382 * have the identical conversions in the identical order to the
2383 * original strings, but differ in the text in-between. We
2384 * then use the normal g_strdup_vprintf() to format the arguments
2385 * with the two new format strings. By comparing the results,
2386 * we can figure out what segments of the output come from
2387 * the original format string, and what from the arguments,
2388 * and thus know what portions of the string to escape.
2390 * For instance, for:
2392 * g_markup_printf_escaped ("%s ate %d apples", "Susan & Fred", 5);
2394 * We form the two format strings "%sX%dX" and %sY%sY". The results
2395 * of formatting with those two strings are
2397 * "%sX%dX" => "Susan & FredX5X"
2398 * "%sY%dY" => "Susan & FredY5Y"
2400 * To find the span of the first argument, we find the first position
2401 * where the two arguments differ, which tells us that the first
2402 * argument formatted to "Susan & Fred". We then escape that
2403 * to "Susan &amp; Fred" and join up with the intermediate portions
2404 * of the format string and the second argument to get
2405 * "Susan &amp; Fred ate 5 apples".
2408 /* Create the two modified format strings
2410 format1 = g_string_new (NULL);
2411 format2 = g_string_new (NULL);
2412 p = format;
2413 while (TRUE)
2415 const char *after;
2416 const char *conv = find_conversion (p, &after);
2417 if (!conv)
2418 break;
2420 g_string_append_len (format1, conv, after - conv);
2421 g_string_append_c (format1, 'X');
2422 g_string_append_len (format2, conv, after - conv);
2423 g_string_append_c (format2, 'Y');
2425 p = after;
2428 /* Use them to format the arguments
2430 G_VA_COPY (args2, args);
2432 output1 = g_strdup_vprintf (format1->str, args);
2433 if (!output1)
2435 va_end (args2);
2436 goto cleanup;
2439 output2 = g_strdup_vprintf (format2->str, args2);
2440 va_end (args2);
2441 if (!output2)
2442 goto cleanup;
2444 result = g_string_new (NULL);
2446 /* Iterate through the original format string again,
2447 * copying the non-conversion portions and the escaped
2448 * converted arguments to the output string.
2450 op1 = output1;
2451 op2 = output2;
2452 p = format;
2453 while (TRUE)
2455 const char *after;
2456 const char *output_start;
2457 const char *conv = find_conversion (p, &after);
2458 char *escaped;
2460 if (!conv) /* The end, after points to the trailing \0 */
2462 g_string_append_len (result, p, after - p);
2463 break;
2466 g_string_append_len (result, p, conv - p);
2467 output_start = op1;
2468 while (*op1 == *op2)
2470 op1++;
2471 op2++;
2474 escaped = g_markup_escape_text (output_start, op1 - output_start);
2475 g_string_append (result, escaped);
2476 g_free (escaped);
2478 p = after;
2479 op1++;
2480 op2++;
2483 cleanup:
2484 g_string_free (format1, TRUE);
2485 g_string_free (format2, TRUE);
2486 g_free (output1);
2487 g_free (output2);
2489 if (result)
2490 return g_string_free (result, FALSE);
2491 else
2492 return NULL;
2496 * g_markup_printf_escaped:
2497 * @format: printf() style format string
2498 * @...: the arguments to insert in the format string
2500 * Formats arguments according to @format, escaping
2501 * all string and character arguments in the fashion
2502 * of g_markup_escape_text(). This is useful when you
2503 * want to insert literal strings into XML-style markup
2504 * output, without having to worry that the strings
2505 * might themselves contain markup.
2507 * |[
2508 * const char *store = "Fortnum &amp; Mason";
2509 * const char *item = "Tea";
2510 * char *output;
2511 * &nbsp;
2512 * output = g_markup_printf_escaped ("&lt;purchase&gt;"
2513 * "&lt;store&gt;&percnt;s&lt;/store&gt;"
2514 * "&lt;item&gt;&percnt;s&lt;/item&gt;"
2515 * "&lt;/purchase&gt;",
2516 * store, item);
2517 * ]|
2519 * Return value: newly allocated result from formatting
2520 * operation. Free with g_free().
2522 * Since: 2.4
2524 gchar *
2525 g_markup_printf_escaped (const gchar *format, ...)
2527 char *result;
2528 va_list args;
2530 va_start (args, format);
2531 result = g_markup_vprintf_escaped (format, args);
2532 va_end (args);
2534 return result;
2537 static gboolean
2538 g_markup_parse_boolean (const char *string,
2539 gboolean *value)
2541 char const * const falses[] = { "false", "f", "no", "n", "0" };
2542 char const * const trues[] = { "true", "t", "yes", "y", "1" };
2543 int i;
2545 for (i = 0; i < G_N_ELEMENTS (falses); i++)
2547 if (g_ascii_strcasecmp (string, falses[i]) == 0)
2549 if (value != NULL)
2550 *value = FALSE;
2552 return TRUE;
2556 for (i = 0; i < G_N_ELEMENTS (trues); i++)
2558 if (g_ascii_strcasecmp (string, trues[i]) == 0)
2560 if (value != NULL)
2561 *value = TRUE;
2563 return TRUE;
2567 return FALSE;
2571 * GMarkupCollectType:
2572 * @G_MARKUP_COLLECT_INVALID: used to terminate the list of attributes
2573 * to collect
2574 * @G_MARKUP_COLLECT_STRING: collect the string pointer directly from
2575 * the attribute_values[] array. Expects a parameter of type (const
2576 * char **). If %G_MARKUP_COLLECT_OPTIONAL is specified and the
2577 * attribute isn't present then the pointer will be set to %NULL
2578 * @G_MARKUP_COLLECT_STRDUP: as with %G_MARKUP_COLLECT_STRING, but
2579 * expects a parameter of type (char **) and g_strdup()s the
2580 * returned pointer. The pointer must be freed with g_free()
2581 * @G_MARKUP_COLLECT_BOOLEAN: expects a parameter of type (gboolean *)
2582 * and parses the attribute value as a boolean. Sets %FALSE if the
2583 * attribute isn't present. Valid boolean values consist of
2584 * (case-insensitive) "false", "f", "no", "n", "0" and "true", "t",
2585 * "yes", "y", "1"
2586 * @G_MARKUP_COLLECT_TRISTATE: as with %G_MARKUP_COLLECT_BOOLEAN, but
2587 * in the case of a missing attribute a value is set that compares
2588 * equal to neither %FALSE nor %TRUE G_MARKUP_COLLECT_OPTIONAL is
2589 * implied
2590 * @G_MARKUP_COLLECT_OPTIONAL: can be bitwise ORed with the other fields.
2591 * If present, allows the attribute not to appear. A default value
2592 * is set depending on what value type is used
2594 * A mixed enumerated type and flags field. You must specify one type
2595 * (string, strdup, boolean, tristate). Additionally, you may optionally
2596 * bitwise OR the type with the flag %G_MARKUP_COLLECT_OPTIONAL.
2598 * It is likely that this enum will be extended in the future to
2599 * support other types.
2603 * g_markup_collect_attributes:
2604 * @element_name: the current tag name
2605 * @attribute_names: the attribute names
2606 * @attribute_values: the attribute values
2607 * @error: a pointer to a #GError or %NULL
2608 * @first_type: the #GMarkupCollectType of the first attribute
2609 * @first_attr: the name of the first attribute
2610 * @...: a pointer to the storage location of the first attribute
2611 * (or %NULL), followed by more types names and pointers, ending
2612 * with %G_MARKUP_COLLECT_INVALID
2614 * Collects the attributes of the element from the data passed to the
2615 * #GMarkupParser start_element function, dealing with common error
2616 * conditions and supporting boolean values.
2618 * This utility function is not required to write a parser but can save
2619 * a lot of typing.
2621 * The @element_name, @attribute_names, @attribute_values and @error
2622 * parameters passed to the start_element callback should be passed
2623 * unmodified to this function.
2625 * Following these arguments is a list of "supported" attributes to collect.
2626 * It is an error to specify multiple attributes with the same name. If any
2627 * attribute not in the list appears in the @attribute_names array then an
2628 * unknown attribute error will result.
2630 * The #GMarkupCollectType field allows specifying the type of collection
2631 * to perform and if a given attribute must appear or is optional.
2633 * The attribute name is simply the name of the attribute to collect.
2635 * The pointer should be of the appropriate type (see the descriptions
2636 * under #GMarkupCollectType) and may be %NULL in case a particular
2637 * attribute is to be allowed but ignored.
2639 * This function deals with issuing errors for missing attributes
2640 * (of type %G_MARKUP_ERROR_MISSING_ATTRIBUTE), unknown attributes
2641 * (of type %G_MARKUP_ERROR_UNKNOWN_ATTRIBUTE) and duplicate
2642 * attributes (of type %G_MARKUP_ERROR_INVALID_CONTENT) as well
2643 * as parse errors for boolean-valued attributes (again of type
2644 * %G_MARKUP_ERROR_INVALID_CONTENT). In all of these cases %FALSE
2645 * will be returned and @error will be set as appropriate.
2647 * Return value: %TRUE if successful
2649 * Since: 2.16
2651 gboolean
2652 g_markup_collect_attributes (const gchar *element_name,
2653 const gchar **attribute_names,
2654 const gchar **attribute_values,
2655 GError **error,
2656 GMarkupCollectType first_type,
2657 const gchar *first_attr,
2658 ...)
2660 GMarkupCollectType type;
2661 const gchar *attr;
2662 guint64 collected;
2663 int written;
2664 va_list ap;
2665 int i;
2667 type = first_type;
2668 attr = first_attr;
2669 collected = 0;
2670 written = 0;
2672 va_start (ap, first_attr);
2673 while (type != G_MARKUP_COLLECT_INVALID)
2675 gboolean mandatory;
2676 const gchar *value;
2678 mandatory = !(type & G_MARKUP_COLLECT_OPTIONAL);
2679 type &= (G_MARKUP_COLLECT_OPTIONAL - 1);
2681 /* tristate records a value != TRUE and != FALSE
2682 * for the case where the attribute is missing
2684 if (type == G_MARKUP_COLLECT_TRISTATE)
2685 mandatory = FALSE;
2687 for (i = 0; attribute_names[i]; i++)
2688 if (i >= 40 || !(collected & (G_GUINT64_CONSTANT(1) << i)))
2689 if (!strcmp (attribute_names[i], attr))
2690 break;
2692 /* ISO C99 only promises that the user can pass up to 127 arguments.
2693 * Subtracting the first 4 arguments plus the final NULL and dividing
2694 * by 3 arguments per collected attribute, we are left with a maximum
2695 * number of supported attributes of (127 - 5) / 3 = 40.
2697 * In reality, nobody is ever going to call us with anywhere close to
2698 * 40 attributes to collect, so it is safe to assume that if i > 40
2699 * then the user has given some invalid or repeated arguments. These
2700 * problems will be caught and reported at the end of the function.
2702 * We know at this point that we have an error, but we don't know
2703 * what error it is, so just continue...
2705 if (i < 40)
2706 collected |= (G_GUINT64_CONSTANT(1) << i);
2708 value = attribute_values[i];
2710 if (value == NULL && mandatory)
2712 g_set_error (error, G_MARKUP_ERROR,
2713 G_MARKUP_ERROR_MISSING_ATTRIBUTE,
2714 "element '%s' requires attribute '%s'",
2715 element_name, attr);
2717 va_end (ap);
2718 goto failure;
2721 switch (type)
2723 case G_MARKUP_COLLECT_STRING:
2725 const char **str_ptr;
2727 str_ptr = va_arg (ap, const char **);
2729 if (str_ptr != NULL)
2730 *str_ptr = value;
2732 break;
2734 case G_MARKUP_COLLECT_STRDUP:
2736 char **str_ptr;
2738 str_ptr = va_arg (ap, char **);
2740 if (str_ptr != NULL)
2741 *str_ptr = g_strdup (value);
2743 break;
2745 case G_MARKUP_COLLECT_BOOLEAN:
2746 case G_MARKUP_COLLECT_TRISTATE:
2747 if (value == NULL)
2749 gboolean *bool_ptr;
2751 bool_ptr = va_arg (ap, gboolean *);
2753 if (bool_ptr != NULL)
2755 if (type == G_MARKUP_COLLECT_TRISTATE)
2756 /* constructivists rejoice!
2757 * neither false nor true...
2759 *bool_ptr = -1;
2761 else /* G_MARKUP_COLLECT_BOOLEAN */
2762 *bool_ptr = FALSE;
2765 else
2767 if (!g_markup_parse_boolean (value, va_arg (ap, gboolean *)))
2769 g_set_error (error, G_MARKUP_ERROR,
2770 G_MARKUP_ERROR_INVALID_CONTENT,
2771 "element '%s', attribute '%s', value '%s' "
2772 "cannot be parsed as a boolean value",
2773 element_name, attr, value);
2775 va_end (ap);
2776 goto failure;
2780 break;
2782 default:
2783 g_assert_not_reached ();
2786 type = va_arg (ap, GMarkupCollectType);
2787 attr = va_arg (ap, const char *);
2788 written++;
2790 va_end (ap);
2792 /* ensure we collected all the arguments */
2793 for (i = 0; attribute_names[i]; i++)
2794 if ((collected & (G_GUINT64_CONSTANT(1) << i)) == 0)
2796 /* attribute not collected: could be caused by two things.
2798 * 1) it doesn't exist in our list of attributes
2799 * 2) it existed but was matched by a duplicate attribute earlier
2801 * find out.
2803 int j;
2805 for (j = 0; j < i; j++)
2806 if (strcmp (attribute_names[i], attribute_names[j]) == 0)
2807 /* duplicate! */
2808 break;
2810 /* j is now the first occurrence of attribute_names[i] */
2811 if (i == j)
2812 g_set_error (error, G_MARKUP_ERROR,
2813 G_MARKUP_ERROR_UNKNOWN_ATTRIBUTE,
2814 "attribute '%s' invalid for element '%s'",
2815 attribute_names[i], element_name);
2816 else
2817 g_set_error (error, G_MARKUP_ERROR,
2818 G_MARKUP_ERROR_INVALID_CONTENT,
2819 "attribute '%s' given multiple times for element '%s'",
2820 attribute_names[i], element_name);
2822 goto failure;
2825 return TRUE;
2827 failure:
2828 /* replay the above to free allocations */
2829 type = first_type;
2830 attr = first_attr;
2832 va_start (ap, first_attr);
2833 while (type != G_MARKUP_COLLECT_INVALID)
2835 gpointer ptr;
2837 ptr = va_arg (ap, gpointer);
2839 if (ptr != NULL)
2841 switch (type & (G_MARKUP_COLLECT_OPTIONAL - 1))
2843 case G_MARKUP_COLLECT_STRDUP:
2844 if (written)
2845 g_free (*(char **) ptr);
2847 case G_MARKUP_COLLECT_STRING:
2848 *(char **) ptr = NULL;
2849 break;
2851 case G_MARKUP_COLLECT_BOOLEAN:
2852 *(gboolean *) ptr = FALSE;
2853 break;
2855 case G_MARKUP_COLLECT_TRISTATE:
2856 *(gboolean *) ptr = -1;
2857 break;
2861 type = va_arg (ap, GMarkupCollectType);
2862 attr = va_arg (ap, const char *);
2864 va_end (ap);
2866 return FALSE;