xkbcomp: handle XKB file include's better
[platform/upstream/libxkbcommon.git] / src / xkbcomp / compat.c
1 /************************************************************
2  * Copyright (c) 1994 by Silicon Graphics Computer Systems, Inc.
3  *
4  * Permission to use, copy, modify, and distribute this
5  * software and its documentation for any purpose and without
6  * fee is hereby granted, provided that the above copyright
7  * notice appear in all copies and that both that copyright
8  * notice and this permission notice appear in supporting
9  * documentation, and that the name of Silicon Graphics not be
10  * used in advertising or publicity pertaining to distribution
11  * of the software without specific prior written permission.
12  * Silicon Graphics makes no representation about the suitability
13  * of this software for any purpose. It is provided "as is"
14  * without any express or implied warranty.
15  *
16  * SILICON GRAPHICS DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS
17  * SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
18  * AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL SILICON
19  * GRAPHICS BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL
20  * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
21  * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
22  * OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION  WITH
23  * THE USE OR PERFORMANCE OF THIS SOFTWARE.
24  *
25  ********************************************************/
26
27 /*
28  * Copyright © 2012 Ran Benita <ran234@gmail.com>
29  *
30  * Permission is hereby granted, free of charge, to any person obtaining a
31  * copy of this software and associated documentation files (the "Software"),
32  * to deal in the Software without restriction, including without limitation
33  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
34  * and/or sell copies of the Software, and to permit persons to whom the
35  * Software is furnished to do so, subject to the following conditions:
36  *
37  * The above copyright notice and this permission notice (including the next
38  * paragraph) shall be included in all copies or substantial portions of the
39  * Software.
40  *
41  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
42  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
43  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
44  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
45  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
46  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
47  * DEALINGS IN THE SOFTWARE.
48  */
49
50 #include "xkbcomp-priv.h"
51 #include "text.h"
52 #include "expr.h"
53 #include "action.h"
54 #include "vmod.h"
55 #include "include.h"
56
57 /*
58  * The xkb_compat section
59  * =====================
60  * This section is the third to be processed, after xkb_keycodes and
61  * xkb_types.
62  *
63  * Interpret statements
64  * --------------------
65  * Statements of the form:
66  *      interpret Num_Lock+Any { ... }
67  *      interpret Shift_Lock+AnyOf(Shift+Lock) { ... }
68  *
69  * The xkb_symbols section (see symbols.c) allows the keymap author to do,
70  * among other things, the following for each key:
71  * - Bind an action, like SetMods or LockGroup, to the key. Actions, like
72  *   symbols, are specified for each level of each group in the key
73  *   separately.
74  * - Add a virtual modifier to the key's virtual modifier mapping (vmodmap).
75  * - Specify whether the key should repeat or not.
76  *
77  * However, doing this for each key (or level) is tedious and inflexible.
78  * Interpret's are a mechanism to apply these settings to a bunch of
79  * keys/levels at once.
80  *
81  * Each interpret specifies a condition by which it attaches to certain
82  * levels. The condition consists of two parts:
83  * - A keysym. If the level has a different (or more than one) keysym, the
84  *   match failes. Leaving out the keysym is equivalent to using the
85  *   NoSymbol keysym, which always matches successfully.
86  * - A modifier predicate. The predicate consists of a matching operation
87  *   and a mask of (real) modifiers. The modifers are matched against the
88  *   key's modifier map (modmap). The matching operation can be one of the
89  *   following:
90  *   + AnyOfOrNone - The modmap must either be empty or include at least
91  *     one of the specified modifiers.
92  *   + AnyOf - The modmap must include at least one of the specified
93  *     modifiers.
94  *   + NoneOf - The modmap must not include any of the specified modifiers.
95  *   + AllOf - The modmap must include all of the specified modifiers (but
96  *     may include others as well).
97  *   + Exactly - The modmap must be exactly the same as the specified
98  *     modifiers.
99  *   Leaving out the predicate is equivalent to usign AnyOfOrNone while
100  *   specifying all modifiers. Leaving out just the matching condtition
101  *   is equivalent to using Exactly.
102  * An interpret may also include "useModMapMods = level1;" - see below.
103  *
104  * If a level fulfils the conditions of several interpret's, only the
105  * most specific one is used:
106  * - A specific keysym will always match before a generic NoSymbol
107  *   condition.
108  * - If the keysyms are the same, the interpret with the more specific
109  *   matching operation is used. The above list is sorted from least to
110  *   most specific.
111  * - If both the keysyms and the matching operations are the same (but the
112  *   modifiers are different), the first interpret is used.
113  *
114  * As described above, once an interpret "attaches" to a level, it can bind
115  * an action to that level, add one virtual modifier to the key's vmodmap,
116  * or set the key's repeat setting. You should note the following:
117  * - The key repeat is a property of the entire key; it is not level-specific.
118  *   In order to avoid confusion, it is only inspected for the first level of
119  *   the first group; the interpret's repeat setting is ignored when applied
120  *   to other levels.
121  * - If one of the above fields was set directly for a key in xkb_symbols,
122  *   the explicit setting takes precedence over the interpret.
123  *
124  * The body of the statment may include statements of the following
125  * forms (all of which are optional):
126  *
127  * - useModMapMods statement:
128  *      useModMapMods = level1;
129  *
130  *   When set to 'level1', the interpret will only match levels which are
131  *   the first level of the first group of the keys. This can be useful in
132  *   conjunction with e.g. a virtualModifier statement.
133  *
134  * - action statement:
135  *      action = LockMods(modifiers=NumLock);
136  *
137  *   Bind this action to the matching levels.
138  *
139  * - virtual modifier statement:
140  *      virtualModifier = NumLock;
141  *
142  *   Add this virtual modifier to the key's vmodmap. The given virtual
143  *   modifier must be declared at the top level of the file with a
144  *   virtual_modifiers statement, e.g.:
145  *      virtual_modifiers NumLock;
146  *
147  * - repeat statement:
148  *      repeat = True;
149  *
150  *   Set whether the key should repeat or not. Must be a boolean value.
151  *
152  * Led map statements
153  * ------------------------
154  * Statements of the form:
155  *      indicator "Shift Lock" { ... }
156  *
157  *   This statement specifies the behavior and binding of the LED (a.k.a
158  *   indicator) with the given name ("Shift Lock" above). The name should
159  *   have been declared previously in the xkb_keycodes section (see Led
160  *   name statement), and given an index there. If it wasn't, it is created
161  *   with the next free index.
162  *   The body of the statement describes the conditions of the keyboard
163  *   state which will cause the LED to be lit. It may include the following
164  *   statements:
165  *
166  * - modifiers statment:
167  *      modifiers = ScrollLock;
168  *
169  *   If the given modifiers are in the required state (see below), the
170  *   led is lit.
171  *
172  * - whichModifierState statment:
173  *      whichModState = Latched + Locked;
174  *
175  *   Can be any combination of:
176  *      base, latched, locked, effective
177  *      any (i.e. all of the above)
178  *      none (i.e. none of the above)
179  *      compat (legacy value, treated as effective)
180  *   This will cause the respective portion of the modifer state (see
181  *   struct xkb_state) to be matched against the modifiers given in the
182  *   "modifiers" statement.
183  *
184  *   Here's a simple example:
185  *      indicator "Num Lock" {
186  *          modifiers = NumLock;
187  *          whichModState = Locked;
188  *      };
189  *   Whenever the NumLock modifier is locked, the Num Lock LED will light
190  *   up.
191  *
192  * - groups statment:
193  *      groups = All - group1;
194  *
195  *   If the given groups are in the required state (see below), the led
196  *   is lit.
197  *
198  * - whichGroupState statment:
199  *      whichGroupState = Effective;
200  *
201  *   Can be any combination of:
202  *      base, latched, locked, effective
203  *      any (i.e. all of the above)
204  *      none (i.e. none of the above)
205  *   This will cause the respective portion of the group state (see
206  *   struct xkb_state) to be matched against the groups given in the
207  *   "groups" statement.
208  *
209  *   Note: the above conditions are disjunctive, i.e. if any of them are
210  *   satisfied the led is lit.
211  *
212  * Virtual modifier statements
213  * ---------------------------
214  * Statements of the form:
215  *     virtual_modifiers LControl;
216  *
217  * Can appear in the xkb_types, xkb_compat, xkb_symbols sections.
218  * TODO
219  *
220  * Effect on keymap
221  * ----------------
222  * After all of the xkb_compat sections have been compiled, the following
223  * members of struct xkb_keymap are finalized:
224  *      darray(struct xkb_sym_interpret) sym_interprets;
225  *      darray(struct xkb_led) leds;
226  *      char *compat_section_name;
227  * TODO: virtual modifiers.
228  */
229
230 enum si_field {
231     SI_FIELD_VIRTUAL_MOD    = (1 << 0),
232     SI_FIELD_ACTION         = (1 << 1),
233     SI_FIELD_AUTO_REPEAT    = (1 << 2),
234     SI_FIELD_LEVEL_ONE_ONLY = (1 << 3),
235 };
236
237 typedef struct {
238     enum si_field defined;
239     unsigned file_id;
240     enum merge_mode merge;
241
242     struct xkb_sym_interpret interp;
243 } SymInterpInfo;
244
245 enum led_field {
246     LED_FIELD_MODS       = (1 << 0),
247     LED_FIELD_GROUPS     = (1 << 1),
248     LED_FIELD_CTRLS      = (1 << 2),
249 };
250
251 typedef struct {
252     enum led_field defined;
253     unsigned file_id;
254     enum merge_mode merge;
255
256     struct xkb_led led;
257 } LedInfo;
258
259 typedef struct {
260     char *name;
261     unsigned file_id;
262     int errorCount;
263     SymInterpInfo default_interp;
264     darray(SymInterpInfo) interps;
265     LedInfo default_led;
266     darray(LedInfo) leds;
267     ActionsInfo *actions;
268     struct xkb_keymap *keymap;
269 } CompatInfo;
270
271 static const char *
272 siText(SymInterpInfo *si, CompatInfo *info)
273 {
274     char *buf = xkb_context_get_buffer(info->keymap->ctx, 128);
275
276     if (si == &info->default_interp)
277         return "default";
278
279     snprintf(buf, 128, "%s+%s(%s)",
280              KeysymText(info->keymap->ctx, si->interp.sym),
281              SIMatchText(si->interp.match),
282              ModMaskText(info->keymap, si->interp.mods));
283
284     return buf;
285 }
286
287 static inline bool
288 ReportSINotArray(CompatInfo *info, SymInterpInfo *si, const char *field)
289 {
290     return ReportNotArray(info->keymap->ctx, "symbol interpretation", field,
291                           siText(si, info));
292 }
293
294 static inline bool
295 ReportSIBadType(CompatInfo *info, SymInterpInfo *si, const char *field,
296                 const char *wanted)
297 {
298     return ReportBadType(info->keymap->ctx, "symbol interpretation", field,
299                          siText(si, info), wanted);
300 }
301
302 static inline bool
303 ReportLedBadType(CompatInfo *info, LedInfo *ledi, const char *field,
304                  const char *wanted)
305 {
306     return ReportBadType(info->keymap->ctx, "indicator map", field,
307                          xkb_atom_text(info->keymap->ctx, ledi->led.name),
308                          wanted);
309 }
310
311 static inline bool
312 ReportLedNotArray(CompatInfo *info, LedInfo *ledi, const char *field)
313 {
314     return ReportNotArray(info->keymap->ctx, "indicator map", field,
315                           xkb_atom_text(info->keymap->ctx, ledi->led.name));
316 }
317
318 static void
319 InitCompatInfo(CompatInfo *info, struct xkb_keymap *keymap, unsigned file_id,
320                ActionsInfo *actions)
321 {
322     memset(info, 0, sizeof(*info));
323     info->keymap = keymap;
324     info->file_id = file_id;
325     info->actions = actions;
326     info->default_interp.file_id = file_id;
327     info->default_interp.merge = MERGE_OVERRIDE;
328     info->default_interp.interp.virtual_mod = XKB_MOD_INVALID;
329     info->default_led.file_id = file_id;
330     info->default_led.merge = MERGE_OVERRIDE;
331 }
332
333 static void
334 ClearCompatInfo(CompatInfo *info)
335 {
336     free(info->name);
337     darray_free(info->interps);
338     darray_free(info->leds);
339 }
340
341 static SymInterpInfo *
342 FindMatchingInterp(CompatInfo *info, SymInterpInfo *new)
343 {
344     SymInterpInfo *old;
345
346     darray_foreach(old, info->interps)
347         if (old->interp.sym == new->interp.sym &&
348             old->interp.mods == new->interp.mods &&
349             old->interp.match == new->interp.match)
350             return old;
351
352     return NULL;
353 }
354
355 static bool
356 UseNewInterpField(enum si_field field, SymInterpInfo *old, SymInterpInfo *new,
357                   bool report, enum si_field *collide)
358 {
359     if (!(old->defined & field))
360         return true;
361
362     if (new->defined & field) {
363         if (report)
364             *collide |= field;
365
366         if (new->merge != MERGE_AUGMENT)
367             return true;
368     }
369
370     return false;
371 }
372
373 static bool
374 AddInterp(CompatInfo *info, SymInterpInfo *new)
375 {
376     enum si_field collide = 0;
377     SymInterpInfo *old;
378
379     old = FindMatchingInterp(info, new);
380     if (old) {
381         int verbosity = xkb_context_get_log_verbosity(info->keymap->ctx);
382         bool report = ((old->file_id == new->file_id && verbosity > 0) ||
383                        verbosity > 9);
384
385         if (new->merge == MERGE_REPLACE) {
386             if (report)
387                 log_warn(info->keymap->ctx,
388                          "Multiple definitions for \"%s\"; "
389                          "Earlier interpretation ignored\n",
390                          siText(new, info));
391             *old = *new;
392             return true;
393         }
394
395         if (UseNewInterpField(SI_FIELD_VIRTUAL_MOD, old, new, report,
396                               &collide)) {
397             old->interp.virtual_mod = new->interp.virtual_mod;
398             old->defined |= SI_FIELD_VIRTUAL_MOD;
399         }
400         if (UseNewInterpField(SI_FIELD_ACTION, old, new, report,
401                               &collide)) {
402             old->interp.action = new->interp.action;
403             old->defined |= SI_FIELD_ACTION;
404         }
405         if (UseNewInterpField(SI_FIELD_AUTO_REPEAT, old, new, report,
406                               &collide)) {
407             old->interp.repeat = new->interp.repeat;
408             old->defined |= SI_FIELD_AUTO_REPEAT;
409         }
410         if (UseNewInterpField(SI_FIELD_LEVEL_ONE_ONLY, old, new, report,
411                               &collide)) {
412             old->interp.level_one_only = new->interp.level_one_only;
413             old->defined |= SI_FIELD_LEVEL_ONE_ONLY;
414         }
415
416         if (collide) {
417             log_warn(info->keymap->ctx,
418                      "Multiple interpretations of \"%s\"; "
419                      "Using %s definition for duplicate fields\n",
420                      siText(new, info),
421                      (new->merge != MERGE_AUGMENT ? "last" : "first"));
422         }
423
424         return true;
425     }
426
427     darray_append(info->interps, *new);
428     return true;
429 }
430
431
432 /***====================================================================***/
433
434 static bool
435 ResolveStateAndPredicate(ExprDef *expr, enum xkb_match_operation *pred_rtrn,
436                          xkb_mod_mask_t *mods_rtrn, CompatInfo *info)
437 {
438     if (expr == NULL) {
439         *pred_rtrn = MATCH_ANY_OR_NONE;
440         *mods_rtrn = MOD_REAL_MASK_ALL;
441         return true;
442     }
443
444     *pred_rtrn = MATCH_EXACTLY;
445     if (expr->op == EXPR_ACTION_DECL) {
446         const char *pred_txt = xkb_atom_text(info->keymap->ctx,
447                                              expr->value.action.name);
448         if (!LookupString(symInterpretMatchMaskNames, pred_txt, pred_rtrn)) {
449             log_err(info->keymap->ctx,
450                     "Illegal modifier predicate \"%s\"; Ignored\n", pred_txt);
451             return false;
452         }
453         expr = expr->value.action.args;
454     }
455     else if (expr->op == EXPR_IDENT) {
456         const char *pred_txt = xkb_atom_text(info->keymap->ctx,
457                                              expr->value.str);
458         if (pred_txt && istreq(pred_txt, "any")) {
459             *pred_rtrn = MATCH_ANY;
460             *mods_rtrn = MOD_REAL_MASK_ALL;
461             return true;
462         }
463     }
464
465     return ExprResolveModMask(info->keymap, expr, MOD_REAL, mods_rtrn);
466 }
467
468 /***====================================================================***/
469
470 static bool
471 UseNewLEDField(enum led_field field, LedInfo *old, LedInfo *new,
472                bool report, enum led_field *collide)
473 {
474     if (!(old->defined & field))
475         return true;
476
477     if (new->defined & field) {
478         if (report)
479             *collide |= field;
480
481         if (new->merge != MERGE_AUGMENT)
482             return true;
483     }
484
485     return false;
486 }
487
488 static bool
489 AddLedMap(CompatInfo *info, LedInfo *new)
490 {
491     LedInfo *old;
492     enum led_field collide;
493     struct xkb_context *ctx = info->keymap->ctx;
494     int verbosity = xkb_context_get_log_verbosity(ctx);
495
496     darray_foreach(old, info->leds) {
497         bool report;
498
499         if (old->led.name != new->led.name)
500             continue;
501
502         if (old->led.mods.mods == new->led.mods.mods &&
503             old->led.groups == new->led.groups &&
504             old->led.ctrls == new->led.ctrls &&
505             old->led.which_mods == new->led.which_mods &&
506             old->led.which_groups == new->led.which_groups) {
507             old->defined |= new->defined;
508             return true;
509         }
510
511         report = ((old->file_id == new->file_id && verbosity > 0) ||
512                   verbosity > 9);
513
514         if (new->merge == MERGE_REPLACE) {
515             if (report)
516                 log_warn(info->keymap->ctx,
517                          "Map for indicator %s redefined; "
518                          "Earlier definition ignored\n",
519                          xkb_atom_text(ctx, old->led.name));
520             *old = *new;
521             return true;
522         }
523
524         collide = 0;
525         if (UseNewLEDField(LED_FIELD_MODS, old, new, report, &collide)) {
526             old->led.which_mods = new->led.which_mods;
527             old->led.mods = new->led.mods;
528             old->defined |= LED_FIELD_MODS;
529         }
530         if (UseNewLEDField(LED_FIELD_GROUPS, old, new, report, &collide)) {
531             old->led.which_groups = new->led.which_groups;
532             old->led.groups = new->led.groups;
533             old->defined |= LED_FIELD_GROUPS;
534         }
535         if (UseNewLEDField(LED_FIELD_CTRLS, old, new, report, &collide)) {
536             old->led.ctrls = new->led.ctrls;
537             old->defined |= LED_FIELD_CTRLS;
538         }
539
540         if (collide) {
541             log_warn(info->keymap->ctx,
542                      "Map for indicator %s redefined; "
543                      "Using %s definition for duplicate fields\n",
544                      xkb_atom_text(ctx, old->led.name),
545                      (new->merge == MERGE_AUGMENT ? "first" : "last"));
546         }
547
548         return true;
549     }
550
551     darray_append(info->leds, *new);
552     return true;
553 }
554
555 static void
556 MergeIncludedCompatMaps(CompatInfo *into, CompatInfo *from,
557                         enum merge_mode merge)
558 {
559     SymInterpInfo *si;
560     LedInfo *ledi;
561
562     if (from->errorCount > 0) {
563         into->errorCount += from->errorCount;
564         return;
565     }
566
567     if (into->name == NULL) {
568         into->name = from->name;
569         from->name = NULL;
570     }
571
572     darray_foreach(si, from->interps) {
573         si->merge = (merge == MERGE_DEFAULT ? si->merge : merge);
574         if (!AddInterp(into, si))
575             into->errorCount++;
576     }
577
578     darray_foreach(ledi, from->leds) {
579         ledi->merge = (merge == MERGE_DEFAULT ? ledi->merge : merge);
580         if (!AddLedMap(into, ledi))
581             into->errorCount++;
582     }
583 }
584
585 static void
586 HandleCompatMapFile(CompatInfo *info, XkbFile *file, enum merge_mode merge);
587
588 static bool
589 HandleIncludeCompatMap(CompatInfo *info, IncludeStmt *include)
590 {
591     CompatInfo included;
592
593     InitCompatInfo(&included, info->keymap, info->file_id, info->actions);
594     included.name = include->stmt;
595     include->stmt = NULL;
596
597     for (IncludeStmt *stmt = include; stmt; stmt = stmt->next_incl) {
598         CompatInfo next_incl;
599         XkbFile *file;
600
601         file = ProcessIncludeFile(info->keymap->ctx, stmt, FILE_TYPE_COMPAT);
602         if (!file) {
603             info->errorCount += 10;
604             ClearCompatInfo(&included);
605             return false;
606         }
607
608         InitCompatInfo(&next_incl, info->keymap, file->id, info->actions);
609         next_incl.default_interp = info->default_interp;
610         next_incl.default_interp.file_id = file->id;
611         next_incl.default_interp.merge = stmt->merge;
612         next_incl.default_led = info->default_led;
613         next_incl.default_led.file_id = file->id;
614         next_incl.default_led.merge = stmt->merge;
615
616         HandleCompatMapFile(&next_incl, file, MERGE_OVERRIDE);
617
618         MergeIncludedCompatMaps(&included, &next_incl, stmt->merge);
619
620         ClearCompatInfo(&next_incl);
621         FreeXkbFile(file);
622     }
623
624     MergeIncludedCompatMaps(info, &included, include->merge);
625     ClearCompatInfo(&included);
626
627     return (info->errorCount == 0);
628 }
629
630 static bool
631 SetInterpField(CompatInfo *info, SymInterpInfo *si, const char *field,
632                ExprDef *arrayNdx, ExprDef *value)
633 {
634     struct xkb_keymap *keymap = info->keymap;
635     xkb_mod_index_t ndx;
636
637     if (istreq(field, "action")) {
638         if (arrayNdx)
639             return ReportSINotArray(info, si, field);
640
641         if (!HandleActionDef(value, keymap, &si->interp.action, info->actions))
642             return false;
643
644         si->defined |= SI_FIELD_ACTION;
645     }
646     else if (istreq(field, "virtualmodifier") ||
647              istreq(field, "virtualmod")) {
648         if (arrayNdx)
649             return ReportSINotArray(info, si, field);
650
651         if (!ExprResolveMod(keymap, value, MOD_VIRT, &ndx))
652             return ReportSIBadType(info, si, field, "virtual modifier");
653
654         si->interp.virtual_mod = ndx;
655         si->defined |= SI_FIELD_VIRTUAL_MOD;
656     }
657     else if (istreq(field, "repeat")) {
658         bool set;
659
660         if (arrayNdx)
661             return ReportSINotArray(info, si, field);
662
663         if (!ExprResolveBoolean(keymap->ctx, value, &set))
664             return ReportSIBadType(info, si, field, "boolean");
665
666         si->interp.repeat = set;
667
668         si->defined |= SI_FIELD_AUTO_REPEAT;
669     }
670     else if (istreq(field, "locking")) {
671         log_dbg(info->keymap->ctx,
672                 "The \"locking\" field in symbol interpretation is unsupported; "
673                 "Ignored\n");
674     }
675     else if (istreq(field, "usemodmap") ||
676              istreq(field, "usemodmapmods")) {
677         unsigned int val;
678
679         if (arrayNdx)
680             return ReportSINotArray(info, si, field);
681
682         if (!ExprResolveEnum(keymap->ctx, value, &val, useModMapValueNames))
683             return ReportSIBadType(info, si, field, "level specification");
684
685         si->interp.level_one_only = !!val;
686         si->defined |= SI_FIELD_LEVEL_ONE_ONLY;
687     }
688     else {
689         return ReportBadField(keymap->ctx, "symbol interpretation", field,
690                               siText(si, info));
691     }
692
693     return true;
694 }
695
696 static bool
697 SetLedMapField(CompatInfo *info, LedInfo *ledi, const char *field,
698                ExprDef *arrayNdx, ExprDef *value)
699 {
700     bool ok = true;
701     struct xkb_keymap *keymap = info->keymap;
702
703     if (istreq(field, "modifiers") || istreq(field, "mods")) {
704         if (arrayNdx)
705             return ReportLedNotArray(info, ledi, field);
706
707         if (!ExprResolveModMask(keymap, value, MOD_BOTH, &ledi->led.mods.mods))
708             return ReportLedBadType(info, ledi, field, "modifier mask");
709
710         ledi->defined |= LED_FIELD_MODS;
711     }
712     else if (istreq(field, "groups")) {
713         unsigned int mask;
714
715         if (arrayNdx)
716             return ReportLedNotArray(info, ledi, field);
717
718         if (!ExprResolveMask(keymap->ctx, value, &mask, groupMaskNames))
719             return ReportLedBadType(info, ledi, field, "group mask");
720
721         ledi->led.groups = mask;
722         ledi->defined |= LED_FIELD_GROUPS;
723     }
724     else if (istreq(field, "controls") || istreq(field, "ctrls")) {
725         unsigned int mask;
726
727         if (arrayNdx)
728             return ReportLedNotArray(info, ledi, field);
729
730         if (!ExprResolveMask(keymap->ctx, value, &mask, ctrlMaskNames))
731             return ReportLedBadType(info, ledi, field, "controls mask");
732
733         ledi->led.ctrls = mask;
734         ledi->defined |= LED_FIELD_CTRLS;
735     }
736     else if (istreq(field, "allowexplicit")) {
737         log_dbg(info->keymap->ctx,
738                 "The \"allowExplicit\" field in indicator statements is unsupported; "
739                 "Ignored\n");
740     }
741     else if (istreq(field, "whichmodstate") ||
742              istreq(field, "whichmodifierstate")) {
743         unsigned int mask;
744
745         if (arrayNdx)
746             return ReportLedNotArray(info, ledi, field);
747
748         if (!ExprResolveMask(keymap->ctx, value, &mask,
749                              modComponentMaskNames))
750             return ReportLedBadType(info, ledi, field,
751                                     "mask of modifier state components");
752
753         ledi->led.which_mods = mask;
754     }
755     else if (istreq(field, "whichgroupstate")) {
756         unsigned mask;
757
758         if (arrayNdx)
759             return ReportLedNotArray(info, ledi, field);
760
761         if (!ExprResolveMask(keymap->ctx, value, &mask,
762                              groupComponentMaskNames))
763             return ReportLedBadType(info, ledi, field,
764                                     "mask of group state components");
765
766         ledi->led.which_groups = mask;
767     }
768     else if (istreq(field, "driveskbd") ||
769              istreq(field, "driveskeyboard") ||
770              istreq(field, "leddriveskbd") ||
771              istreq(field, "leddriveskeyboard") ||
772              istreq(field, "indicatordriveskbd") ||
773              istreq(field, "indicatordriveskeyboard")) {
774         log_dbg(info->keymap->ctx,
775                 "The \"%s\" field in indicator statements is unsupported; "
776                 "Ignored\n", field);
777     }
778     else if (istreq(field, "index")) {
779         /* Users should see this, it might cause unexpected behavior. */
780         log_err(info->keymap->ctx,
781                 "The \"index\" field in indicator statements is unsupported; "
782                 "Ignored\n");
783     }
784     else {
785         log_err(info->keymap->ctx,
786                 "Unknown field %s in map for %s indicator; "
787                 "Definition ignored\n",
788                 field, xkb_atom_text(keymap->ctx, ledi->led.name));
789         ok = false;
790     }
791
792     return ok;
793 }
794
795 static bool
796 HandleGlobalVar(CompatInfo *info, VarDef *stmt)
797 {
798     const char *elem, *field;
799     ExprDef *ndx;
800     bool ret;
801
802     if (!ExprResolveLhs(info->keymap->ctx, stmt->name, &elem, &field, &ndx))
803         ret = false;
804     else if (elem && istreq(elem, "interpret"))
805         ret = SetInterpField(info, &info->default_interp, field, ndx,
806                              stmt->value);
807     else if (elem && istreq(elem, "indicator"))
808         ret = SetLedMapField(info, &info->default_led, field, ndx,
809                              stmt->value);
810     else
811         ret = SetActionField(info->keymap, elem, field, ndx, stmt->value,
812                              info->actions);
813     return ret;
814 }
815
816 static bool
817 HandleInterpBody(CompatInfo *info, VarDef *def, SymInterpInfo *si)
818 {
819     bool ok = true;
820     const char *elem, *field;
821     ExprDef *arrayNdx;
822
823     for (; def; def = (VarDef *) def->common.next) {
824         if (def->name && def->name->op == EXPR_FIELD_REF) {
825             log_err(info->keymap->ctx,
826                     "Cannot set a global default value from within an interpret statement; "
827                     "Move statements to the global file scope\n");
828             ok = false;
829             continue;
830         }
831
832         ok = ExprResolveLhs(info->keymap->ctx, def->name, &elem, &field,
833                             &arrayNdx);
834         if (!ok)
835             continue;
836
837         ok = SetInterpField(info, si, field, arrayNdx, def->value);
838     }
839
840     return ok;
841 }
842
843 static bool
844 HandleInterpDef(CompatInfo *info, InterpDef *def, enum merge_mode merge)
845 {
846     enum xkb_match_operation pred;
847     xkb_mod_mask_t mods;
848     SymInterpInfo si;
849
850     if (!ResolveStateAndPredicate(def->match, &pred, &mods, info)) {
851         log_err(info->keymap->ctx,
852                 "Couldn't determine matching modifiers; "
853                 "Symbol interpretation ignored\n");
854         return false;
855     }
856
857     si = info->default_interp;
858     si.merge = merge = (def->merge == MERGE_DEFAULT ? merge : def->merge);
859
860     if (!LookupKeysym(def->sym, &si.interp.sym)) {
861         log_err(info->keymap->ctx,
862                 "Could not resolve keysym %s; "
863                 "Symbol interpretation ignored\n",
864                 def->sym);
865         return false;
866     }
867
868     si.interp.match = pred;
869     si.interp.mods = mods;
870
871     if (!HandleInterpBody(info, def->def, &si)) {
872         info->errorCount++;
873         return false;
874     }
875
876     if (!AddInterp(info, &si)) {
877         info->errorCount++;
878         return false;
879     }
880
881     return true;
882 }
883
884 static bool
885 HandleLedMapDef(CompatInfo *info, LedMapDef *def, enum merge_mode merge)
886 {
887     LedInfo ledi;
888     VarDef *var;
889     bool ok;
890
891     if (def->merge != MERGE_DEFAULT)
892         merge = def->merge;
893
894     ledi = info->default_led;
895     ledi.merge = merge;
896     ledi.led.name = def->name;
897
898     ok = true;
899     for (var = def->body; var != NULL; var = (VarDef *) var->common.next) {
900         const char *elem, *field;
901         ExprDef *arrayNdx;
902         if (!ExprResolveLhs(info->keymap->ctx, var->name, &elem, &field,
903                             &arrayNdx)) {
904             ok = false;
905             continue;
906         }
907
908         if (elem) {
909             log_err(info->keymap->ctx,
910                     "Cannot set defaults for \"%s\" element in indicator map; "
911                     "Assignment to %s.%s ignored\n", elem, elem, field);
912             ok = false;
913         }
914         else {
915             ok = SetLedMapField(info, &ledi, field, arrayNdx, var->value) && ok;
916         }
917     }
918
919     if (ok)
920         return AddLedMap(info, &ledi);
921
922     return false;
923 }
924
925 static void
926 HandleCompatMapFile(CompatInfo *info, XkbFile *file, enum merge_mode merge)
927 {
928     bool ok;
929
930     merge = (merge == MERGE_DEFAULT ? MERGE_AUGMENT : merge);
931
932     free(info->name);
933     info->name = strdup_safe(file->name);
934
935     for (ParseCommon *stmt = file->defs; stmt; stmt = stmt->next) {
936         switch (stmt->type) {
937         case STMT_INCLUDE:
938             ok = HandleIncludeCompatMap(info, (IncludeStmt *) stmt);
939             break;
940         case STMT_INTERP:
941             ok = HandleInterpDef(info, (InterpDef *) stmt, merge);
942             break;
943         case STMT_GROUP_COMPAT:
944             log_dbg(info->keymap->ctx,
945                     "The \"group\" statement in compat is unsupported; "
946                     "Ignored\n");
947             ok = true;
948             break;
949         case STMT_LED_MAP:
950             ok = HandleLedMapDef(info, (LedMapDef *) stmt, merge);
951             break;
952         case STMT_VAR:
953             ok = HandleGlobalVar(info, (VarDef *) stmt);
954             break;
955         case STMT_VMOD:
956             ok = HandleVModDef(info->keymap, (VModDef *) stmt);
957             break;
958         default:
959             log_err(info->keymap->ctx,
960                     "Interpretation files may not include other types; "
961                     "Ignoring %s\n", stmt_type_to_string(stmt->type));
962             ok = false;
963             break;
964         }
965
966         if (!ok)
967             info->errorCount++;
968
969         if (info->errorCount > 10) {
970             log_err(info->keymap->ctx,
971                     "Abandoning compatibility map \"%s\"\n", file->topName);
972             break;
973         }
974     }
975 }
976
977 static void
978 CopyInterps(CompatInfo *info, bool needSymbol, enum xkb_match_operation pred)
979 {
980     SymInterpInfo *si;
981
982     darray_foreach(si, info->interps)
983         if (si->interp.match == pred &&
984             (si->interp.sym != XKB_KEY_NoSymbol) == needSymbol)
985             darray_append(info->keymap->sym_interprets, si->interp);
986 }
987
988 static void
989 CopyLedMapDefs(CompatInfo *info)
990 {
991     LedInfo *ledi;
992     xkb_led_index_t i;
993     struct xkb_led *led;
994     struct xkb_keymap *keymap = info->keymap;
995
996     darray_foreach(ledi, info->leds) {
997         /*
998          * Find the LED with the given name, if it was already declared
999          * in keycodes.
1000          */
1001         darray_enumerate(i, led, keymap->leds)
1002             if (led->name == ledi->led.name)
1003                 break;
1004
1005         /* Not previously declared; create it with next free index. */
1006         if (i >= darray_size(keymap->leds)) {
1007             log_dbg(keymap->ctx,
1008                     "Indicator name \"%s\" was not declared in the keycodes section; "
1009                     "Adding new indicator\n",
1010                     xkb_atom_text(keymap->ctx, ledi->led.name));
1011
1012             darray_enumerate(i, led, keymap->leds)
1013                 if (led->name == XKB_ATOM_NONE)
1014                     break;
1015
1016             if (i >= darray_size(keymap->leds)) {
1017                 /* Not place to put it; ignore. */
1018                 if (i >= XKB_MAX_LEDS) {
1019                     log_err(keymap->ctx,
1020                             "Too many indicators (maximum is %d); "
1021                             "Indicator name \"%s\" ignored\n",
1022                             XKB_MAX_LEDS,
1023                             xkb_atom_text(keymap->ctx, ledi->led.name));
1024                     continue;
1025                 }
1026                 /* Add a new LED. */
1027                 darray_resize(keymap->leds, i + 1);
1028                 led = &darray_item(keymap->leds, i);
1029             }
1030         }
1031
1032         *led = ledi->led;
1033         if (led->groups != 0 && led->which_groups == 0)
1034             led->which_groups = XKB_STATE_LAYOUT_EFFECTIVE;
1035         if (led->mods.mods != 0 && led->which_mods == 0)
1036             led->which_mods = XKB_STATE_MODS_EFFECTIVE;
1037     }
1038 }
1039
1040 static bool
1041 CopyCompatToKeymap(struct xkb_keymap *keymap, CompatInfo *info)
1042 {
1043     keymap->compat_section_name = strdup_safe(info->name);
1044
1045     if (!darray_empty(info->interps)) {
1046         /* Most specific to least specific. */
1047         CopyInterps(info, true, MATCH_EXACTLY);
1048         CopyInterps(info, true, MATCH_ALL);
1049         CopyInterps(info, true, MATCH_NONE);
1050         CopyInterps(info, true, MATCH_ANY);
1051         CopyInterps(info, true, MATCH_ANY_OR_NONE);
1052         CopyInterps(info, false, MATCH_EXACTLY);
1053         CopyInterps(info, false, MATCH_ALL);
1054         CopyInterps(info, false, MATCH_NONE);
1055         CopyInterps(info, false, MATCH_ANY);
1056         CopyInterps(info, false, MATCH_ANY_OR_NONE);
1057     }
1058
1059     CopyLedMapDefs(info);
1060
1061     return true;
1062 }
1063
1064 bool
1065 CompileCompatMap(XkbFile *file, struct xkb_keymap *keymap,
1066                  enum merge_mode merge)
1067 {
1068     CompatInfo info;
1069     ActionsInfo *actions;
1070
1071     actions = NewActionsInfo();
1072     if (!actions)
1073         return false;
1074
1075     InitCompatInfo(&info, keymap, file->id, actions);
1076     info.default_interp.merge = merge;
1077     info.default_led.merge = merge;
1078
1079     HandleCompatMapFile(&info, file, merge);
1080     if (info.errorCount != 0)
1081         goto err_info;
1082
1083     if (!CopyCompatToKeymap(keymap, &info))
1084         goto err_info;
1085
1086     ClearCompatInfo(&info);
1087     FreeActionsInfo(actions);
1088     return true;
1089
1090 err_info:
1091     ClearCompatInfo(&info);
1092     FreeActionsInfo(actions);
1093     return false;
1094 }