create a common function for the many places where all nodes in the table
[platform/upstream/glib.git] / glib / gmarkup.c
index 484d448..381bea2 100644 (file)
@@ -27,9 +27,8 @@
 #include <errno.h>
 
 #include "glib.h"
-#include "galias.h"
-
 #include "glibintl.h"
+#include "galias.h"
 
 GQuark
 g_markup_error_quark (void)
@@ -222,20 +221,34 @@ set_error (GMarkupParseContext *context,
   s = g_strdup_vprintf (format, args);
   va_end (args);
 
-  tmp_error = g_error_new (G_MARKUP_ERROR,
-                           code,
-                           _("Error on line %d char %d: %s"),
-                           context->line_number,
-                           context->char_number,
-                           s);
-
+  tmp_error = g_error_new_literal (G_MARKUP_ERROR, code, s);
   g_free (s);
 
+  g_prefix_error (&tmp_error,
+                  _("Error on line %d char %d: "),
+                  context->line_number,
+                  context->char_number);
+
   mark_error (context, tmp_error);
 
   g_propagate_error (error, tmp_error);
 }
 
+static void
+propagate_error (GMarkupParseContext  *context,
+                 GError              **dest,
+                 GError               *src)
+{
+  if (context->flags & G_MARKUP_PREFIX_ERROR_POSITION)
+    g_prefix_error (&src,
+                    _("Error on line %d char %d: "),
+                    context->line_number,
+                    context->char_number);
+
+  mark_error (context, src);
+
+  g_propagate_error (dest, src);
+}
 
 /* To make these faster, we first use the ascii-only tests, then check
  * for the usual non-alnum name-end chars, and only then call the
@@ -956,7 +969,7 @@ g_markup_parse_context_parse (GMarkupParseContext *context,
               set_error (context,
                          error,
                          G_MARKUP_ERROR_BAD_UTF8,
-                         _("Invalid UTF-8 encoded text"));
+                         _("Invalid UTF-8 encoded text - overlong sequence"));
             }
           
           goto finished;
@@ -984,7 +997,7 @@ g_markup_parse_context_parse (GMarkupParseContext *context,
       set_error (context,
                  error,
                  G_MARKUP_ERROR_BAD_UTF8,
-                 _("Invalid UTF-8 encoded text"));
+                 _("Invalid UTF-8 encoded text - not a start char"));
       goto finished;
     }
 
@@ -1001,21 +1014,28 @@ g_markup_parse_context_parse (GMarkupParseContext *context,
                        &first_invalid))
     {
       gint newlines = 0;
-      const gchar *p;
-      p = context->current_text;
-      while (p != context->current_text_end)
+      const gchar *p, *q;
+      q = p = context->current_text;
+      while (p != first_invalid)
         {
           if (*p == '\n')
-            ++newlines;
+            {
+              ++newlines;
+              q = p + 1;
+              context->char_number = 1;
+            }
           ++p;
         }
 
       context->line_number += newlines;
+      context->char_number += g_utf8_strlen (q, first_invalid - q);
 
       set_error (context,
                  error,
                  G_MARKUP_ERROR_BAD_UTF8,
-                 _("Invalid UTF-8 encoded text"));
+                 _("Invalid UTF-8 encoded text - not valid '%s'"),
+                 g_strndup (context->current_text,
+                            context->current_text_len));
       goto finished;
     }
 
@@ -1341,10 +1361,7 @@ g_markup_parse_context_parse (GMarkupParseContext *context,
                             context->attr_values[0] == NULL);
                   
                   if (tmp_error != NULL)
-                    {
-                      mark_error (context, tmp_error);
-                      g_propagate_error (error, tmp_error);
-                    }
+                    propagate_error (context, error, tmp_error);
                 }
             }
           break;
@@ -1494,10 +1511,7 @@ g_markup_parse_context_parse (GMarkupParseContext *context,
                       context->start = context->iter;
                     }
                   else
-                    {
-                      mark_error (context, tmp_error);
-                      g_propagate_error (error, tmp_error);
-                    }
+                    propagate_error (context, error, tmp_error);
                 }
 
               truncate_partial (context);
@@ -1607,10 +1621,7 @@ g_markup_parse_context_parse (GMarkupParseContext *context,
                                                            context->tag_stack);
                  
                  if (tmp_error)
-                    {
-                      mark_error (context, tmp_error);
-                      g_propagate_error (error, tmp_error);
-                    }
+                    propagate_error (context, error, tmp_error);
                 }
              
               g_free (close_name);
@@ -1624,18 +1635,27 @@ g_markup_parse_context_parse (GMarkupParseContext *context,
              if (*context->iter == '<') 
                context->balance++;
               if (*context->iter == '>') 
-               {
+               {                               
+                 gchar *str;
+                 gsize len;
+
                  context->balance--;
                  add_to_partial (context, context->start, context->iter);
                  context->start = context->iter;
-                 if ((g_str_has_prefix (context->partial_chunk->str, "<?")
-                      && g_str_has_suffix (context->partial_chunk->str, "?")) ||
-                     (g_str_has_prefix (context->partial_chunk->str, "<!--")
-                      && g_str_has_suffix (context->partial_chunk->str, "--")) ||
-                     (g_str_has_prefix (context->partial_chunk->str, "<![CDATA[") 
-                      && g_str_has_suffix (context->partial_chunk->str, "]]")) ||
-                     (g_str_has_prefix (context->partial_chunk->str, "<!DOCTYPE")
-                      && context->balance == 0)) 
+
+                 str = context->partial_chunk->str;
+                 len = context->partial_chunk->len;
+
+                 if (str[1] == '?' && str[len - 1] == '?')
+                   break;
+                 if (strncmp (str, "<!--", 4) == 0 && 
+                     strcmp (str + len - 2, "--") == 0)
+                   break;
+                 if (strncmp (str, "<![CDATA[", 9) == 0 && 
+                     strcmp (str + len - 2, "]]") == 0)
+                   break;
+                 if (strncmp (str, "<!DOCTYPE", 9) == 0 &&
+                     context->balance == 0)
                    break;
                }
             }
@@ -1661,13 +1681,12 @@ g_markup_parse_context_parse (GMarkupParseContext *context,
               add_to_partial (context, context->start, context->iter);
 
              if (context->flags & G_MARKUP_TREAT_CDATA_AS_TEXT &&
-                 g_str_has_prefix (context->partial_chunk->str, "<![CDATA[") &&
-                 g_str_has_suffix (context->partial_chunk->str, "]]>"))
+                 strncmp (context->partial_chunk->str, "<![CDATA[", 9) == 0)
                {
                  if (context->parser->text)
                    (*context->parser->text) (context,
-                                             context->partial_chunk->str + strlen ("<![CDATA["),
-                                             context->partial_chunk->len - strlen ("<![CDATA[" "]]>"),
+                                             context->partial_chunk->str + 9,
+                                             context->partial_chunk->len - 12,
                                              context->user_data,
                                              &tmp_error);
                }
@@ -1686,10 +1705,7 @@ g_markup_parse_context_parse (GMarkupParseContext *context,
                   context->start = context->iter; /* could begin text */
                 }
               else
