Prevent error pileup
[platform/upstream/glib.git] / gio / glib-compile-schemas.c
1 /*
2  * Copyright © 2010 Codethink Limited
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2 of the licence, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with this library; if not, write to the
16  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17  * Boston, MA 02111-1307, USA.
18  *
19  * Author: Ryan Lortie <desrt@desrt.ca>
20  */
21
22 /* Prologue {{{1 */
23 #define _GNU_SOURCE
24 #include "config.h"
25
26 #include <gstdio.h>
27 #include <locale.h>
28 #include <string.h>
29 #include <unistd.h>
30 #include <stdio.h>
31
32 #include <gi18n.h>
33
34 #include "gvdb/gvdb-builder.h"
35 #include "strinfo.c"
36
37 /* Handling of <enum> {{{1 */
38 typedef struct
39 {
40   GString *strinfo;
41
42   gboolean is_flags;
43 } EnumState;
44
45 static void
46 enum_state_free (gpointer data)
47 {
48   EnumState *state = data;
49
50   g_string_free (state->strinfo, TRUE);
51   g_slice_free (EnumState, state);
52 }
53
54 EnumState *
55 enum_state_new (gboolean is_flags)
56 {
57   EnumState *state;
58
59   state = g_slice_new (EnumState);
60   state->strinfo = g_string_new (NULL);
61   state->is_flags = is_flags;
62
63   return state;
64 }
65
66 static void
67 enum_state_add_value (EnumState    *state,
68                       const gchar  *nick,
69                       const gchar  *valuestr,
70                       GError      **error)
71 {
72   gint64 value;
73   gchar *end;
74
75   if (nick[0] == '\0' || nick[1] == '\0')
76     {
77       g_set_error (error, G_MARKUP_ERROR,
78                    G_MARKUP_ERROR_INVALID_CONTENT,
79                    "nick must be a minimum of 2 characters");
80       return;
81     }
82
83   value = g_ascii_strtoll (valuestr, &end, 0);
84   if (*end || state->is_flags ?
85                 (value > G_MAXUINT32 || value < 0) :
86                 (value > G_MAXINT32 || value < G_MININT32))
87     {
88       g_set_error (error, G_MARKUP_ERROR,
89                    G_MARKUP_ERROR_INVALID_CONTENT,
90                    "invalid numeric value");
91       return;
92     }
93
94   if (strinfo_builder_contains (state->strinfo, nick))
95     {
96       g_set_error (error, G_MARKUP_ERROR,
97                    G_MARKUP_ERROR_INVALID_CONTENT,
98                    "<value nick='%s'/> already specified", nick);
99       return;
100     }
101
102   if (strinfo_builder_contains_value (state->strinfo, value))
103     {
104       g_set_error (error, G_MARKUP_ERROR,
105                    G_MARKUP_ERROR_INVALID_CONTENT,
106                    "value='%s' already specified", valuestr);
107       return;
108     }
109
110   /* Silently drop the null case if it is mentioned.
111    * It is properly denoted with an empty array.
112    */
113   if (state->is_flags && value == 0)
114     return;
115
116   if (state->is_flags && (value & (value - 1)))
117     {
118       g_set_error (error, G_MARKUP_ERROR,
119                    G_MARKUP_ERROR_INVALID_CONTENT,
120                    "flags values must have at most 1 bit set");
121       return;
122     }
123
124   /* Since we reject exact duplicates of value='' and we only allow one
125    * bit to be set, it's not possible to have overlaps.
126    *
127    * If we loosen the one-bit-set restriction we need an overlap check.
128    */
129
130   strinfo_builder_append_item (state->strinfo, nick, value);
131 }
132
133 static void
134 enum_state_end (EnumState **state_ptr,
135                 GError    **error)
136 {
137   EnumState *state;
138
139   state = *state_ptr;
140   *state_ptr = NULL;
141
142   if (state->strinfo->len == 0)
143     g_set_error (error,
144                  G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT,
145                  "<%s> must contain at least one <value>",
146                  state->is_flags ? "flags" : "enum");
147 }
148
149 /* Handling of <key> {{{1 */
150 typedef struct
151 {
152   /* for <child>, @child_schema will be set.
153    * for <key>, everything else will be set.
154    */
155   gchar        *child_schema;
156
157
158   GVariantType *type;
159   gboolean      have_gettext_domain;
160
161   gchar         l10n;
162   gchar        *l10n_context;
163   GString      *unparsed_default_value;
164   GVariant     *default_value;
165
166   GString      *strinfo;
167   gboolean      is_enum;
168   gboolean      is_flags;
169
170   GVariant     *minimum;
171   GVariant     *maximum;
172
173   gboolean      has_choices;
174   gboolean      has_aliases;
175   gboolean      is_override;
176
177   gboolean      checked;
178   GVariant     *serialised;
179 } KeyState;
180
181 static KeyState *
182 key_state_new (const gchar *type_string,
183                const gchar *gettext_domain,
184                gboolean     is_enum,
185                gboolean     is_flags,
186                GString     *strinfo)
187 {
188   KeyState *state;
189
190   state = g_slice_new0 (KeyState);
191   state->type = g_variant_type_new (type_string);
192   state->have_gettext_domain = gettext_domain != NULL;
193   state->is_enum = is_enum;
194   state->is_flags = is_flags;
195
196   if (strinfo)
197     state->strinfo = g_string_new_len (strinfo->str, strinfo->len);
198   else
199     state->strinfo = g_string_new (NULL);
200
201   return state;
202 }
203
204 static KeyState *
205 key_state_override (KeyState    *state,
206                     const gchar *gettext_domain)
207 {
208   KeyState *copy;
209
210   copy = g_slice_new0 (KeyState);
211   copy->type = g_variant_type_copy (state->type);
212   copy->have_gettext_domain = gettext_domain != NULL;
213   copy->strinfo = g_string_new_len (state->strinfo->str,
214                                     state->strinfo->len);
215   copy->is_enum = state->is_enum;
216   copy->is_flags = state->is_flags;
217   copy->is_override = TRUE;
218
219   if (state->minimum)
220     {
221       copy->minimum = g_variant_ref (state->minimum);
222       copy->maximum = g_variant_ref (state->maximum);
223     }
224
225   return copy;
226 }
227
228 static KeyState *
229 key_state_new_child (const gchar *child_schema)
230 {
231   KeyState *state;
232
233   state = g_slice_new0 (KeyState);
234   state->child_schema = g_strdup (child_schema);
235
236   return state;
237 }
238
239 static gboolean
240 is_valid_choices (GVariant *variant,
241                   GString  *strinfo)
242 {
243   switch (g_variant_classify (variant))
244     {
245       case G_VARIANT_CLASS_MAYBE:
246       case G_VARIANT_CLASS_ARRAY:
247         {
248           gboolean valid = TRUE;
249           GVariantIter iter;
250
251           g_variant_iter_init (&iter, variant);
252
253           while (valid && (variant = g_variant_iter_next_value (&iter)))
254             {
255               valid = is_valid_choices (variant, strinfo);
256               g_variant_unref (variant);
257             }
258
259           return valid;
260         }
261
262       case G_VARIANT_CLASS_STRING:
263         return strinfo_is_string_valid ((const guint32 *) strinfo->str,
264                                         strinfo->len / 4,
265                                         g_variant_get_string (variant, NULL));
266
267       default:
268         g_assert_not_reached ();
269     }
270 }
271
272
273 /* Gets called at </default> </choices> or <range/> to check for
274  * validity of the default value so that any inconsistency is
275  * reported as soon as it is encountered.
276  */
277 static void
278 key_state_check_range (KeyState  *state,
279                        GError   **error)
280 {
281   if (state->default_value)
282     {
283       const gchar *tag;
284
285       tag = state->is_override ? "override" : "default";
286
287       if (state->minimum)
288         {
289           if (g_variant_compare (state->default_value, state->minimum) < 0 ||
290               g_variant_compare (state->default_value, state->maximum) > 0)
291             {
292               g_set_error (error, G_MARKUP_ERROR,
293                            G_MARKUP_ERROR_INVALID_CONTENT,
294                            "<%s> is not contained in "
295                            "the specified range", tag);
296             }
297         }
298
299       else if (state->strinfo->len)
300         {
301           if (!is_valid_choices (state->default_value, state->strinfo))
302             {
303               if (state->is_enum)
304                 g_set_error (error, G_MARKUP_ERROR,
305                              G_MARKUP_ERROR_INVALID_CONTENT,
306                              "<%s> is not a valid member of "
307                              "the specified enumerated type", tag);
308
309               else if (state->is_flags)
310                 g_set_error (error, G_MARKUP_ERROR,
311                              G_MARKUP_ERROR_INVALID_CONTENT,
312                              "<%s> contains string not in the "
313                              "specified flags type", tag);
314
315               else
316                 g_set_error (error, G_MARKUP_ERROR,
317                              G_MARKUP_ERROR_INVALID_CONTENT,
318                              "<%s> contains string not in "
319                              "<choices>", tag);
320             }
321         }
322     }
323 }
324
325 static void
326 key_state_set_range (KeyState     *state,
327                      const gchar  *min_str,
328                      const gchar  *max_str,
329                      GError      **error)
330 {
331   if (state->minimum)
332     {
333       g_set_error_literal (error, G_MARKUP_ERROR,
334                            G_MARKUP_ERROR_INVALID_CONTENT,
335                            "<range/> already specified for this key");
336       return;
337     }
338
339   if (strchr ("ynqiuxtd", *(char *) state->type) == NULL)
340     {
341       gchar *type = g_variant_type_dup_string (state->type);
342       g_set_error (error, G_MARKUP_ERROR,
343                   G_MARKUP_ERROR_INVALID_CONTENT,
344                   "<range> not allowed for keys of type '%s'", type);
345       g_free (type);
346       return;
347     }
348
349   state->minimum = g_variant_parse (state->type, min_str, NULL, NULL, error);
350   if (state->minimum == NULL)
351     return;
352
353   state->maximum = g_variant_parse (state->type, max_str, NULL, NULL, error);
354   if (state->maximum == NULL)
355     return;
356
357   if (g_variant_compare (state->minimum, state->maximum) > 0)
358     {
359       g_set_error (error, G_MARKUP_ERROR,
360                    G_MARKUP_ERROR_INVALID_CONTENT,
361                    "<range> specified minimum is greater than maxmimum");
362       return;
363     }
364
365   key_state_check_range (state, error);
366 }
367
368 static GString *
369 key_state_start_default (KeyState     *state,
370                          const gchar  *l10n,
371                          const gchar  *context,
372                          GError      **error)
373 {
374   if (l10n != NULL)
375     {
376       if (strcmp (l10n, "messages") == 0)
377         state->l10n = 'm';
378
379       else if (strcmp (l10n, "time") == 0)
380         state->l10n = 't';
381
382       else
383         {
384           g_set_error (error, G_MARKUP_ERROR,
385                        G_MARKUP_ERROR_INVALID_CONTENT,
386                        "unsupported l10n category: %s", l10n);
387           return NULL;
388         }
389
390       if (!state->have_gettext_domain)
391         {
392           g_set_error_literal (error, G_MARKUP_ERROR,
393                                G_MARKUP_ERROR_INVALID_CONTENT,
394                                "l10n requested, but no "
395                                "gettext domain given");
396           return NULL;
397         }
398
399       state->l10n_context = g_strdup (context);
400     }
401
402   else if (context != NULL)
403     {
404       g_set_error_literal (error, G_MARKUP_ERROR,
405                            G_MARKUP_ERROR_INVALID_CONTENT,
406                            "translation context given for "
407                            " value without l10n enabled");
408       return NULL;
409     }
410
411   return g_string_new (NULL);
412 }
413
414 static void
415 key_state_end_default (KeyState  *state,
416                        GString  **string,
417                        GError   **error)
418 {
419   state->unparsed_default_value = *string;
420   *string = NULL;
421
422   state->default_value = g_variant_parse (state->type,
423                                           state->unparsed_default_value->str,
424                                           NULL, NULL, error);
425   key_state_check_range (state, error);
426 }
427
428 static void
429 key_state_start_choices (KeyState  *state,
430                          GError   **error)
431 {
432   const GVariantType *type = state->type;
433
434   if (state->is_enum)
435     {
436       g_set_error_literal (error, G_MARKUP_ERROR,
437                            G_MARKUP_ERROR_INVALID_CONTENT,
438                            "<choices> can not be specified for keys "
439                            "tagged as having an enumerated type");
440       return;
441     }
442
443   if (state->has_choices)
444     {
445       g_set_error_literal (error, G_MARKUP_ERROR,
446                            G_MARKUP_ERROR_INVALID_CONTENT,
447                            "<choices> already specified for this key");
448       return;
449     }
450
451   while (g_variant_type_is_maybe (type) || g_variant_type_is_array (type))
452     type = g_variant_type_element (type);
453
454   if (!g_variant_type_equal (type, G_VARIANT_TYPE_STRING))
455     {
456       gchar *type_string = g_variant_type_dup_string (state->type);
457       g_set_error (error, G_MARKUP_ERROR,
458                    G_MARKUP_ERROR_INVALID_CONTENT,
459                    "<choices> not allowed for keys of type '%s'",
460                    type_string);
461       g_free (type_string);
462       return;
463     }
464 }
465
466 static void
467 key_state_add_choice (KeyState     *state,
468                       const gchar  *choice,
469                       GError      **error)
470 {
471   if (strinfo_builder_contains (state->strinfo, choice))
472     {
473       g_set_error (error, G_MARKUP_ERROR,
474                    G_MARKUP_ERROR_INVALID_CONTENT,
475                    "<choice value='%s'/> already given", choice);
476       return;
477     }
478
479   strinfo_builder_append_item (state->strinfo, choice, 0);
480   state->has_choices = TRUE;
481 }
482
483 static void
484 key_state_end_choices (KeyState  *state,
485                        GError   **error)
486 {
487   if (!state->has_choices)
488     {
489       g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT,
490                    "<choices> must contain at least one <choice>");
491       return;
492     }
493
494   key_state_check_range (state, error);
495 }
496
497 static void
498 key_state_start_aliases (KeyState  *state,
499                          GError   **error)
500 {
501   if (state->has_aliases)
502     g_set_error_literal (error, G_MARKUP_ERROR,
503                          G_MARKUP_ERROR_INVALID_CONTENT,
504                          "<aliases> already specified for this key");
505   else if (!state->is_flags && !state->is_enum && !state->has_choices)
506     g_set_error_literal (error, G_MARKUP_ERROR,
507                          G_MARKUP_ERROR_INVALID_CONTENT,
508                          "<aliases> can only be specified for keys with "
509                          "enumerated or flags types or after <choices>");
510 }
511
512 static void
513 key_state_add_alias (KeyState     *state,
514                      const gchar  *alias,
515                      const gchar  *target,
516                      GError      **error)
517 {
518   if (strinfo_builder_contains (state->strinfo, alias))
519     {
520       if (strinfo_is_string_valid ((guint32 *) state->strinfo->str,
521                                    state->strinfo->len / 4,
522                                    alias))
523         {
524           if (state->is_enum)
525             g_set_error (error, G_MARKUP_ERROR,
526                          G_MARKUP_ERROR_INVALID_CONTENT,
527                          "<alias value='%s'/> given when '%s' is already "
528                          "a member of the enumerated type", alias, alias);
529
530           else
531             g_set_error (error, G_MARKUP_ERROR,
532                          G_MARKUP_ERROR_INVALID_CONTENT,
533                          "<alias value='%s'/> given when "
534                          "<choice value='%s'/> was already given",
535                          alias, alias);
536         }
537
538       else
539         g_set_error (error, G_MARKUP_ERROR,
540                      G_MARKUP_ERROR_INVALID_CONTENT,
541                      "<alias value='%s'/> already specified", alias);
542
543       return;
544     }
545
546   if (!strinfo_builder_append_alias (state->strinfo, alias, target))
547     {
548       g_set_error (error, G_MARKUP_ERROR,
549                    G_MARKUP_ERROR_INVALID_CONTENT,
550                    "alias target '%s' is not in %s", target,
551                    state->is_enum ? "enumerated type" : "<choices>");
552       return;
553     }
554
555   state->has_aliases = TRUE;
556 }
557
558 static void
559 key_state_end_aliases (KeyState  *state,
560                        GError   **error)
561 {
562   if (!state->has_aliases)
563     {
564       g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT,
565                    "<aliases> must contain at least one <alias>");
566       return;
567     }
568 }
569
570 static gboolean
571 key_state_check (KeyState  *state,
572                  GError   **error)
573 {
574   if (state->checked)
575     return TRUE;
576
577   return state->checked = TRUE;
578 }
579
580 static GVariant *
581 key_state_serialise (KeyState *state)
582 {
583   if (state->serialised == NULL)
584     {
585       if (state->child_schema)
586         {
587           state->serialised = g_variant_new_string (state->child_schema);
588         }
589
590       else
591         {
592           GVariantBuilder builder;
593
594           g_assert (key_state_check (state, NULL));
595
596           g_variant_builder_init (&builder, G_VARIANT_TYPE_TUPLE);
597
598           /* default value */
599           g_variant_builder_add_value (&builder, state->default_value);
600
601           /* translation */
602           if (state->l10n)
603             {
604               if (state->l10n_context)
605                 {
606                   gint len;
607
608                   /* Contextified messages are supported by prepending
609                    * the context, followed by '\004' to the start of the
610                    * message string.  We do that here to save GSettings
611                    * the work later on.
612                    */
613                   len = strlen (state->l10n_context);
614                   state->l10n_context[len] = '\004';
615                   g_string_prepend_len (state->unparsed_default_value,
616                                         state->l10n_context, len + 1);
617                   g_free (state->l10n_context);
618                   state->l10n_context = NULL;
619                 }
620
621               g_variant_builder_add (&builder, "(y(y&s))", 'l', state->l10n,
622                                      state->unparsed_default_value->str);
623               g_string_free (state->unparsed_default_value, TRUE);
624               state->unparsed_default_value = NULL;
625             }
626
627           /* choice, aliases, enums */
628           if (state->strinfo->len)
629             {
630               GVariant *array;
631               guint32 *words;
632               gpointer data;
633               gsize size;
634               gint i;
635
636               data = state->strinfo->str;
637               size = state->strinfo->len;
638
639               words = data;
640               for (i = 0; i < size / sizeof (guint32); i++)
641                 words[i] = GUINT32_TO_LE (words[i]);
642
643               array = g_variant_new_from_data (G_VARIANT_TYPE ("au"),
644                                                data, size, TRUE,
645                                                g_free, data);
646
647               g_string_free (state->strinfo, FALSE);
648               state->strinfo = NULL;
649
650               g_variant_builder_add (&builder, "(y@au)",
651                                      state->is_flags ? 'f' :
652                                      state->is_enum ? 'e' : 'c',
653                                      array);
654             }
655
656           /* range */
657           if (state->minimum || state->maximum)
658             g_variant_builder_add (&builder, "(y(**))", 'r',
659                                    state->minimum, state->maximum);
660
661           state->serialised = g_variant_builder_end (&builder);
662         }
663
664       g_variant_ref_sink (state->serialised);
665     }
666
667   return g_variant_ref (state->serialised);
668 }
669
670 static void
671 key_state_free (gpointer data)
672 {
673   KeyState *state = data;
674
675   if (state->type)
676     g_variant_type_free (state->type);
677
678   g_free (state->l10n_context);
679
680   if (state->unparsed_default_value)
681     g_string_free (state->unparsed_default_value, TRUE);
682
683   if (state->default_value)
684     g_variant_unref (state->default_value);
685
686   if (state->strinfo)
687     g_string_free (state->strinfo, TRUE);
688
689   if (state->minimum)
690     g_variant_unref (state->minimum);
691
692   if (state->maximum)
693     g_variant_unref (state->maximum);
694
695   if (state->serialised)
696     g_variant_unref (state->serialised);
697
698   g_slice_free (KeyState, state);
699 }
700
701 /* Key name validity {{{1 */
702 static gboolean allow_any_name = FALSE;
703
704 static gboolean
705 is_valid_keyname (const gchar  *key,
706                   GError      **error)
707 {
708   gint i;
709
710   if (key[0] == '\0')
711     {
712       g_set_error_literal (error, G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT,
713                            _("empty names are not permitted"));
714       return FALSE;
715     }
716
717   if (allow_any_name)
718     return TRUE;
719
720   if (!g_ascii_islower (key[0]))
721     {
722       g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT,
723                    _("invalid name '%s': names must begin "
724                      "with a lowercase letter"), key);
725       return FALSE;
726     }
727
728   for (i = 1; key[i]; i++)
729     {
730       if (key[i] != '-' &&
731           !g_ascii_islower (key[i]) &&
732           !g_ascii_isdigit (key[i]))
733         {
734           g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT,
735                        _("invalid name '%s': invalid character '%c'; "
736                          "only lowercase letters, numbers and dash ('-') "
737                          "are permitted."), key, key[i]);
738           return FALSE;
739         }
740
741       if (key[i] == '-' && key[i + 1] == '-')
742         {
743           g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT,
744                        _("invalid name '%s': two successive dashes ('--') "
745                          "are not permitted."), key);
746           return FALSE;
747         }
748     }
749
750   if (key[i - 1] == '-')
751     {
752       g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT,
753                    _("invalid name '%s': the last character may not be a "
754                      "dash ('-')."), key);
755       return FALSE;
756     }
757
758   if (i > 32)
759     {
760       g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT,
761                    _("invalid name '%s': maximum length is 32"), key);
762       return FALSE;
763     }
764
765   return TRUE;
766 }
767
768 /* Handling of <schema> {{{1 */
769 typedef struct _SchemaState SchemaState;
770 struct _SchemaState
771 {
772   SchemaState *extends;
773
774   gchar       *path;
775   gchar       *gettext_domain;
776   gchar       *extends_name;
777   gchar       *list_of;
778
779   GHashTable  *keys;
780 };
781
782 static SchemaState *
783 schema_state_new (const gchar  *path,
784                   const gchar  *gettext_domain,
785                   SchemaState  *extends,
786                   const gchar  *extends_name,
787                   const gchar  *list_of)
788 {
789   SchemaState *state;
790
791   state = g_slice_new (SchemaState);
792   state->path = g_strdup (path);
793   state->gettext_domain = g_strdup (gettext_domain);
794   state->extends = extends;
795   state->extends_name = g_strdup (extends_name);
796   state->list_of = g_strdup (list_of);
797   state->keys = g_hash_table_new_full (g_str_hash, g_str_equal,
798                                        g_free, key_state_free);
799
800   return state;
801 }
802
803 static void
804 schema_state_free (gpointer data)
805 {
806   SchemaState *state = data;
807
808   g_free (state->path);
809   g_free (state->gettext_domain);
810   g_hash_table_unref (state->keys);
811 }
812
813 static void
814 schema_state_add_child (SchemaState  *state,
815                         const gchar  *name,
816                         const gchar  *schema,
817                         GError      **error)
818 {
819   gchar *childname;
820
821   if (!is_valid_keyname (name, error))
822     return;
823
824   childname = g_strconcat (name, "/", NULL);
825
826   if (g_hash_table_lookup (state->keys, childname))
827     {
828       g_set_error (error, G_MARKUP_ERROR,
829                    G_MARKUP_ERROR_INVALID_CONTENT,
830                    _("<child name='%s'> already specified"), name);
831       return;
832     }
833
834   g_hash_table_insert (state->keys, childname,
835                        key_state_new_child (schema));
836 }
837
838 static KeyState *
839 schema_state_add_key (SchemaState  *state,
840                       GHashTable   *enum_table,
841                       GHashTable   *flags_table,
842                       const gchar  *name,
843                       const gchar  *type_string,
844                       const gchar  *enum_type,
845                       const gchar  *flags_type,
846                       GError      **error)
847 {
848   SchemaState *node;
849   GString *strinfo;
850   KeyState *key;
851
852   if (state->list_of)
853     {
854       g_set_error_literal (error, G_MARKUP_ERROR,
855                            G_MARKUP_ERROR_INVALID_CONTENT,
856                            _("can not add keys to a 'list-of' schema"));
857       return NULL;
858     }
859
860   if (!is_valid_keyname (name, error))
861     return NULL;
862
863   if (g_hash_table_lookup (state->keys, name))
864     {
865       g_set_error (error, G_MARKUP_ERROR,
866                    G_MARKUP_ERROR_INVALID_CONTENT,
867                    _("<key name='%s'> already specified"), name);
868       return NULL;
869     }
870
871   for (node = state; node; node = node->extends)
872     if (node->extends)
873       {
874         KeyState *shadow;
875
876         shadow = g_hash_table_lookup (node->extends->keys, name);
877
878         /* in case of <key> <override> <key> make sure we report the
879          * location of the original <key>, not the <override>.
880          */
881         if (shadow && !shadow->is_override)
882           {
883             g_set_error (error, G_MARKUP_ERROR,
884                          G_MARKUP_ERROR_INVALID_CONTENT,
885                          _("<key name='%s'> shadows <key name='%s'> in "
886                            "<schema id='%s'>; use <override> to modify value"),
887                          name, name, node->extends_name);
888             return NULL;
889           }
890       }
891
892   if ((type_string != NULL) + (enum_type != NULL) + (flags_type != NULL) != 1)
893     {
894       g_set_error (error, G_MARKUP_ERROR,
895                    G_MARKUP_ERROR_MISSING_ATTRIBUTE,
896                    _("exactly one of 'type', 'enum' or 'flags' must "
897                      "be specified as an attribute to <key>"));
898       return NULL;
899     }
900
901   if (type_string == NULL) /* flags or enums was specified */
902     {
903       EnumState *enum_state;
904
905       if (enum_type)
906         enum_state = g_hash_table_lookup (enum_table, enum_type);
907       else
908         enum_state = g_hash_table_lookup (flags_table, flags_type);
909
910
911       if (enum_state == NULL)
912         {
913           g_set_error (error, G_MARKUP_ERROR,
914                        G_MARKUP_ERROR_INVALID_CONTENT,
915                        _("<%s id='%s'> not (yet) defined."),
916                        flags_type ? "flags"    : "enum",
917                        flags_type ? flags_type : enum_type);
918           return NULL;
919         }
920
921       type_string = flags_type ? "as" : "s";
922       strinfo = enum_state->strinfo;
923     }
924   else
925     {
926       if (!g_variant_type_string_is_valid (type_string))
927         {
928           g_set_error (error, G_MARKUP_ERROR,
929                        G_MARKUP_ERROR_INVALID_CONTENT,
930                        _("invalid GVariant type string '%s'"), type_string);
931           return NULL;
932         }
933
934       strinfo = NULL;
935     }
936
937   key = key_state_new (type_string, state->gettext_domain,
938                        enum_type != NULL, flags_type != NULL, strinfo);
939   g_hash_table_insert (state->keys, g_strdup (name), key);
940
941   return key;
942 }
943
944 static void
945 schema_state_add_override (SchemaState  *state,
946                            KeyState    **key_state,
947                            GString     **string,
948                            const gchar  *key,
949                            const gchar  *l10n,
950                            const gchar  *context,
951                            GError      **error)
952 {
953   SchemaState *parent;
954   KeyState *original;
955
956   if (state->extends == NULL)
957     {
958       g_set_error_literal (error, G_MARKUP_ERROR,
959                            G_MARKUP_ERROR_INVALID_CONTENT,
960                            _("<override> given but schema isn't "
961                              "extending anything"));
962       return;
963     }
964
965   for (parent = state->extends; parent; parent = parent->extends)
966     if ((original = g_hash_table_lookup (parent->keys, key)))
967       break;
968
969   if (original == NULL)
970     {
971       g_set_error (error, G_MARKUP_ERROR,
972                    G_MARKUP_ERROR_INVALID_CONTENT,
973                    _("no <key name='%s'> to override"), key);
974       return;
975     }
976
977   if (g_hash_table_lookup (state->keys, key))
978     {
979       g_set_error (error, G_MARKUP_ERROR,
980                    G_MARKUP_ERROR_INVALID_CONTENT,
981                    _("<override name='%s'> already specified"), key);
982       return;
983     }
984
985   *key_state = key_state_override (original, state->gettext_domain);
986   *string = key_state_start_default (*key_state, l10n, context, error);
987   g_hash_table_insert (state->keys, g_strdup (key), *key_state);
988 }
989
990 static void
991 override_state_end (KeyState **key_state,
992                     GString  **string,
993                     GError   **error)
994 {
995   key_state_end_default (*key_state, string, error);
996   *key_state = NULL;
997 }
998
999 /* Handling of toplevel state {{{1 */
1000 typedef struct
1001 {
1002   GHashTable  *schema_table;            /* string -> SchemaState */
1003   GHashTable  *flags_table;             /* string -> EnumState */
1004   GHashTable  *enum_table;              /* string -> EnumState */
1005
1006   GSList      *this_file_schemas;       /* strings: <schema>s in this file */
1007   GSList      *this_file_flagss;        /* strings: <flags>s in this file */
1008   GSList      *this_file_enums;         /* strings: <enum>s in this file */
1009
1010   gchar       *schemalist_domain;       /* the <schemalist> gettext domain */
1011
1012   SchemaState *schema_state;            /* non-NULL when inside <schema> */
1013   KeyState    *key_state;               /* non-NULL when inside <key> */
1014   EnumState   *enum_state;              /* non-NULL when inside <enum> */
1015
1016   GString     *string;                  /* non-NULL when accepting text */
1017 } ParseState;
1018
1019 static gboolean
1020 is_subclass (const gchar *class_name,
1021              const gchar *possible_parent,
1022              GHashTable  *schema_table)
1023 {
1024   SchemaState *class;
1025
1026   if (strcmp (class_name, possible_parent) == 0)
1027     return TRUE;
1028
1029   class = g_hash_table_lookup (schema_table, class_name);
1030   g_assert (class != NULL);
1031
1032   return class->extends_name &&
1033          is_subclass (class->extends_name, possible_parent, schema_table);
1034 }
1035
1036 static void
1037 parse_state_start_schema (ParseState  *state,
1038                           const gchar  *id,
1039                           const gchar  *path,
1040                           const gchar  *gettext_domain,
1041                           const gchar  *extends_name,
1042                           const gchar  *list_of,
1043                           GError      **error)
1044 {
1045   SchemaState *extends;
1046   gchar *my_id;
1047
1048   if (g_hash_table_lookup (state->schema_table, id))
1049     {
1050       g_set_error (error, G_MARKUP_ERROR,
1051                    G_MARKUP_ERROR_INVALID_CONTENT,
1052                    _("<schema id='%s'> already specified"), id);
1053       return;
1054     }
1055
1056   if (extends_name)
1057     {
1058       extends = g_hash_table_lookup (state->schema_table, extends_name);
1059
1060       if (extends == NULL)
1061         {
1062           g_set_error (error, G_MARKUP_ERROR,
1063                        G_MARKUP_ERROR_INVALID_CONTENT,
1064                        _("<schema id='%s'> extends not yet "
1065                          "existing schema '%s'"), id, extends_name);
1066           return;
1067         }
1068     }
1069   else
1070     extends = NULL;
1071
1072   if (list_of)
1073     {
1074       SchemaState *tmp;
1075
1076       if (!(tmp = g_hash_table_lookup (state->schema_table, list_of)))
1077         {
1078           g_set_error (error, G_MARKUP_ERROR,
1079                        G_MARKUP_ERROR_INVALID_CONTENT,
1080                        _("<schema id='%s'> is list of not yet "
1081                          "existing schema '%s'"), id, list_of);
1082           return;
1083         }
1084
1085       if (tmp->path)
1086         {
1087           g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT,
1088                        _("Can not be a list of a schema with a path"));
1089           return;
1090         }
1091     }
1092
1093   if (extends)
1094     {
1095       if (extends->path)
1096         {
1097           g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT,
1098                        _("Can not extend a schema with a path"));
1099           return;
1100         }
1101
1102       if (list_of)
1103         {
1104           if (extends->list_of == NULL)
1105             {
1106               g_set_error (error, G_MARKUP_ERROR,
1107                            G_MARKUP_ERROR_INVALID_CONTENT,
1108                            _("<schema id='%s'> is a list, extending "
1109                              "<schema id='%s'> which is not a list"),
1110                            id, extends_name);
1111               return;
1112             }
1113
1114           if (!is_subclass (list_of, extends->list_of, state->schema_table))
1115             {
1116               g_set_error (error, G_MARKUP_ERROR,
1117                            G_MARKUP_ERROR_INVALID_CONTENT,
1118                            _("<schema id='%s' list-of='%s'> extends <schema "
1119                              "id='%s' list-of='%s'> but '%s' does not "
1120                              "extend '%s'"), id, list_of, extends_name,
1121                            extends->list_of, list_of, extends->list_of);
1122               return;
1123             }
1124         }
1125       else
1126         /* by default we are a list of the same thing that the schema
1127          * we are extending is a list of (which might be nothing)
1128          */
1129         list_of = extends->list_of;
1130     }
1131
1132   if (path && !(g_str_has_prefix (path, "/") && g_str_has_suffix (path, "/")))
1133     {
1134       g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT,
1135                    _("a path, if given, must begin and end with a slash"));
1136       return;
1137     }
1138
1139   if (path && list_of && !g_str_has_suffix (path, ":/"))
1140     {
1141       g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT,
1142                    _("the path of a list must end with ':/'"));
1143       return;
1144     }
1145
1146   state->schema_state = schema_state_new (path, gettext_domain,
1147                                           extends, extends_name, list_of);
1148
1149   my_id = g_strdup (id);
1150   state->this_file_schemas = g_slist_prepend (state->this_file_schemas, my_id);
1151   g_hash_table_insert (state->schema_table, my_id, state->schema_state);
1152 }
1153
1154 static void
1155 parse_state_start_enum (ParseState   *state,
1156                         const gchar  *id,
1157                         gboolean      is_flags,
1158                         GError      **error)
1159 {
1160   GSList **list = is_flags ? &state->this_file_flagss : &state->this_file_enums;
1161   GHashTable *table = is_flags ? state->flags_table : state->enum_table;
1162   gchar *my_id;
1163
1164   if (g_hash_table_lookup (table, id))
1165     {
1166       g_set_error (error, G_MARKUP_ERROR,
1167                    G_MARKUP_ERROR_INVALID_CONTENT,
1168                    _("<%s id='%s'> already specified"),
1169                    is_flags ? "flags" : "enum", id);
1170       return;
1171     }
1172
1173   state->enum_state = enum_state_new (is_flags);
1174
1175   my_id = g_strdup (id);
1176   *list = g_slist_prepend (*list, my_id);
1177   g_hash_table_insert (table, my_id, state->enum_state);
1178 }
1179
1180 /* GMarkup Parser Functions {{{1 */
1181
1182 /* Start element {{{2 */
1183 static void
1184 start_element (GMarkupParseContext  *context,
1185                const gchar          *element_name,
1186                const gchar         **attribute_names,
1187                const gchar         **attribute_values,
1188                gpointer              user_data,
1189                GError              **error)
1190 {
1191   ParseState *state = user_data;
1192   const GSList *element_stack;
1193   const gchar *container;
1194
1195   element_stack = g_markup_parse_context_get_element_stack (context);
1196   container = element_stack->next ? element_stack->next->data : NULL;
1197
1198 #define COLLECT(first, ...) \
1199   g_markup_collect_attributes (element_name,                                 \
1200                                attribute_names, attribute_values, error,     \
1201                                first, __VA_ARGS__, G_MARKUP_COLLECT_INVALID)
1202 #define OPTIONAL   G_MARKUP_COLLECT_OPTIONAL
1203 #define STRDUP     G_MARKUP_COLLECT_STRDUP
1204 #define STRING     G_MARKUP_COLLECT_STRING
1205 #define NO_ATTRS()  COLLECT (G_MARKUP_COLLECT_INVALID, NULL)
1206
1207   /* Toplevel items {{{3 */
1208   if (container == NULL)
1209     {
1210       if (strcmp (element_name, "schemalist") == 0)
1211         {
1212           COLLECT (OPTIONAL | STRDUP,
1213                    "gettext-domain",
1214                    &state->schemalist_domain);
1215           return;
1216         }
1217     }
1218
1219
1220   /* children of <schemalist> {{{3 */
1221   else if (strcmp (container, "schemalist") == 0)
1222     {
1223       if (strcmp (element_name, "schema") == 0)
1224         {
1225           const gchar *id, *path, *gettext_domain, *extends, *list_of;
1226           if (COLLECT (STRING, "id", &id,
1227                        OPTIONAL | STRING, "path", &path,
1228                        OPTIONAL | STRING, "gettext-domain", &gettext_domain,
1229                        OPTIONAL | STRING, "extends", &extends,
1230                        OPTIONAL | STRING, "list-of", &list_of))
1231             parse_state_start_schema (state, id, path, gettext_domain,
1232                                       extends, list_of, error);
1233           return;
1234         }
1235
1236       else if (strcmp (element_name, "enum") == 0)
1237         {
1238           const gchar *id;
1239           if (COLLECT (STRING, "id", &id))
1240             parse_state_start_enum (state, id, FALSE, error);
1241           return;
1242         }
1243
1244       else if (strcmp (element_name, "flags") == 0)
1245         {
1246           const gchar *id;
1247           if (COLLECT (STRING, "id", &id))
1248             parse_state_start_enum (state, id, TRUE, error);
1249           return;
1250         }
1251     }
1252
1253
1254   /* children of <schema> {{{3 */
1255   else if (strcmp (container, "schema") == 0)
1256     {
1257       if (strcmp (element_name, "key") == 0)
1258         {
1259           const gchar *name, *type_string, *enum_type, *flags_type;
1260
1261           if (COLLECT (STRING,            "name",  &name,
1262                        OPTIONAL | STRING, "type",  &type_string,
1263                        OPTIONAL | STRING, "enum",  &enum_type,
1264                        OPTIONAL | STRING, "flags", &flags_type))
1265
1266             state->key_state = schema_state_add_key (state->schema_state,
1267                                                      state->enum_table,
1268                                                      state->flags_table,
1269                                                      name, type_string,
1270                                                      enum_type, flags_type,
1271                                                      error);
1272           return;
1273         }
1274       else if (strcmp (element_name, "child") == 0)
1275         {
1276           const gchar *name, *schema;
1277
1278           if (COLLECT (STRING, "name", &name, STRING, "schema", &schema))
1279             schema_state_add_child (state->schema_state,
1280                                     name, schema, error);
1281           return;
1282         }
1283       else if (strcmp (element_name, "override") == 0)
1284         {
1285           const gchar *name, *l10n, *context;
1286
1287           if (COLLECT (STRING,            "name",    &name,
1288                        OPTIONAL | STRING, "l10n",    &l10n,
1289                        OPTIONAL | STRING, "context", &context))
1290             schema_state_add_override (state->schema_state,
1291                                        &state->key_state, &state->string,
1292                                        name, l10n, context, error);
1293           return;
1294         }
1295     }
1296
1297   /* children of <key> {{{3 */
1298   else if (strcmp (container, "key") == 0)
1299     {
1300       if (strcmp (element_name, "default") == 0)
1301         {
1302           const gchar *l10n, *context;
1303           if (COLLECT (STRING | OPTIONAL, "l10n",    &l10n,
1304                        STRING | OPTIONAL, "context", &context))
1305             state->string = key_state_start_default (state->key_state,
1306                                                      l10n, context, error);
1307           return;
1308         }
1309
1310       else if (strcmp (element_name, "summary") == 0 ||
1311                strcmp (element_name, "description") == 0)
1312         {
1313           if (NO_ATTRS ())
1314             state->string = g_string_new (NULL);
1315           return;
1316         }
1317
1318       else if (strcmp (element_name, "range") == 0)
1319         {
1320           const gchar *min, *max;
1321           if (COLLECT (STRING, "min", &min, STRING, "max", &max))
1322             key_state_set_range (state->key_state, min, max, error);
1323           return;
1324         }
1325
1326       else if (strcmp (element_name, "choices") == 0)
1327         {
1328           if (NO_ATTRS ())
1329             key_state_start_choices (state->key_state, error);
1330           return;
1331         }
1332
1333       else if (strcmp (element_name, "aliases") == 0)
1334         {
1335           if (NO_ATTRS ())
1336             key_state_start_aliases (state->key_state, error);
1337           return;
1338         }
1339     }
1340
1341
1342   /* children of <choices> {{{3 */
1343   else if (strcmp (container, "choices") == 0)
1344     {
1345       if (strcmp (element_name, "choice") == 0)
1346         {
1347           const gchar *value;
1348           if (COLLECT (STRING, "value", &value))
1349             key_state_add_choice (state->key_state, value, error);
1350           return;
1351         }
1352     }
1353
1354
1355   /* children of <aliases> {{{3 */
1356   else if (strcmp (container, "aliases") == 0)
1357     {
1358       if (strcmp (element_name, "alias") == 0)
1359         {
1360           const gchar *value, *target;
1361           if (COLLECT (STRING, "value", &value, STRING, "target", &target))
1362             key_state_add_alias (state->key_state, value, target, error);
1363           return;
1364         }
1365     }
1366
1367
1368   /* children of <enum> {{{3 */
1369   else if (strcmp (container, "enum") == 0 ||
1370            strcmp (container, "flags") == 0)
1371     {
1372       if (strcmp (element_name, "value") == 0)
1373         {
1374           const gchar *nick, *valuestr;
1375           if (COLLECT (STRING, "nick", &nick,
1376                        STRING, "value", &valuestr))
1377             enum_state_add_value (state->enum_state, nick, valuestr, error);
1378           return;
1379         }
1380     }
1381   /* 3}}} */
1382
1383   if (container)
1384     g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_UNKNOWN_ELEMENT,
1385                  _("Element <%s> not allowed inside <%s>"),
1386                  element_name, container);
1387   else
1388     g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_UNKNOWN_ELEMENT,
1389                  _("Element <%s> not allowed at toplevel"), element_name);
1390 }
1391 /* 2}}} */
1392 /* End element {{{2 */
1393
1394 static void
1395 key_state_end (KeyState **state_ptr,
1396                GError   **error)
1397 {
1398   KeyState *state;
1399
1400   state = *state_ptr;
1401   *state_ptr = NULL;
1402
1403   if (state->default_value == NULL)
1404     {
1405       g_set_error_literal (error,
1406                            G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT,
1407                            "element <default> is required in <key>");
1408       return;
1409     }
1410 }
1411
1412 static void
1413 schema_state_end (SchemaState **state_ptr,
1414                   GError      **error)
1415 {
1416   SchemaState *state;
1417
1418   state = *state_ptr;
1419   *state_ptr = NULL;
1420 }
1421
1422 static void
1423 end_element (GMarkupParseContext  *context,
1424              const gchar          *element_name,
1425              gpointer              user_data,
1426              GError              **error)
1427 {
1428   ParseState *state = user_data;
1429
1430   if (strcmp (element_name, "schemalist") == 0)
1431     {
1432       g_free (state->schemalist_domain);
1433       state->schemalist_domain = NULL;
1434     }
1435
1436   else if (strcmp (element_name, "enum") == 0 ||
1437            strcmp (element_name, "flags") == 0)
1438     enum_state_end (&state->enum_state, error);
1439
1440   else if (strcmp (element_name, "schema") == 0)
1441     schema_state_end (&state->schema_state, error);
1442
1443   else if (strcmp (element_name, "override") == 0)
1444     override_state_end (&state->key_state, &state->string, error);
1445
1446   else if (strcmp (element_name, "key") == 0)
1447     key_state_end (&state->key_state, error);
1448
1449   else if (strcmp (element_name, "default") == 0)
1450     key_state_end_default (state->key_state, &state->string, error);
1451
1452   else if (strcmp (element_name, "choices") == 0)
1453     key_state_end_choices (state->key_state, error);
1454
1455   else if (strcmp (element_name, "aliases") == 0)
1456     key_state_end_aliases (state->key_state, error);
1457
1458   if (state->string)
1459     {
1460       g_string_free (state->string, TRUE);
1461       state->string = NULL;
1462     }
1463 }
1464 /* Text {{{2 */
1465 static void
1466 text (GMarkupParseContext  *context,
1467       const gchar          *text,
1468       gsize                 text_len,
1469       gpointer              user_data,
1470       GError              **error)
1471 {
1472   ParseState *state = user_data;
1473   gsize i;
1474
1475   for (i = 0; i < text_len; i++)
1476     if (!g_ascii_isspace (text[i]))
1477       {
1478         if (state->string)
1479           g_string_append_len (state->string, text, text_len);
1480
1481         else
1482           g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT,
1483                        _("text may not appear inside <%s>"),
1484                        g_markup_parse_context_get_element (context));
1485
1486         break;
1487       }
1488 }
1489
1490 /* Write to GVDB {{{1 */
1491 typedef struct
1492 {
1493   GHashTable *table;
1494   GvdbItem *root;
1495 } GvdbPair;
1496
1497 static void
1498 gvdb_pair_init (GvdbPair *pair)
1499 {
1500   pair->table = gvdb_hash_table_new (NULL, NULL);
1501   pair->root = gvdb_hash_table_insert (pair->table, "");
1502 }
1503
1504 typedef struct
1505 {
1506   GvdbPair pair;
1507   gboolean l10n;
1508 } OutputSchemaData;
1509
1510 static void
1511 output_key (gpointer key,
1512             gpointer value,
1513             gpointer user_data)
1514 {
1515   OutputSchemaData *data;
1516   const gchar *name;
1517   KeyState *state;
1518   GvdbItem *item;
1519
1520   name = key;
1521   state = value;
1522   data = user_data;
1523
1524   item = gvdb_hash_table_insert (data->pair.table, name);
1525   gvdb_item_set_parent (item, data->pair.root);
1526   gvdb_item_set_value (item, key_state_serialise (state));
1527
1528   if (state->l10n)
1529     data->l10n = TRUE;
1530 }
1531
1532 static void
1533 output_schema (gpointer key,
1534                gpointer value,
1535                gpointer user_data)
1536 {
1537   OutputSchemaData data;
1538   GvdbPair *root_pair;
1539   SchemaState *state;
1540   const gchar *id;
1541   GvdbItem *item;
1542
1543   id = key;
1544   state = value;
1545   root_pair = user_data;
1546
1547   gvdb_pair_init (&data.pair);
1548   data.l10n = FALSE;
1549
1550   item = gvdb_hash_table_insert (root_pair->table, id);
1551   gvdb_item_set_parent (item, root_pair->root);
1552   gvdb_item_set_hash_table (item, data.pair.table);
1553
1554   g_hash_table_foreach (state->keys, output_key, &data);
1555
1556   if (state->path)
1557     gvdb_hash_table_insert_string (data.pair.table, ".path", state->path);
1558
1559   if (state->extends_name)
1560     gvdb_hash_table_insert_string (data.pair.table, ".extends",
1561                                    state->extends_name);
1562
1563   if (state->list_of)
1564     gvdb_hash_table_insert_string (data.pair.table, ".list-of",
1565                                    state->extends_name);
1566
1567   if (data.l10n)
1568     gvdb_hash_table_insert_string (data.pair.table,
1569                                    ".gettext-domain",
1570                                    state->gettext_domain);
1571 }
1572
1573 static gboolean
1574 write_to_file (GHashTable   *schema_table,
1575                const gchar  *filename,
1576                GError      **error)
1577 {
1578   gboolean success;
1579   GvdbPair pair;
1580
1581   gvdb_pair_init (&pair);
1582
1583   g_hash_table_foreach (schema_table, output_schema, &pair);
1584
1585   success = gvdb_table_write_contents (pair.table, filename,
1586                                        G_BYTE_ORDER != G_LITTLE_ENDIAN,
1587                                        error);
1588   g_hash_table_unref (pair.table);
1589
1590   return success;
1591 }
1592
1593 /* Parser driver {{{1 */
1594 static GHashTable *
1595 parse_gschema_files (gchar    **files,
1596                      gboolean   strict)
1597 {
1598   GMarkupParser parser = { start_element, end_element, text };
1599   ParseState state = { 0, };
1600   const gchar *filename;
1601   GError *error = NULL;
1602
1603   state.enum_table = g_hash_table_new_full (g_str_hash, g_str_equal,
1604                                             g_free, enum_state_free);
1605
1606   state.flags_table = g_hash_table_new_full (g_str_hash, g_str_equal,
1607                                              g_free, enum_state_free);
1608
1609   state.schema_table = g_hash_table_new_full (g_str_hash, g_str_equal,
1610                                               g_free, schema_state_free);
1611
1612   while ((filename = *files++) != NULL)
1613     {
1614       GMarkupParseContext *context;
1615       gchar *contents;
1616       gsize size;
1617
1618       if (!g_file_get_contents (filename, &contents, &size, &error))
1619         {
1620           fprintf (stderr, "%s\n", error->message);
1621           g_clear_error (&error);
1622           continue;
1623         }
1624
1625       context = g_markup_parse_context_new (&parser,
1626                                             G_MARKUP_PREFIX_ERROR_POSITION,
1627                                             &state, NULL);
1628
1629
1630       if (!g_markup_parse_context_parse (context, contents, size, &error) ||
1631           !g_markup_parse_context_end_parse (context, &error))
1632         {
1633           GSList *item;
1634
1635           /* back out any changes from this file */
1636           for (item = state.this_file_schemas; item; item = item->next)
1637             g_hash_table_remove (state.schema_table, item->data);
1638
1639           for (item = state.this_file_flagss; item; item = item->next)
1640             g_hash_table_remove (state.flags_table, item->data);
1641
1642           for (item = state.this_file_enums; item; item = item->next)
1643             g_hash_table_remove (state.enum_table, item->data);
1644
1645           /* let them know */
1646           fprintf (stderr, "%s: %s.  ", filename, error->message);
1647           g_clear_error (&error);
1648
1649           if (strict)
1650             {
1651               /* Translators: Do not translate "--strict". */
1652               fprintf (stderr, _("--strict was specified; exiting.\n"));
1653               g_hash_table_unref (state.schema_table);
1654               g_hash_table_unref (state.flags_table);
1655               g_hash_table_unref (state.enum_table);
1656
1657               return NULL;
1658             }
1659           else
1660             fprintf (stderr, _("This entire file has been ignored.\n"));
1661         }
1662
1663       /* cleanup */
1664       g_markup_parse_context_free (context);
1665       g_slist_free (state.this_file_schemas);
1666       g_slist_free (state.this_file_flagss);
1667       g_slist_free (state.this_file_enums);
1668       state.this_file_schemas = NULL;
1669       state.this_file_flagss = NULL;
1670       state.this_file_enums = NULL;
1671     }
1672
1673   g_hash_table_unref (state.flags_table);
1674   g_hash_table_unref (state.enum_table);
1675
1676   return state.schema_table;
1677 }
1678
1679 static gint
1680 compare_strings (gconstpointer a,
1681                  gconstpointer b)
1682 {
1683   gchar *one = *(gchar **) a;
1684   gchar *two = *(gchar **) b;
1685   gint cmp;
1686
1687   cmp = g_str_has_suffix (two, ".enums.xml") -
1688         g_str_has_suffix (one, ".enums.xml");
1689
1690   if (!cmp)
1691     cmp = strcmp (one, two);
1692
1693   return cmp;
1694 }
1695
1696 static gboolean
1697 set_overrides (GHashTable  *schema_table,
1698                gchar      **files,
1699                gboolean     strict)
1700 {
1701   const gchar *filename;
1702   GError *error = NULL;
1703
1704   while ((filename = *files++))
1705     {
1706       GKeyFile *key_file;
1707       gchar **groups;
1708       gint i;
1709
1710       key_file = g_key_file_new ();
1711       if (!g_key_file_load_from_file (key_file, filename, 0, &error))
1712         {
1713           fprintf (stderr, "%s: %s.  ", filename, error->message);
1714           g_key_file_free (key_file);
1715           g_clear_error (&error);
1716
1717           if (!strict)
1718             {
1719               fprintf (stderr, _("Ignoring this file.\n"));
1720               continue;
1721             }
1722
1723           fprintf (stderr, _("--strict was specified; exiting.\n"));
1724           return FALSE;
1725         }
1726
1727       groups = g_key_file_get_groups (key_file, NULL);
1728
1729       for (i = 0; groups[i]; i++)
1730         {
1731           const gchar *group = groups[i];
1732           SchemaState *schema;
1733           gchar **keys;
1734           gint j;
1735
1736           schema = g_hash_table_lookup (schema_table, group);
1737
1738           if (schema == NULL)
1739             /* Having the schema not be installed is expected to be a
1740              * common case.  Don't even emit an error message about
1741              * that.
1742              */
1743             continue;
1744
1745           keys = g_key_file_get_keys (key_file, group, NULL, NULL);
1746           g_assert (keys != NULL);
1747
1748           for (j = 0; keys[j]; j++)
1749             {
1750               const gchar *key = keys[j];
1751               KeyState *state;
1752               GVariant *value;
1753               gchar *string;
1754
1755               state = g_hash_table_lookup (schema->keys, key);
1756
1757               if (state == NULL)
1758                 {
1759                   fprintf (stderr, _("No such key `%s' in schema `%s' as "
1760                                      "specified in override file `%s'"),
1761                            key, group, filename);
1762
1763                   if (!strict)
1764                     {
1765                       fprintf (stderr, _("; ignoring override for this key.\n"));
1766                       continue;
1767                     }
1768
1769                   fprintf (stderr, _(" and --strict was specified; exiting.\n"));
1770                   g_key_file_free (key_file);
1771                   g_strfreev (groups);
1772                   g_strfreev (keys);
1773
1774                   return FALSE;
1775                 }
1776
1777               string = g_key_file_get_value (key_file, group, key, NULL);
1778               g_assert (string != NULL);
1779
1780               value = g_variant_parse (state->type, string,
1781                                        NULL, NULL, &error);
1782
1783               if (value == NULL)
1784                 {
1785                   fprintf (stderr, _("error parsing key `%s' in schema `%s' "
1786                                      "as specified in override file `%s': "
1787                                      "%s.  "),
1788                            key, group, filename, error->message);
1789
1790                   g_clear_error (&error);
1791                   g_free (string);
1792
1793                   if (!strict)
1794                     {
1795                       fprintf (stderr, _("Ignoring override for this key.\n"));
1796                       continue;
1797                     }
1798
1799                   fprintf (stderr, _("--strict was specified; exiting.\n"));
1800                   g_key_file_free (key_file);
1801                   g_strfreev (groups);
1802                   g_strfreev (keys);
1803
1804                   return FALSE;
1805                 }
1806
1807               if (state->minimum)
1808                 {
1809                   if (g_variant_compare (value, state->minimum) < 0 ||
1810                       g_variant_compare (value, state->maximum) > 0)
1811                     {
1812                       fprintf (stderr,
1813                                _("override for key `%s' in schema `%s' in "
1814                                  "override file `%s' is out of the range "
1815                                  "given in the schema"),
1816                                key, group, filename);
1817
1818                       g_variant_unref (value);
1819                       g_free (string);
1820
1821                       if (!strict)
1822                         {
1823                           fprintf (stderr, _("; ignoring override for this key.\n"));
1824                           continue;
1825                         }
1826
1827                       fprintf (stderr, _(" and --strict was specified; exiting.\n"));
1828                       g_key_file_free (key_file);
1829                       g_strfreev (groups);
1830                       g_strfreev (keys);
1831
1832                       return FALSE;
1833                     }
1834                 }
1835
1836               else if (state->strinfo->len)
1837                 {
1838                   if (!is_valid_choices (value, state->strinfo))
1839                     {
1840                       fprintf (stderr,
1841                                _("override for key `%s' in schema `%s' in "
1842                                  "override file `%s' is not in the list "
1843                                  "of valid choices"),
1844                                key, group, filename);
1845
1846                       g_variant_unref (value);
1847                       g_free (string);
1848
1849                       if (!strict)
1850                         {
1851                           fprintf (stderr, _("; ignoring override for this key.\n"));
1852                           continue;
1853                         }
1854
1855                       fprintf (stderr, _(" and --strict was specified; exiting.\n"));
1856                       g_key_file_free (key_file);
1857                       g_strfreev (groups);
1858                       g_strfreev (keys);
1859
1860                       return FALSE;
1861                     }
1862                 }
1863
1864               g_variant_unref (state->default_value);
1865               state->default_value = value;
1866               g_free (string);
1867             }
1868
1869           g_strfreev (keys);
1870         }
1871
1872       g_strfreev (groups);
1873     }
1874
1875   return TRUE;
1876 }
1877
1878 int
1879 main (int argc, char **argv)
1880 {
1881   GError *error;
1882   GHashTable *table;
1883   GDir *dir;
1884   const gchar *file;
1885   gchar *srcdir;
1886   gchar *targetdir = NULL;
1887   gchar *target;
1888   gboolean uninstall = FALSE;
1889   gboolean dry_run = FALSE;
1890   gboolean strict = FALSE;
1891   gchar **schema_files = NULL;
1892   gchar **override_files = NULL;
1893   GOptionContext *context;
1894   GOptionEntry entries[] = {
1895     { "targetdir", 0, 0, G_OPTION_ARG_FILENAME, &targetdir, N_("where to store the gschemas.compiled file"), N_("DIRECTORY") },
1896     { "strict", 0, 0, G_OPTION_ARG_NONE, &strict, N_("Abort on any errors in schemas"), NULL },
1897     { "dry-run", 0, 0, G_OPTION_ARG_NONE, &dry_run, N_("Do not write the gschema.compiled file"), NULL },
1898     { "uninstall", 0, 0, G_OPTION_ARG_NONE, &uninstall, N_("This option will be removed soon.") },
1899     { "allow-any-name", 0, 0, G_OPTION_ARG_NONE, &allow_any_name, N_("Do not enforce key name restrictions") },
1900
1901     /* These options are only for use in the gschema-compile tests */
1902     { "schema-file", 0, G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_FILENAME_ARRAY, &schema_files, NULL, NULL },
1903     { NULL }
1904   };
1905
1906   setlocale (LC_ALL, "");
1907
1908   context = g_option_context_new (N_("DIRECTORY"));
1909   g_option_context_set_translation_domain (context, GETTEXT_PACKAGE);
1910   g_option_context_set_summary (context,
1911     N_("Compile all GSettings schema files into a schema cache.\n"
1912        "Schema files are required to have the extension .gschema.xml,\n"
1913        "and the cache file is called gschemas.compiled."));
1914   g_option_context_add_main_entries (context, entries, GETTEXT_PACKAGE);
1915
1916   error = NULL;
1917   if (!g_option_context_parse (context, &argc, &argv, &error))
1918     {
1919       fprintf (stderr, "%s\n", error->message);
1920       return 1;
1921     }
1922
1923   g_option_context_free (context);
1924
1925   if (!schema_files && argc != 2)
1926     {
1927       fprintf (stderr, _("You should give exactly one directory name\n"));
1928       return 1;
1929     }
1930
1931   srcdir = argv[1];
1932
1933   if (targetdir == NULL)
1934     targetdir = srcdir;
1935
1936   target = g_build_filename (targetdir, "gschemas.compiled", NULL);
1937
1938   if (!schema_files)
1939     {
1940       GPtrArray *overrides;
1941       GPtrArray *files;
1942
1943       files = g_ptr_array_new ();
1944       overrides = g_ptr_array_new ();
1945
1946       dir = g_dir_open (srcdir, 0, &error);
1947       if (dir == NULL)
1948         {
1949           fprintf (stderr, "%s\n", error->message);
1950           return 1;
1951         }
1952
1953       while ((file = g_dir_read_name (dir)) != NULL)
1954         {
1955           if (g_str_has_suffix (file, ".gschema.xml") ||
1956               g_str_has_suffix (file, ".enums.xml"))
1957             g_ptr_array_add (files, g_build_filename (srcdir, file, NULL));
1958
1959           else if (g_str_has_suffix (file, ".gschema.override"))
1960             g_ptr_array_add (overrides,
1961                              g_build_filename (srcdir, file, NULL));
1962         }
1963
1964       if (files->len == 0)
1965         {
1966           fprintf (stderr, _("No schema files found: "));
1967
1968           if (g_unlink (target))
1969             fprintf (stderr, _("doing nothing.\n"));
1970
1971           else
1972             fprintf (stderr, _("removed existing output file.\n"));
1973
1974           return 0;
1975         }
1976       g_ptr_array_sort (files, compare_strings);
1977       g_ptr_array_add (files, NULL);
1978
1979       g_ptr_array_sort (overrides, compare_strings);
1980       g_ptr_array_add (overrides, NULL);
1981
1982       schema_files = (char **) g_ptr_array_free (files, FALSE);
1983       override_files = (gchar **) g_ptr_array_free (overrides, FALSE);
1984     }
1985
1986   if ((table = parse_gschema_files (schema_files, strict)) == NULL)
1987     {
1988       g_free (target);
1989       return 1;
1990     }
1991
1992   if (override_files != NULL &&
1993       !set_overrides (table, override_files, strict))
1994     {
1995       g_free (target);
1996       return 1;
1997     }
1998
1999   if (!dry_run && !write_to_file (table, target, &error))
2000     {
2001       fprintf (stderr, "%s\n", error->message);
2002       g_free (target);
2003       return 1;
2004     }
2005
2006   g_free (target);
2007
2008   return 0;
2009 }
2010
2011 /* Epilogue {{{1 */
2012
2013 /* vim:set foldmethod=marker: */