schema compiler: Don't store zero-valued flags
[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
506   if (!state->is_flags && !state->is_enum && !state->has_choices)
507     g_set_error_literal (error, G_MARKUP_ERROR,
508                          G_MARKUP_ERROR_INVALID_CONTENT,
509                          "<aliases> can only be specified for keys with "
510                          "enumerated or flags types or after <choices>");
511 }
512
513 static void
514 key_state_add_alias (KeyState     *state,
515                      const gchar  *alias,
516                      const gchar  *target,
517                      GError      **error)
518 {
519   if (strinfo_builder_contains (state->strinfo, alias))
520     {
521       if (strinfo_is_string_valid ((guint32 *) state->strinfo->str,
522                                    state->strinfo->len / 4,
523                                    alias))
524         {
525           if (state->is_enum)
526             g_set_error (error, G_MARKUP_ERROR,
527                          G_MARKUP_ERROR_INVALID_CONTENT,
528                          "<alias value='%s'/> given when '%s' is already "
529                          "a member of the enumerated type", alias, alias);
530
531           else
532             g_set_error (error, G_MARKUP_ERROR,
533                          G_MARKUP_ERROR_INVALID_CONTENT,
534                          "<alias value='%s'/> given when "
535                          "<choice value='%s'/> was already given",
536                          alias, alias);
537         }
538
539       else
540         g_set_error (error, G_MARKUP_ERROR,
541                      G_MARKUP_ERROR_INVALID_CONTENT,
542                      "<alias value='%s'/> already specified", alias);
543
544       return;
545     }
546
547   if (!strinfo_builder_append_alias (state->strinfo, alias, target))
548     {
549       g_set_error (error, G_MARKUP_ERROR,
550                    G_MARKUP_ERROR_INVALID_CONTENT,
551                    "alias target '%s' is not in %s", target,
552                    state->is_enum ? "enumerated type" : "<choices>");
553       return;
554     }
555
556   state->has_aliases = TRUE;
557 }
558
559 static void
560 key_state_end_aliases (KeyState  *state,
561                        GError   **error)
562 {
563   if (!state->has_aliases)
564     {
565       g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT,
566                    "<aliases> must contain at least one <alias>");
567       return;
568     }
569 }
570
571 static gboolean
572 key_state_check (KeyState  *state,
573                  GError   **error)
574 {
575   if (state->checked)
576     return TRUE;
577
578   return state->checked = TRUE;
579 }
580
581 static GVariant *
582 key_state_serialise (KeyState *state)
583 {
584   if (state->serialised == NULL)
585     {
586       if (state->child_schema)
587         {
588           state->serialised = g_variant_new_string (state->child_schema);
589         }
590
591       else
592         {
593           GVariantBuilder builder;
594
595           g_assert (key_state_check (state, NULL));
596
597           g_variant_builder_init (&builder, G_VARIANT_TYPE_TUPLE);
598
599           /* default value */
600           g_variant_builder_add_value (&builder, state->default_value);
601
602           /* translation */
603           if (state->l10n)
604             {
605               if (state->l10n_context)
606                 {
607                   gint len;
608
609                   /* Contextified messages are supported by prepending
610                    * the context, followed by '\004' to the start of the
611                    * message string.  We do that here to save GSettings
612                    * the work later on.
613                    */
614                   len = strlen (state->l10n_context);
615                   state->l10n_context[len] = '\004';
616                   g_string_prepend_len (state->unparsed_default_value,
617                                         state->l10n_context, len + 1);
618                   g_free (state->l10n_context);
619                   state->l10n_context = NULL;
620                 }
621
622               g_variant_builder_add (&builder, "(y(y&s))", 'l', state->l10n,
623                                      state->unparsed_default_value->str);
624               g_string_free (state->unparsed_default_value, TRUE);
625               state->unparsed_default_value = NULL;
626             }
627
628           /* choice, aliases, enums */
629           if (state->strinfo->len)
630             {
631               GVariant *array;
632               guint32 *words;
633               gpointer data;
634               gsize size;
635               gint i;
636
637               data = state->strinfo->str;
638               size = state->strinfo->len;
639
640               words = data;
641               for (i = 0; i < size / sizeof (guint32); i++)
642                 words[i] = GUINT32_TO_LE (words[i]);
643
644               array = g_variant_new_from_data (G_VARIANT_TYPE ("au"),
645                                                data, size, TRUE,
646                                                g_free, data);
647
648               g_string_free (state->strinfo, FALSE);
649               state->strinfo = NULL;
650
651               g_variant_builder_add (&builder, "(y@au)",
652                                      state->is_flags ? 'f' :
653                                      state->is_enum ? 'e' : 'c',
654                                      array);
655             }
656
657           /* range */
658           if (state->minimum || state->maximum)
659             g_variant_builder_add (&builder, "(y(**))", 'r',
660                                    state->minimum, state->maximum);
661
662           state->serialised = g_variant_builder_end (&builder);
663         }
664
665       g_variant_ref_sink (state->serialised);
666     }
667
668   return g_variant_ref (state->serialised);
669 }
670
671 static void
672 key_state_free (gpointer data)
673 {
674   KeyState *state = data;
675
676   if (state->type)
677     g_variant_type_free (state->type);
678
679   g_free (state->l10n_context);
680
681   if (state->unparsed_default_value)
682     g_string_free (state->unparsed_default_value, TRUE);
683
684   if (state->default_value)
685     g_variant_unref (state->default_value);
686
687   if (state->strinfo)
688     g_string_free (state->strinfo, TRUE);
689
690   if (state->minimum)
691     g_variant_unref (state->minimum);
692
693   if (state->maximum)
694     g_variant_unref (state->maximum);
695
696   if (state->serialised)
697     g_variant_unref (state->serialised);
698
699   g_slice_free (KeyState, state);
700 }
701
702 /* Key name validity {{{1 */
703 static gboolean allow_any_name = FALSE;
704
705 static gboolean
706 is_valid_keyname (const gchar  *key,
707                   GError      **error)
708 {
709   gint i;
710
711   if (key[0] == '\0')
712     {
713       g_set_error_literal (error, G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT,
714                            _("empty names are not permitted"));
715       return FALSE;
716     }
717
718   if (allow_any_name)
719     return TRUE;
720
721   if (!g_ascii_islower (key[0]))
722     {
723       g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT,
724                    _("invalid name '%s': names must begin "
725                      "with a lowercase letter"), key);
726       return FALSE;
727     }
728
729   for (i = 1; key[i]; i++)
730     {
731       if (key[i] != '-' &&
732           !g_ascii_islower (key[i]) &&
733           !g_ascii_isdigit (key[i]))
734         {
735           g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT,
736                        _("invalid name '%s': invalid character '%c'; "
737                          "only lowercase letters, numbers and dash ('-') "
738                          "are permitted."), key, key[i]);
739           return FALSE;
740         }
741
742       if (key[i] == '-' && key[i + 1] == '-')
743         {
744           g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT,
745                        _("invalid name '%s': two successive dashes ('--') "
746                          "are not permitted."), key);
747           return FALSE;
748         }
749     }
750
751   if (key[i - 1] == '-')
752     {
753       g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT,
754                    _("invalid name '%s': the last character may not be a "
755                      "dash ('-')."), key);
756       return FALSE;
757     }
758
759   if (i > 32)
760     {
761       g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT,
762                    _("invalid name '%s': maximum length is 32"), key);
763       return FALSE;
764     }
765
766   return TRUE;
767 }
768
769 /* Handling of <schema> {{{1 */
770 typedef struct _SchemaState SchemaState;
771 struct _SchemaState
772 {
773   SchemaState *extends;
774
775   gchar       *path;
776   gchar       *gettext_domain;
777   gchar       *extends_name;
778   gchar       *list_of;
779
780   GHashTable  *keys;
781 };
782
783 static SchemaState *
784 schema_state_new (const gchar  *path,
785                   const gchar  *gettext_domain,
786                   SchemaState  *extends,
787                   const gchar  *extends_name,
788                   const gchar  *list_of)
789 {
790   SchemaState *state;
791
792   state = g_slice_new (SchemaState);
793   state->path = g_strdup (path);
794   state->gettext_domain = g_strdup (gettext_domain);
795   state->extends = extends;
796   state->extends_name = g_strdup (extends_name);
797   state->list_of = g_strdup (list_of);
798   state->keys = g_hash_table_new_full (g_str_hash, g_str_equal,
799                                        g_free, key_state_free);
800
801   return state;
802 }
803
804 static void
805 schema_state_free (gpointer data)
806 {
807   SchemaState *state = data;
808
809   g_free (state->path);
810   g_free (state->gettext_domain);
811   g_hash_table_unref (state->keys);
812 }
813
814 static void
815 schema_state_add_child (SchemaState  *state,
816                         const gchar  *name,
817                         const gchar  *schema,
818                         GError      **error)
819 {
820   gchar *childname;
821
822   if (!is_valid_keyname (name, error))
823     return;
824
825   childname = g_strconcat (name, "/", NULL);
826
827   if (g_hash_table_lookup (state->keys, childname))
828     {
829       g_set_error (error, G_MARKUP_ERROR,
830                    G_MARKUP_ERROR_INVALID_CONTENT,
831                    _("<child name='%s'> already specified"), name);
832       return;
833     }
834
835   g_hash_table_insert (state->keys, childname,
836                        key_state_new_child (schema));
837 }
838
839 static KeyState *
840 schema_state_add_key (SchemaState  *state,
841                       GHashTable   *enum_table,
842                       GHashTable   *flags_table,
843                       const gchar  *name,
844                       const gchar  *type_string,
845                       const gchar  *enum_type,
846                       const gchar  *flags_type,
847                       GError      **error)
848 {
849   SchemaState *node;
850   GString *strinfo;
851   KeyState *key;
852
853   if (state->list_of)
854     {
855       g_set_error_literal (error, G_MARKUP_ERROR,
856                            G_MARKUP_ERROR_INVALID_CONTENT,
857                            _("can not add keys to a 'list-of' schema"));
858       return NULL;
859     }
860
861   if (!is_valid_keyname (name, error))
862     return NULL;
863
864   if (g_hash_table_lookup (state->keys, name))
865     {
866       g_set_error (error, G_MARKUP_ERROR,
867                    G_MARKUP_ERROR_INVALID_CONTENT,
868                    _("<key name='%s'> already specified"), name);
869       return NULL;
870     }
871
872   for (node = state; node; node = node->extends)
873     if (node->extends)
874       {
875         KeyState *shadow;
876
877         shadow = g_hash_table_lookup (node->extends->keys, name);
878
879         /* in case of <key> <override> <key> make sure we report the
880          * location of the original <key>, not the <override>.
881          */
882         if (shadow && !shadow->is_override)
883           {
884             g_set_error (error, G_MARKUP_ERROR,
885                          G_MARKUP_ERROR_INVALID_CONTENT,
886                          _("<key name='%s'> shadows <key name='%s'> in "
887                            "<schema id='%s'>; use <override> to modify value"),
888                          name, name, node->extends_name);
889             return NULL;
890           }
891       }
892
893   if ((type_string != NULL) + (enum_type != NULL) + (flags_type != NULL) != 1)
894     {
895       g_set_error (error, G_MARKUP_ERROR,
896                    G_MARKUP_ERROR_MISSING_ATTRIBUTE,
897                    _("exactly one of 'type', 'enum' or 'flags' must "
898                      "be specified as an attribute to <key>"));
899       return NULL;
900     }
901
902   if (type_string == NULL) /* flags or enums was specified */
903     {
904       EnumState *enum_state;
905
906       if (enum_type)
907         enum_state = g_hash_table_lookup (enum_table, enum_type);
908       else
909         enum_state = g_hash_table_lookup (flags_table, flags_type);
910
911
912       if (enum_state == NULL)
913         {
914           g_set_error (error, G_MARKUP_ERROR,
915                        G_MARKUP_ERROR_INVALID_CONTENT,
916                        _("<%s id='%s'> not (yet) defined."),
917                        flags_type ? "flags"    : "enum",
918                        flags_type ? flags_type : enum_type);
919           return NULL;
920         }
921
922       type_string = flags_type ? "as" : "s";
923       strinfo = enum_state->strinfo;
924     }
925   else
926     {
927       if (!g_variant_type_string_is_valid (type_string))
928         {
929           g_set_error (error, G_MARKUP_ERROR,
930                        G_MARKUP_ERROR_INVALID_CONTENT,
931                        _("invalid GVariant type string '%s'"), type_string);
932           return NULL;
933         }
934
935       strinfo = NULL;
936     }
937
938   key = key_state_new (type_string, state->gettext_domain,
939                        enum_type != NULL, flags_type != NULL, strinfo);
940   g_hash_table_insert (state->keys, g_strdup (name), key);
941
942   return key;
943 }
944
945 static void
946 schema_state_add_override (SchemaState  *state,
947                            KeyState    **key_state,
948                            GString     **string,
949                            const gchar  *key,
950                            const gchar  *l10n,
951                            const gchar  *context,
952                            GError      **error)
953 {
954   SchemaState *parent;
955   KeyState *original;
956
957   if (state->extends == NULL)
958     {
959       g_set_error_literal (error, G_MARKUP_ERROR,
960                            G_MARKUP_ERROR_INVALID_CONTENT,
961                            _("<override> given but schema isn't "
962                              "extending anything"));
963       return;
964     }
965
966   for (parent = state->extends; parent; parent = parent->extends)
967     if ((original = g_hash_table_lookup (parent->keys, key)))
968       break;
969
970   if (original == NULL)
971     {
972       g_set_error (error, G_MARKUP_ERROR,
973                    G_MARKUP_ERROR_INVALID_CONTENT,
974                    _("no <key name='%s'> to override"), key);
975       return;
976     }
977
978   if (g_hash_table_lookup (state->keys, key))
979     {
980       g_set_error (error, G_MARKUP_ERROR,
981                    G_MARKUP_ERROR_INVALID_CONTENT,
982                    _("<override name='%s'> already specified"), key);
983       return;
984     }
985
986   *key_state = key_state_override (original, state->gettext_domain);
987   *string = key_state_start_default (*key_state, l10n, context, error);
988   g_hash_table_insert (state->keys, g_strdup (key), *key_state);
989 }
990
991 static void
992 override_state_end (KeyState **key_state,
993                     GString  **string,
994                     GError   **error)
995 {
996   key_state_end_default (*key_state, string, error);
997   *key_state = NULL;
998 }
999
1000 /* Handling of toplevel state {{{1 */
1001 typedef struct
1002 {
1003   GHashTable  *schema_table;            /* string -> SchemaState */
1004   GHashTable  *flags_table;             /* string -> EnumState */
1005   GHashTable  *enum_table;              /* string -> EnumState */
1006
1007   GSList      *this_file_schemas;       /* strings: <schema>s in this file */
1008   GSList      *this_file_flagss;        /* strings: <flags>s in this file */
1009   GSList      *this_file_enums;         /* strings: <enum>s in this file */
1010
1011   gchar       *schemalist_domain;       /* the <schemalist> gettext domain */
1012
1013   SchemaState *schema_state;            /* non-NULL when inside <schema> */
1014   KeyState    *key_state;               /* non-NULL when inside <key> */
1015   EnumState   *enum_state;              /* non-NULL when inside <enum> */
1016
1017   GString     *string;                  /* non-NULL when accepting text */
1018 } ParseState;
1019
1020 static gboolean
1021 is_subclass (const gchar *class_name,
1022              const gchar *possible_parent,
1023              GHashTable  *schema_table)
1024 {
1025   SchemaState *class;
1026
1027   if (strcmp (class_name, possible_parent) == 0)
1028     return TRUE;
1029
1030   class = g_hash_table_lookup (schema_table, class_name);
1031   g_assert (class != NULL);
1032
1033   return class->extends_name &&
1034          is_subclass (class->extends_name, possible_parent, schema_table);
1035 }
1036
1037 static void
1038 parse_state_start_schema (ParseState  *state,
1039                           const gchar  *id,
1040                           const gchar  *path,
1041                           const gchar  *gettext_domain,
1042                           const gchar  *extends_name,
1043                           const gchar  *list_of,
1044                           GError      **error)
1045 {
1046   SchemaState *extends;
1047   gchar *my_id;
1048
1049   if (g_hash_table_lookup (state->schema_table, id))
1050     {
1051       g_set_error (error, G_MARKUP_ERROR,
1052                    G_MARKUP_ERROR_INVALID_CONTENT,
1053                    _("<schema id='%s'> already specified"), id);
1054       return;
1055     }
1056
1057   if (extends_name)
1058     {
1059       extends = g_hash_table_lookup (state->schema_table, extends_name);
1060
1061       if (extends == NULL)
1062         {
1063           g_set_error (error, G_MARKUP_ERROR,
1064                        G_MARKUP_ERROR_INVALID_CONTENT,
1065                        _("<schema id='%s'> extends not yet "
1066                          "existing schema '%s'"), id, extends_name);
1067           return;
1068         }
1069     }
1070   else
1071     extends = NULL;
1072
1073   if (list_of)
1074     {
1075       SchemaState *tmp;
1076
1077       if (!(tmp = g_hash_table_lookup (state->schema_table, list_of)))
1078         {
1079           g_set_error (error, G_MARKUP_ERROR,
1080                        G_MARKUP_ERROR_INVALID_CONTENT,
1081                        _("<schema id='%s'> is list of not yet "
1082                          "existing schema '%s'"), id, list_of);
1083           return;
1084         }
1085
1086       if (tmp->path)
1087         {
1088           g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT,
1089                        _("Can not be a list of a schema with a path"));
1090           return;
1091         }
1092     }
1093
1094   if (extends)
1095     {
1096       if (extends->path)
1097         {
1098           g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT,
1099                        _("Can not extend a schema with a path"));
1100           return;
1101         }
1102
1103       if (list_of)
1104         {
1105           if (extends->list_of == NULL)
1106             {
1107               g_set_error (error, G_MARKUP_ERROR,
1108                            G_MARKUP_ERROR_INVALID_CONTENT,
1109                            _("<schema id='%s'> is a list, extending "
1110                              "<schema id='%s'> which is not a list"),
1111                            id, extends_name);
1112               return;
1113             }
1114
1115           if (!is_subclass (list_of, extends->list_of, state->schema_table))
1116             {
1117               g_set_error (error, G_MARKUP_ERROR,
1118                            G_MARKUP_ERROR_INVALID_CONTENT,
1119                            _("<schema id='%s' list-of='%s'> extends <schema "
1120                              "id='%s' list-of='%s'> but '%s' does not "
1121                              "extend '%s'"), id, list_of, extends_name,
1122                            extends->list_of, list_of, extends->list_of);
1123               return;
1124             }
1125         }
1126       else
1127         /* by default we are a list of the same thing that the schema
1128          * we are extending is a list of (which might be nothing)
1129          */
1130         list_of = extends->list_of;
1131     }
1132
1133   if (path && !(g_str_has_prefix (path, "/") && g_str_has_suffix (path, "/")))
1134     {
1135       g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT,
1136                    _("a path, if given, must begin and end with a slash"));
1137       return;
1138     }
1139
1140   if (path && list_of && !g_str_has_suffix (path, ":/"))
1141     {
1142       g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT,
1143                    _("the path of a list must end with ':/'"));
1144       return;
1145     }
1146
1147   state->schema_state = schema_state_new (path, gettext_domain,
1148                                           extends, extends_name, list_of);
1149
1150   my_id = g_strdup (id);
1151   state->this_file_schemas = g_slist_prepend (state->this_file_schemas, my_id);
1152   g_hash_table_insert (state->schema_table, my_id, state->schema_state);
1153 }
1154
1155 static void
1156 parse_state_start_enum (ParseState   *state,
1157                         const gchar  *id,
1158                         gboolean      is_flags,
1159                         GError      **error)
1160 {
1161   GSList **list = is_flags ? &state->this_file_flagss : &state->this_file_enums;
1162   GHashTable *table = is_flags ? state->flags_table : state->enum_table;
1163   gchar *my_id;
1164
1165   if (g_hash_table_lookup (table, id))
1166     {
1167       g_set_error (error, G_MARKUP_ERROR,
1168                    G_MARKUP_ERROR_INVALID_CONTENT,
1169                    _("<%s id='%s'> already specified"),
1170                    is_flags ? "flags" : "enum", id);
1171       return;
1172     }
1173
1174   state->enum_state = enum_state_new (is_flags);
1175
1176   my_id = g_strdup (id);
1177   *list = g_slist_prepend (*list, my_id);
1178   g_hash_table_insert (table, my_id, state->enum_state);
1179 }
1180
1181 /* GMarkup Parser Functions {{{1 */
1182
1183 /* Start element {{{2 */
1184 static void
1185 start_element (GMarkupParseContext  *context,
1186                const gchar          *element_name,
1187                const gchar         **attribute_names,
1188                const gchar         **attribute_values,
1189                gpointer              user_data,
1190                GError              **error)
1191 {
1192   ParseState *state = user_data;
1193   const GSList *element_stack;
1194   const gchar *container;
1195
1196   element_stack = g_markup_parse_context_get_element_stack (context);
1197   container = element_stack->next ? element_stack->next->data : NULL;
1198
1199 #define COLLECT(first, ...) \
1200   g_markup_collect_attributes (element_name,                                 \
1201                                attribute_names, attribute_values, error,     \
1202                                first, __VA_ARGS__, G_MARKUP_COLLECT_INVALID)
1203 #define OPTIONAL   G_MARKUP_COLLECT_OPTIONAL
1204 #define STRDUP     G_MARKUP_COLLECT_STRDUP
1205 #define STRING     G_MARKUP_COLLECT_STRING
1206 #define NO_ATTRS()  COLLECT (G_MARKUP_COLLECT_INVALID, NULL)
1207
1208   /* Toplevel items {{{3 */
1209   if (container == NULL)
1210     {
1211       if (strcmp (element_name, "schemalist") == 0)
1212         {
1213           COLLECT (OPTIONAL | STRDUP,
1214                    "gettext-domain",
1215                    &state->schemalist_domain);
1216           return;
1217         }
1218     }
1219
1220
1221   /* children of <schemalist> {{{3 */
1222   else if (strcmp (container, "schemalist") == 0)
1223     {
1224       if (strcmp (element_name, "schema") == 0)
1225         {
1226           const gchar *id, *path, *gettext_domain, *extends, *list_of;
1227           if (COLLECT (STRING, "id", &id,
1228                        OPTIONAL | STRING, "path", &path,
1229                        OPTIONAL | STRING, "gettext-domain", &gettext_domain,
1230                        OPTIONAL | STRING, "extends", &extends,
1231                        OPTIONAL | STRING, "list-of", &list_of))
1232             parse_state_start_schema (state, id, path, gettext_domain,
1233                                       extends, list_of, error);
1234           return;
1235         }
1236
1237       else if (strcmp (element_name, "enum") == 0)
1238         {
1239           const gchar *id;
1240           if (COLLECT (STRING, "id", &id))
1241             parse_state_start_enum (state, id, FALSE, error);
1242           return;
1243         }
1244
1245       else if (strcmp (element_name, "flags") == 0)
1246         {
1247           const gchar *id;
1248           if (COLLECT (STRING, "id", &id))
1249             parse_state_start_enum (state, id, TRUE, error);
1250           return;
1251         }
1252     }
1253
1254
1255   /* children of <schema> {{{3 */
1256   else if (strcmp (container, "schema") == 0)
1257     {
1258       if (strcmp (element_name, "key") == 0)
1259         {
1260           const gchar *name, *type_string, *enum_type, *flags_type;
1261
1262           if (COLLECT (STRING,            "name",  &name,
1263                        OPTIONAL | STRING, "type",  &type_string,
1264                        OPTIONAL | STRING, "enum",  &enum_type,
1265                        OPTIONAL | STRING, "flags", &flags_type))
1266
1267             state->key_state = schema_state_add_key (state->schema_state,
1268                                                      state->enum_table,
1269                                                      state->flags_table,
1270                                                      name, type_string,
1271                                                      enum_type, flags_type,
1272                                                      error);
1273           return;
1274         }
1275       else if (strcmp (element_name, "child") == 0)
1276         {
1277           const gchar *name, *schema;
1278
1279           if (COLLECT (STRING, "name", &name, STRING, "schema", &schema))
1280             schema_state_add_child (state->schema_state,
1281                                     name, schema, error);
1282           return;
1283         }
1284       else if (strcmp (element_name, "override") == 0)
1285         {
1286           const gchar *name, *l10n, *context;
1287
1288           if (COLLECT (STRING,            "name",    &name,
1289                        OPTIONAL | STRING, "l10n",    &l10n,
1290                        OPTIONAL | STRING, "context", &context))
1291             schema_state_add_override (state->schema_state,
1292                                        &state->key_state, &state->string,
1293                                        name, l10n, context, error);
1294           return;
1295         }
1296     }
1297
1298   /* children of <key> {{{3 */
1299   else if (strcmp (container, "key") == 0)
1300     {
1301       if (strcmp (element_name, "default") == 0)
1302         {
1303           const gchar *l10n, *context;
1304           if (COLLECT (STRING | OPTIONAL, "l10n",    &l10n,
1305                        STRING | OPTIONAL, "context", &context))
1306             state->string = key_state_start_default (state->key_state,
1307                                                      l10n, context, error);
1308           return;
1309         }
1310
1311       else if (strcmp (element_name, "summary") == 0 ||
1312                strcmp (element_name, "description") == 0)
1313         {
1314           if (NO_ATTRS ())
1315             state->string = g_string_new (NULL);
1316           return;
1317         }
1318
1319       else if (strcmp (element_name, "range") == 0)
1320         {
1321           const gchar *min, *max;
1322           if (COLLECT (STRING, "min", &min, STRING, "max", &max))
1323             key_state_set_range (state->key_state, min, max, error);
1324           return;
1325         }
1326
1327       else if (strcmp (element_name, "choices") == 0)
1328         {
1329           if (NO_ATTRS ())
1330             key_state_start_choices (state->key_state, error);
1331           return;
1332         }
1333
1334       else if (strcmp (element_name, "aliases") == 0)
1335         {
1336           if (NO_ATTRS ())
1337             key_state_start_aliases (state->key_state, error);
1338           return;
1339         }
1340     }
1341
1342
1343   /* children of <choices> {{{3 */
1344   else if (strcmp (container, "choices") == 0)
1345     {
1346       if (strcmp (element_name, "choice") == 0)
1347         {
1348           const gchar *value;
1349           if (COLLECT (STRING, "value", &value))
1350             key_state_add_choice (state->key_state, value, error);
1351           return;
1352         }
1353     }
1354
1355
1356   /* children of <aliases> {{{3 */
1357   else if (strcmp (container, "aliases") == 0)
1358     {
1359       if (strcmp (element_name, "alias") == 0)
1360         {
1361           const gchar *value, *target;
1362           if (COLLECT (STRING, "value", &value, STRING, "target", &target))
1363             key_state_add_alias (state->key_state, value, target, error);
1364           return;
1365         }
1366     }
1367
1368
1369   /* children of <enum> {{{3 */
1370   else if (strcmp (container, "enum") == 0 ||
1371            strcmp (container, "flags") == 0)
1372     {
1373       if (strcmp (element_name, "value") == 0)
1374         {
1375           const gchar *nick, *valuestr;
1376           if (COLLECT (STRING, "nick", &nick,
1377                        STRING, "value", &valuestr))
1378             enum_state_add_value (state->enum_state, nick, valuestr, error);
1379           return;
1380         }
1381     }
1382   /* 3}}} */
1383
1384   if (container)
1385     g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_UNKNOWN_ELEMENT,
1386                  _("Element <%s> not allowed inside <%s>"),
1387                  element_name, container);
1388   else
1389     g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_UNKNOWN_ELEMENT,
1390                  _("Element <%s> not allowed at toplevel"), element_name);
1391 }
1392 /* 2}}} */
1393 /* End element {{{2 */
1394
1395 static void
1396 key_state_end (KeyState **state_ptr,
1397                GError   **error)
1398 {
1399   KeyState *state;
1400
1401   state = *state_ptr;
1402   *state_ptr = NULL;
1403
1404   if (state->default_value == NULL)
1405     {
1406       g_set_error_literal (error,
1407                            G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT,
1408                            "element <default> is required in <key>");
1409       return;
1410     }
1411 }
1412
1413 static void
1414 schema_state_end (SchemaState **state_ptr,
1415                   GError      **error)
1416 {
1417   SchemaState *state;
1418
1419   state = *state_ptr;
1420   *state_ptr = NULL;
1421 }
1422
1423 static void
1424 end_element (GMarkupParseContext  *context,
1425              const gchar          *element_name,
1426              gpointer              user_data,
1427              GError              **error)
1428 {
1429   ParseState *state = user_data;
1430
1431   if (strcmp (element_name, "schemalist") == 0)
1432     {
1433       g_free (state->schemalist_domain);
1434       state->schemalist_domain = NULL;
1435     }
1436
1437   else if (strcmp (element_name, "enum") == 0 ||
1438            strcmp (element_name, "flags") == 0)
1439     enum_state_end (&state->enum_state, error);
1440
1441   else if (strcmp (element_name, "schema") == 0)
1442     schema_state_end (&state->schema_state, error);
1443
1444   else if (strcmp (element_name, "override") == 0)
1445     override_state_end (&state->key_state, &state->string, error);
1446
1447   else if (strcmp (element_name, "key") == 0)
1448     key_state_end (&state->key_state, error);
1449
1450   else if (strcmp (element_name, "default") == 0)
1451     key_state_end_default (state->key_state, &state->string, error);
1452
1453   else if (strcmp (element_name, "choices") == 0)
1454     key_state_end_choices (state->key_state, error);
1455
1456   else if (strcmp (element_name, "aliases") == 0)
1457     key_state_end_aliases (state->key_state, error);
1458
1459   if (state->string)
1460     {
1461       g_string_free (state->string, TRUE);
1462       state->string = NULL;
1463     }
1464 }
1465 /* Text {{{2 */
1466 static void
1467 text (GMarkupParseContext  *context,
1468       const gchar          *text,
1469       gsize                 text_len,
1470       gpointer              user_data,
1471       GError              **error)
1472 {
1473   ParseState *state = user_data;
1474   gsize i;
1475
1476   for (i = 0; i < text_len; i++)
1477     if (!g_ascii_isspace (text[i]))
1478       {
1479         if (state->string)
1480           g_string_append_len (state->string, text, text_len);
1481
1482         else
1483           g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT,
1484                        _("text may not appear inside <%s>"),
1485                        g_markup_parse_context_get_element (context));
1486
1487         break;
1488       }
1489 }
1490
1491 /* Write to GVDB {{{1 */
1492 typedef struct
1493 {
1494   GHashTable *table;
1495   GvdbItem *root;
1496 } GvdbPair;
1497
1498 static void
1499 gvdb_pair_init (GvdbPair *pair)
1500 {
1501   pair->table = gvdb_hash_table_new (NULL, NULL);
1502   pair->root = gvdb_hash_table_insert (pair->table, "");
1503 }
1504
1505 typedef struct
1506 {
1507   GvdbPair pair;
1508   gboolean l10n;
1509 } OutputSchemaData;
1510
1511 static void
1512 output_key (gpointer key,
1513             gpointer value,
1514             gpointer user_data)
1515 {
1516   OutputSchemaData *data;
1517   const gchar *name;
1518   KeyState *state;
1519   GvdbItem *item;
1520
1521   name = key;
1522   state = value;
1523   data = user_data;
1524
1525   item = gvdb_hash_table_insert (data->pair.table, name);
1526   gvdb_item_set_parent (item, data->pair.root);
1527   gvdb_item_set_value (item, key_state_serialise (state));
1528
1529   if (state->l10n)
1530     data->l10n = TRUE;
1531 }
1532
1533 static void
1534 output_schema (gpointer key,
1535                gpointer value,
1536                gpointer user_data)
1537 {
1538   OutputSchemaData data;
1539   GvdbPair *root_pair;
1540   SchemaState *state;
1541   const gchar *id;
1542   GvdbItem *item;
1543
1544   id = key;
1545   state = value;
1546   root_pair = user_data;
1547
1548   gvdb_pair_init (&data.pair);
1549   data.l10n = FALSE;
1550
1551   item = gvdb_hash_table_insert (root_pair->table, id);
1552   gvdb_item_set_parent (item, root_pair->root);
1553   gvdb_item_set_hash_table (item, data.pair.table);
1554
1555   g_hash_table_foreach (state->keys, output_key, &data);
1556
1557   if (state->path)
1558     gvdb_hash_table_insert_string (data.pair.table, ".path", state->path);
1559
1560   if (state->extends_name)
1561     gvdb_hash_table_insert_string (data.pair.table, ".extends",
1562                                    state->extends_name);
1563
1564   if (state->list_of)
1565     gvdb_hash_table_insert_string (data.pair.table, ".list-of",
1566                                    state->extends_name);
1567
1568   if (data.l10n)
1569     gvdb_hash_table_insert_string (data.pair.table,
1570                                    ".gettext-domain",
1571                                    state->gettext_domain);
1572 }
1573
1574 static gboolean
1575 write_to_file (GHashTable   *schema_table,
1576                const gchar  *filename,
1577                GError      **error)
1578 {
1579   gboolean success;
1580   GvdbPair pair;
1581
1582   gvdb_pair_init (&pair);
1583
1584   g_hash_table_foreach (schema_table, output_schema, &pair);
1585
1586   success = gvdb_table_write_contents (pair.table, filename,
1587                                        G_BYTE_ORDER != G_LITTLE_ENDIAN,
1588                                        error);
1589   g_hash_table_unref (pair.table);
1590
1591   return success;
1592 }
1593
1594 /* Parser driver {{{1 */
1595 static GHashTable *
1596 parse_gschema_files (gchar    **files,
1597                      gboolean   strict)
1598 {
1599   GMarkupParser parser = { start_element, end_element, text };
1600   ParseState state = { 0, };
1601   const gchar *filename;
1602   GError *error = NULL;
1603
1604   state.enum_table = g_hash_table_new_full (g_str_hash, g_str_equal,
1605                                             g_free, enum_state_free);
1606
1607   state.flags_table = g_hash_table_new_full (g_str_hash, g_str_equal,
1608                                              g_free, enum_state_free);
1609
1610   state.schema_table = g_hash_table_new_full (g_str_hash, g_str_equal,
1611                                               g_free, schema_state_free);
1612
1613   while ((filename = *files++) != NULL)
1614     {
1615       GMarkupParseContext *context;
1616       gchar *contents;
1617       gsize size;
1618
1619       if (!g_file_get_contents (filename, &contents, &size, &error))
1620         {
1621           fprintf (stderr, "%s\n", error->message);
1622           g_clear_error (&error);
1623           continue;
1624         }
1625
1626       context = g_markup_parse_context_new (&parser,
1627                                             G_MARKUP_PREFIX_ERROR_POSITION,
1628                                             &state, NULL);
1629
1630
1631       if (!g_markup_parse_context_parse (context, contents, size, &error) ||
1632           !g_markup_parse_context_end_parse (context, &error))
1633         {
1634           GSList *item;
1635
1636           /* back out any changes from this file */
1637           for (item = state.this_file_schemas; item; item = item->next)
1638             g_hash_table_remove (state.schema_table, item->data);
1639
1640           for (item = state.this_file_flagss; item; item = item->next)
1641             g_hash_table_remove (state.flags_table, item->data);
1642
1643           for (item = state.this_file_enums; item; item = item->next)
1644             g_hash_table_remove (state.enum_table, item->data);
1645
1646           /* let them know */
1647           fprintf (stderr, "%s: %s.  ", filename, error->message);
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: */