-                {
-                  mark_error (context, tmp_error);
-                  g_propagate_error (error, tmp_error);
-                }
+                propagate_error (context, error, tmp_error);
             }
           break;
 
@@ -1778,6 +1794,7 @@ g_markup_parse_context_end_parse (GMarkupParseContext *context,
       break;
 
     case STATE_INSIDE_ATTRIBUTE_NAME:
+    case STATE_AFTER_ATTRIBUTE_NAME:
       set_error (context, error, G_MARKUP_ERROR_PARSE,
                  _("Document ended unexpectedly inside an attribute name"));
       break;
@@ -1811,6 +1828,7 @@ g_markup_parse_context_end_parse (GMarkupParseContext *context,
 
     case STATE_AFTER_CLOSE_TAG_SLASH:
     case STATE_INSIDE_CLOSE_TAG_NAME:
+    case STATE_AFTER_CLOSE_TAG_NAME:
       set_error (context, error, G_MARKUP_ERROR_PARSE,
                  _("Document ended unexpectedly inside the close tag for "
                    "element '%s'"), current_element (context));
@@ -1840,6 +1858,10 @@ g_markup_parse_context_end_parse (GMarkupParseContext *context,
  *
  * Retrieves the name of the currently open element.
  *
+ * If called from the start_element or end_element handlers this will
+ * give the element_name as passed to those functions. For the parent
+ * elements, see g_markup_parse_context_get_element_stack().
+ *
  * Since: 2.2
  **/
 G_CONST_RETURN gchar *
@@ -1854,6 +1876,33 @@ g_markup_parse_context_get_element (GMarkupParseContext *context)
 } 
 
 /**
+ * g_markup_parse_context_get_element_stack:
+ * @context: a #GMarkupParseContext
+ *
+ * Retrieves the element stack from the internal state of the parser.
+ * The returned #GSList is a list of strings where the first item is
+ * the currently open tag (as would be returned by
+ * g_markup_parse_context_get_element()) and the next item is its
+ * immediate parent.
+ *
+ * This function is intended to be used in the start_element and
+ * end_element handlers where g_markup_parse_context_get_element()
+ * would merely return the name of the element that is being
+ * processed.
+ *
+ * Returns: the element stack, which must not be modified
+ *
+ * Since 2.16
+ **/
+G_CONST_RETURN GSList *
+g_markup_parse_context_get_element_stack (GMarkupParseContext *context)
+{
+  g_return_val_if_fail (context != NULL, NULL);
+
+  return context->tag_stack;
+}
+
+/**
  * g_markup_parse_context_get_position:
  * @context: a #GMarkupParseContext
  * @line_number: return location for a line number, or %NULL
@@ -1886,6 +1935,7 @@ append_escaped_text (GString     *str,
 {
   const gchar *p;
   const gchar *end;
+  gunichar c;
 
   p = text;
   end = text + length;
@@ -1918,7 +1968,15 @@ append_escaped_text (GString     *str,
           break;
 
         default:
-          g_string_append_len (str, p, next - p);
+          c = g_utf8_get_char (p);
+          if ((0x1 <= c && c <= 0x8) ||
+              (0xb <= c && c  <= 0xc) ||
+              (0xe <= c && c <= 0x1f) ||
+              (0x7f <= c && c <= 0x84) ||
+              (0x86 <= c && c <= 0x9f))
+            g_string_append_printf (str, "&#x%x;", c);
+          else
+            g_string_append_len (str, p, next - p);
           break;
         }
 
@@ -2164,9 +2222,11 @@ g_markup_vprintf_escaped (const char *format,
   G_VA_COPY (args2, args);
   
   output1 = g_strdup_vprintf (format1->str, args);
-  va_end (args);
   if (!output1)
-    goto cleanup;
+    {
+      va_end (args2);
+      goto cleanup;
+    }
   
   output2 = g_strdup_vprintf (format2->str, args2);
   va_end (args2);
@@ -2236,7 +2296,7 @@ g_markup_vprintf_escaped (const char *format,
  * output, without having to worry that the strings
  * might themselves contain markup.
  *
- * <informalexample><programlisting>
+ * |[
  * const char *store = "Fortnum &amp; Mason";
  * const char *item = "Tea";
  * char *output;
@@ -2246,7 +2306,7 @@ g_markup_vprintf_escaped (const char *format,
  *                                   "&lt;item&gt;&percnt;s&lt;/item&gt;"
  *                                   "&lt;/purchase&gt;",
  *                                   store, item);
- * </programlisting></informalexample>
+ * ]|
  * 
  * Return value: newly allocated result from formatting
  *  operation. Free with g_free().
@@ -2266,5 +2326,359 @@ g_markup_printf_escaped (const char *format, ...)
   return result;
 }
 
+static gboolean
+g_markup_parse_boolean (const char  *string,
+                        gboolean    *value)
+{
+  char const * const falses[] = { "false", "f", "no", "n", "0" };
+  char const * const trues[] = { "true", "t", "yes", "y", "1" };
+  int i;
+
+  for (i = 0; i < G_N_ELEMENTS (falses); i++)
+    {
+      if (g_ascii_strcasecmp (string, falses[i]) == 0)
+        {
+          if (value != NULL)
+            *value = FALSE;
+
+          return TRUE;
+        }
+    }
+
+  for (i = 0; i < G_N_ELEMENTS (trues); i++)
+    {
+      if (g_ascii_strcasecmp (string, trues[i]) == 0)
+        {
+          if (value != NULL)
+            *value = TRUE;
+
+          return TRUE;
+        }
+    }
+
+  return FALSE;
+}
+
+/**
+ * GMarkupCollectType:
+ * @G_MARKUP_COLLECT_INVALID: used to terminate the list of attributes
+ *                            to collect.
+ * @G_MARKUP_COLLECT_STRING: collect the string pointer directly from
+ *                           the attribute_values[] array.  Expects a
+ *                           parameter of type (const char **).  If
+ *                           %G_MARKUP_COLLECT_OPTIONAL is specified
+ *                           and the attribute isn't present then the
+ *                           pointer will be set to %NULL.
+ * @G_MARKUP_COLLECT_STRDUP: as with %G_MARKUP_COLLECT_STRING, but
+ *                           expects a paramter of type (char **) and
+ *                           g_strdup()s the returned pointer.  The
+ *                           pointer must be freed with g_free().
+ * @G_MARKUP_COLLECT_BOOLEAN: expects a parameter of type (gboolean *)
+ *                            and parses the attribute value as a
+ *                            boolean.  Sets %FALSE if the attribute
+ *                            isn't present.  Valid boolean values
+ *                            consist of (case insensitive) "false",
+ *                            "f", "no", "n", "0" and "true", "t",
+ *                            "yes", "y", "1".
+ * @G_MARKUP_COLLECT_TRISTATE: as with %G_MARKUP_COLLECT_BOOLEAN, but
+ *                             in the case of a missing attribute a
+ *                             value is set that compares equal to
+ *                             neither %FALSE nor %TRUE.
+ *                             G_MARKUP_COLLECT_OPTIONAL is implied.
+ * @G_MARKUP_COLLECT_OPTIONAL: can be bitwise ORed with the other
+ *                             fields.  If present, allows the
+ *                             attribute not to appear.  A default
+ *                             value is set depending on what value
+ *                             type is used.
+ *
+ * A mixed enumerated type and flags field.  You must specify one type
+ * (string, strdup, boolean, tristate).  Additionally, you may
+ * optionally bitwise OR the type with the flag
+ * %G_MARKUP_COLLECT_OPTIONAL.
+ *
+ * It is likely that this enum will be extended in the future to
+ * support other types.
+ **/
+
+/**
+ * g_markup_collect_attributes:
+ * @element_name: the current tag name
+ * @attribute_names: the attribute names
+ * @attribute_values: the attribute values
+ * @error: a pointer to a #GError or %NULL
+ * @first_type: the #GMarkupCollectType of the
+ *              first attribute
+ * @first_attr: the name of the first attribute
+ * @...: a pointer to the storage location of the
+ *       first attribute (or %NULL), followed by
+ *       more types names and pointers, ending
+ *       with %G_MARKUP_COLLECT_INVALID.
+ * 
+ * Collects the attributes of the element from the
+ * data passed to the #GMarkupParser start_element
+ * function, dealing with common error conditions
+ * and supporting boolean values.
+ *
+ * This utility function is not required to write
+ * a parser but can save a lot of typing.
+ *
+ * The @element_name, @attribute_names,
+ * @attribute_values and @error parameters passed
+ * to the start_element callback should be passed
+ * unmodified to this function.
+ *
+ * Following these arguments is a list of
+ * "supported" attributes to collect.  It is an
+ * error to specify multiple attributes with the
+ * same name.  If any attribute not in the list
+ * appears in the @attribute_names array then an
+ * unknown attribute error will result.
+ *
+ * The #GMarkupCollectType field allows specifying
+ * the type of collection to perform and if a
+ * given attribute must appear or is optional.
+ *
+ * The attribute name is simply the name of the
+ * attribute to collect.
+ *
+ * The pointer should be of the appropriate type
+ * (see the descriptions under
+ * #GMarkupCollectType) and may be %NULL in case a
+ * particular attribute is to be allowed but
+ * ignored.
+ *
+ * This function deals with issuing errors for missing attributes 
+ * (of type %G_MARKUP_ERROR_MISSING_ATTRIBUTE), unknown attributes 
+ * (of type %G_MARKUP_ERROR_UNKNOWN_ATTRIBUTE) and duplicate 
+ * attributes (of type %G_MARKUP_ERROR_INVALID_CONTENT) as well 
+ * as parse errors for boolean-valued attributes (again of type
+ * %G_MARKUP_ERROR_INVALID_CONTENT). In all of these cases %FALSE 
+ * will be returned and @error will be set as appropriate.
+ *
+ * Return value: %TRUE if successful
+ *
+ * Since: 2.16
+ **/
+gboolean
+g_markup_collect_attributes (const gchar         *element_name,
+                             const gchar        **attribute_names,
+                             const gchar        **attribute_values,
+                             GError             **error,
+                             GMarkupCollectType   first_type,
+                             const gchar         *first_attr,
+                             ...)
+{
+  GMarkupCollectType type;
+  const gchar *attr;
+  guint64 collected;
+  int written;
+  va_list ap;
+  int i;
+
+  type = first_type;
+  attr = first_attr;
+  collected = 0;
+  written = 0;
+
+  va_start (ap, first_attr);
+  while (type != G_MARKUP_COLLECT_INVALID)
+    {
+      gboolean mandatory;
+      const gchar *value;
+
+      mandatory = !(type & G_MARKUP_COLLECT_OPTIONAL);
+      type &= (G_MARKUP_COLLECT_OPTIONAL - 1);
+
+      /* tristate records a value != TRUE and != FALSE
+       * for the case where the attribute is missing
+       */
+      if (type == G_MARKUP_COLLECT_TRISTATE)
+        mandatory = FALSE;
+
+      for (i = 0; attribute_names[i]; i++)
+        if (i >= 40 || !(collected & (1ull << i)))
+          if (!strcmp (attribute_names[i], attr))
+            break;
+
+      /* ISO C99 only promises that the user can pass up to 127 arguments.
+       * Subtracting the first 4 arguments plus the final NULL and dividing
+       * by 3 arguments per collected attribute, we are left with a maximum
+       * number of supported attributes of (127 - 5) / 3 = 40.
+       *
+       * In reality, nobody is ever going to call us with anywhere close to
+       * 40 attributes to collect, so it is safe to assume that if i > 40
+       * then the user has given some invalid or repeated arguments.  These
+       * problems will be caught and reported at the end of the function.
+       *
+       * We know at this point that we have an error, but we don't know
+       * what error it is, so just continue...
+       */
+      if (i < 40)
+        collected |= (1ull << i);
+
+      value = attribute_values[i];
+
+      if (value == NULL && mandatory)
+        {
+          g_set_error (error, G_MARKUP_ERROR,
+                       G_MARKUP_ERROR_MISSING_ATTRIBUTE,
+                       "element '%s' requires attribute '%s'",
+                       element_name, attr);
+
+          va_end (ap);
+          goto failure;
+        }
+
+      switch (type)
+        {
+        case G_MARKUP_COLLECT_STRING:
+          {
+            const char **str_ptr;
+
+            str_ptr = va_arg (ap, const char **);
+
+            if (str_ptr != NULL)
+              *str_ptr = value;
+          }
+          break;
+
+        case G_MARKUP_COLLECT_STRDUP:
+          {
+            char **str_ptr;
+
+            str_ptr = va_arg (ap, char **);
+
+            if (str_ptr != NULL)
+              *str_ptr = g_strdup (value);
+          }
+          break;
+
+        case G_MARKUP_COLLECT_BOOLEAN:
+        case G_MARKUP_COLLECT_TRISTATE:
+          if (value == NULL)
+            {
+              gboolean *bool_ptr;
+
+              bool_ptr = va_arg (ap, gboolean *);
+
+              if (bool_ptr != NULL)
+                {
+                  if (type == G_MARKUP_COLLECT_TRISTATE)
+                    /* constructivists rejoice!
+                     * neither false nor true...
+                     */
+                    *bool_ptr = -1;
+
+                  else /* G_MARKUP_COLLECT_BOOLEAN */
+                    *bool_ptr = FALSE;
+                }
+            }
+          else
+            {
+              if (!g_markup_parse_boolean (value, va_arg (ap, gboolean *)))
+                {
+                  g_set_error (error, G_MARKUP_ERROR,
+                               G_MARKUP_ERROR_INVALID_CONTENT,
+                               "element '%s', attribute '%s', value '%s' "
+                               "cannot be parsed as a boolean value",
+                               element_name, attr, value);
+
+                  va_end (ap);
+                  goto failure;
+                }
+            }
+
+          break;
+
+        default:
+          g_assert_not_reached ();
+        }
+
+      type = va_arg (ap, GMarkupCollectType);
+      attr = va_arg (ap, const char *);
+      written++;
+    }
+  va_end (ap);
+
+  /* ensure we collected all the arguments */
+  for (i = 0; attribute_names[i]; i++)
+    if ((collected & (1 << i)) == 0)
+      {
+        /* attribute not collected:  could be caused by two things.
+         *
+         * 1) it doesn't exist in our list of attributes
+         * 2) it existed but was matched by a duplicate attribute earlier
+         *
+         * find out.
+         */
+        int j;
+
+        for (j = 0; j < i; j++)
+          if (strcmp (attribute_names[i], attribute_names[j]) == 0)
+            /* duplicate! */
+            break;
+
+        /* j is now the first occurance of attribute_names[i] */
+        if (i == j)
+          g_set_error (error, G_MARKUP_ERROR,
+                       G_MARKUP_ERROR_UNKNOWN_ATTRIBUTE,
+                       "attribute '%s' invalid for element '%s'",
+                       attribute_names[i], element_name);
+        else
+          g_set_error (error, G_MARKUP_ERROR,
+                       G_MARKUP_ERROR_INVALID_CONTENT,
+                       "attribute '%s' given multiple times for element '%s'",
+                       attribute_names[i], element_name);
+
+        goto failure;
+      }
+
+  return TRUE;
+
+failure:
+  /* replay the above to free allocations */
+  type = first_type;
+  attr = first_attr;
+
+  va_start (ap, first_attr);
+  while (type != G_MARKUP_COLLECT_INVALID)
+    {
+      gpointer ptr;
+
+      ptr = va_arg (ap, gpointer);
+
+      if (ptr == NULL)
+        continue;
+
+      switch (type & (G_MARKUP_COLLECT_OPTIONAL - 1))
+        {
+        case G_MARKUP_COLLECT_STRDUP:
+          if (written)
+            g_free (*(char **) ptr);
+
+        case G_MARKUP_COLLECT_STRING:
+          *(char **) ptr = NULL;
+          break;
+
+        case G_MARKUP_COLLECT_BOOLEAN:
+          *(gboolean *) ptr = FALSE;
+          break;
+
+        case G_MARKUP_COLLECT_TRISTATE:
+          *(gboolean *) ptr = -1;
+          break;
+        }
+
+      type = va_arg (ap, GMarkupCollectType);
+      attr = va_arg (ap, const char *);
+
+      if (written)
+        written--;
+    }
+  va_end (ap);
+
+  return FALSE;
+}
+
 #define __G_MARKUP_C__
 #include "galiasdef.c"