ast: use a separate expr struct for action list
[platform/upstream/libxkbcommon.git] / src / xkbcomp / symbols.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 Intel Corporation
29  * Copyright © 2012 Ran Benita <ran234@gmail.com>
30  *
31  * Permission is hereby granted, free of charge, to any person obtaining a
32  * copy of this software and associated documentation files (the "Software"),
33  * to deal in the Software without restriction, including without limitation
34  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
35  * and/or sell copies of the Software, and to permit persons to whom the
36  * Software is furnished to do so, subject to the following conditions:
37  *
38  * The above copyright notice and this permission notice (including the next
39  * paragraph) shall be included in all copies or substantial portions of the
40  * Software.
41  *
42  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
43  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
44  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
45  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
46  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
47  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
48  * DEALINGS IN THE SOFTWARE.
49  *
50  * Author: Daniel Stone <daniel@fooishbar.org>
51  *         Ran Benita <ran234@gmail.com>
52  */
53
54 #include "xkbcomp-priv.h"
55 #include "text.h"
56 #include "expr.h"
57 #include "action.h"
58 #include "vmod.h"
59 #include "include.h"
60 #include "keysym.h"
61
62 enum key_repeat {
63     KEY_REPEAT_UNDEFINED = 0,
64     KEY_REPEAT_YES = 1,
65     KEY_REPEAT_NO = 2,
66 };
67
68 enum group_field {
69     GROUP_FIELD_SYMS = (1 << 0),
70     GROUP_FIELD_ACTS = (1 << 1),
71     GROUP_FIELD_TYPE = (1 << 2),
72 };
73
74 enum key_field {
75     KEY_FIELD_REPEAT = (1 << 0),
76     KEY_FIELD_DEFAULT_TYPE = (1 << 1),
77     KEY_FIELD_GROUPINFO = (1 << 2),
78     KEY_FIELD_VMODMAP = (1 << 3),
79 };
80
81 typedef struct {
82     enum group_field defined;
83     darray(struct xkb_level) levels;
84     xkb_atom_t type;
85 } GroupInfo;
86
87 typedef struct {
88     enum key_field defined;
89     enum merge_mode merge;
90
91     xkb_atom_t name;
92
93     darray(GroupInfo) groups;
94
95     enum key_repeat repeat;
96     xkb_mod_mask_t vmodmap;
97     xkb_atom_t default_type;
98
99     enum xkb_range_exceed_type out_of_range_group_action;
100     xkb_layout_index_t out_of_range_group_number;
101 } KeyInfo;
102
103 static void
104 ClearLevelInfo(struct xkb_level *leveli)
105 {
106     if (leveli->num_syms > 1)
107         free(leveli->u.syms);
108 }
109
110 static void
111 InitGroupInfo(GroupInfo *groupi)
112 {
113     memset(groupi, 0, sizeof(*groupi));
114 }
115
116 static void
117 ClearGroupInfo(GroupInfo *groupi)
118 {
119     struct xkb_level *leveli;
120     darray_foreach(leveli, groupi->levels)
121         ClearLevelInfo(leveli);
122     darray_free(groupi->levels);
123 }
124
125 static void
126 CopyGroupInfo(GroupInfo *to, const GroupInfo *from)
127 {
128     to->defined = from->defined;
129     to->type = from->type;
130     darray_init(to->levels);
131     darray_copy(to->levels, from->levels);
132     for (xkb_level_index_t j = 0; j < darray_size(to->levels); j++)
133         if (darray_item(from->levels, j).num_syms > 1)
134             darray_item(to->levels, j).u.syms =
135                 memdup(darray_item(from->levels, j).u.syms,
136                        darray_item(from->levels, j).num_syms,
137                        sizeof(xkb_keysym_t));
138 }
139
140 static void
141 InitKeyInfo(struct xkb_context *ctx, KeyInfo *keyi)
142 {
143     memset(keyi, 0, sizeof(*keyi));
144     keyi->merge = MERGE_OVERRIDE;
145     keyi->name = xkb_atom_intern_literal(ctx, "*");
146     keyi->out_of_range_group_action = RANGE_WRAP;
147 }
148
149 static void
150 ClearKeyInfo(KeyInfo *keyi)
151 {
152     GroupInfo *groupi;
153     darray_foreach(groupi, keyi->groups)
154         ClearGroupInfo(groupi);
155     darray_free(keyi->groups);
156 }
157
158 /***====================================================================***/
159
160 typedef struct {
161     enum merge_mode merge;
162     bool haveSymbol;
163     xkb_mod_index_t modifier;
164     union {
165         xkb_atom_t keyName;
166         xkb_keysym_t keySym;
167     } u;
168 } ModMapEntry;
169
170 typedef struct {
171     char *name;         /* e.g. pc+us+inet(evdev) */
172     int errorCount;
173     enum merge_mode merge;
174     xkb_layout_index_t explicit_group;
175     darray(KeyInfo) keys;
176     KeyInfo default_key;
177     ActionsInfo *actions;
178     darray(xkb_atom_t) group_names;
179     darray(ModMapEntry) modmaps;
180     struct xkb_mod_set mods;
181
182     struct xkb_context *ctx;
183     /* Needed for AddKeySymbols. */
184     const struct xkb_keymap *keymap;
185 } SymbolsInfo;
186
187 static void
188 InitSymbolsInfo(SymbolsInfo *info, const struct xkb_keymap *keymap,
189                 ActionsInfo *actions, const struct xkb_mod_set *mods)
190 {
191     memset(info, 0, sizeof(*info));
192     info->ctx = keymap->ctx;
193     info->keymap = keymap;
194     info->merge = MERGE_OVERRIDE;
195     InitKeyInfo(keymap->ctx, &info->default_key);
196     info->actions = actions;
197     info->mods = *mods;
198     info->explicit_group = XKB_LAYOUT_INVALID;
199 }
200
201 static void
202 ClearSymbolsInfo(SymbolsInfo *info)
203 {
204     KeyInfo *keyi;
205     free(info->name);
206     darray_foreach(keyi, info->keys)
207         ClearKeyInfo(keyi);
208     darray_free(info->keys);
209     darray_free(info->group_names);
210     darray_free(info->modmaps);
211     ClearKeyInfo(&info->default_key);
212 }
213
214 static const char *
215 KeyInfoText(SymbolsInfo *info, KeyInfo *keyi)
216 {
217     return KeyNameText(info->ctx, keyi->name);
218 }
219
220 static bool
221 MergeGroups(SymbolsInfo *info, GroupInfo *into, GroupInfo *from, bool clobber,
222             bool report, xkb_layout_index_t group, xkb_atom_t key_name)
223 {
224     xkb_level_index_t i, levels_in_both;
225     struct xkb_level *level;
226
227     /* First find the type of the merged group. */
228     if (into->type != from->type) {
229         if (from->type == XKB_ATOM_NONE) {
230             /* it's empty for consistency with other comparisons */
231         }
232         else if (into->type == XKB_ATOM_NONE) {
233             into->type = from->type;
234         }
235         else {
236             xkb_atom_t use = (clobber ? from->type : into->type);
237             xkb_atom_t ignore = (clobber ? into->type : from->type);
238
239             if (report)
240                 log_warn(info->ctx,
241                          "Multiple definitions for group %d type of key %s; "
242                          "Using %s, ignoring %s\n",
243                          group + 1, KeyNameText(info->ctx, key_name),
244                          xkb_atom_text(info->ctx, use),
245                          xkb_atom_text(info->ctx, ignore));
246
247             into->type = use;
248         }
249     }
250     into->defined |= (from->defined & GROUP_FIELD_TYPE);
251
252     /* Now look at the levels. */
253
254     if (darray_empty(from->levels)) {
255         InitGroupInfo(from);
256         return true;
257     }
258
259     if (darray_empty(into->levels)) {
260         from->type = into->type;
261         *into = *from;
262         InitGroupInfo(from);
263         return true;
264     }
265
266     /* Merge the actions and syms. */
267     levels_in_both = MIN(darray_size(into->levels), darray_size(from->levels));
268     for (i = 0; i < levels_in_both; i++) {
269         struct xkb_level *intoLevel = &darray_item(into->levels, i);
270         struct xkb_level *fromLevel = &darray_item(from->levels, i);
271
272         if (fromLevel->action.type == ACTION_TYPE_NONE) {
273             /* it's empty for consistency with other comparisons */
274         }
275         else if (intoLevel->action.type == ACTION_TYPE_NONE) {
276             intoLevel->action = fromLevel->action;
277         }
278         else {
279             union xkb_action *use, *ignore;
280             use = (clobber ? &fromLevel->action : &intoLevel->action);
281             ignore = (clobber ? &intoLevel->action : &fromLevel->action);
282
283             if (report)
284                 log_warn(info->ctx,
285                          "Multiple actions for level %d/group %u on key %s; "
286                          "Using %s, ignoring %s\n",
287                          i + 1, group + 1, KeyNameText(info->ctx, key_name),
288                          ActionTypeText(use->type),
289                          ActionTypeText(ignore->type));
290
291             intoLevel->action = *use;
292         }
293
294         if (fromLevel->num_syms == 0) {
295             /* it's empty for consistency with other comparisons */
296         }
297         else if (intoLevel->num_syms == 0) {
298             intoLevel->num_syms = fromLevel->num_syms;
299             if (fromLevel->num_syms > 1)
300                 intoLevel->u.syms = fromLevel->u.syms;
301             else
302                 intoLevel->u.sym = fromLevel->u.sym;
303             fromLevel->num_syms = 0;
304         }
305         else if (!XkbLevelsSameSyms(fromLevel, intoLevel)) {
306             if (report)
307                 log_warn(info->ctx,
308                          "Multiple symbols for level %d/group %u on key %s; "
309                          "Using %s, ignoring %s\n",
310                          i + 1, group + 1, KeyNameText(info->ctx, key_name),
311                          (clobber ? "from" : "to"),
312                          (clobber ? "to" : "from"));
313
314             if (clobber) {
315                 ClearLevelInfo(intoLevel);
316                 intoLevel->num_syms = fromLevel->num_syms;
317                 if (fromLevel->num_syms > 1)
318                     intoLevel->u.syms = fromLevel->u.syms;
319                 else
320                     intoLevel->u.sym = fromLevel->u.sym;
321                 fromLevel->num_syms = 0;
322             }
323         }
324     }
325     /* If @from has extra levels, get them as well. */
326     darray_foreach_from(level, from->levels, levels_in_both) {
327         darray_append(into->levels, *level);
328         level->num_syms = 0;
329     }
330     into->defined |= (from->defined & GROUP_FIELD_ACTS);
331     into->defined |= (from->defined & GROUP_FIELD_SYMS);
332
333     return true;
334 }
335
336 static bool
337 UseNewKeyField(enum key_field field, enum key_field old, enum key_field new,
338                bool clobber, bool report, enum key_field *collide)
339 {
340     if (!(old & field))
341         return (new & field);
342
343     if (new & field) {
344         if (report)
345             *collide |= field;
346
347         if (clobber)
348             return true;
349     }
350
351     return false;
352 }
353
354 static bool
355 MergeKeys(SymbolsInfo *info, KeyInfo *into, KeyInfo *from, bool same_file)
356 {
357     xkb_layout_index_t i;
358     xkb_layout_index_t groups_in_both;
359     enum key_field collide = 0;
360     const int verbosity = xkb_context_get_log_verbosity(info->ctx);
361     const bool clobber = (from->merge != MERGE_AUGMENT);
362     const bool report = (same_file && verbosity > 0) || verbosity > 9;
363
364     if (from->merge == MERGE_REPLACE) {
365         ClearKeyInfo(into);
366         *into = *from;
367         InitKeyInfo(info->ctx, from);
368         return true;
369     }
370
371     groups_in_both = MIN(darray_size(into->groups), darray_size(from->groups));
372     for (i = 0; i < groups_in_both; i++)
373         MergeGroups(info,
374                     &darray_item(into->groups, i),
375                     &darray_item(from->groups, i),
376                     clobber, report, i, into->name);
377     /* If @from has extra groups, just move them to @into. */
378     for (i = groups_in_both; i < darray_size(from->groups); i++) {
379         darray_append(into->groups, darray_item(from->groups, i));
380         InitGroupInfo(&darray_item(from->groups, i));
381     }
382
383     if (UseNewKeyField(KEY_FIELD_VMODMAP, into->defined, from->defined,
384                        clobber, report, &collide)) {
385         into->vmodmap = from->vmodmap;
386         into->defined |= KEY_FIELD_VMODMAP;
387     }
388     if (UseNewKeyField(KEY_FIELD_REPEAT, into->defined, from->defined,
389                        clobber, report, &collide)) {
390         into->repeat = from->repeat;
391         into->defined |= KEY_FIELD_REPEAT;
392     }
393     if (UseNewKeyField(KEY_FIELD_DEFAULT_TYPE, into->defined, from->defined,
394                        clobber, report, &collide)) {
395         into->default_type = from->default_type;
396         into->defined |= KEY_FIELD_DEFAULT_TYPE;
397     }
398     if (UseNewKeyField(KEY_FIELD_GROUPINFO, into->defined, from->defined,
399                        clobber, report, &collide)) {
400         into->out_of_range_group_action = from->out_of_range_group_action;
401         into->out_of_range_group_number = from->out_of_range_group_number;
402         into->defined |= KEY_FIELD_GROUPINFO;
403     }
404
405     if (collide)
406         log_warn(info->ctx,
407                  "Symbol map for key %s redefined; "
408                  "Using %s definition for conflicting fields\n",
409                  KeyNameText(info->ctx, into->name),
410                  (clobber ? "first" : "last"));
411
412     ClearKeyInfo(from);
413     InitKeyInfo(info->ctx, from);
414     return true;
415 }
416
417 /* TODO: Make it so this function doesn't need the entire keymap. */
418 static bool
419 AddKeySymbols(SymbolsInfo *info, KeyInfo *keyi, bool same_file)
420 {
421     xkb_atom_t real_name;
422     KeyInfo *iter;
423
424     /*
425      * Don't keep aliases in the keys array; this guarantees that
426      * searching for keys to merge with by straight comparison (see the
427      * following loop) is enough, and we won't get multiple KeyInfo's
428      * for the same key because of aliases.
429      */
430     real_name = XkbResolveKeyAlias(info->keymap, keyi->name);
431     if (real_name != XKB_ATOM_NONE)
432         keyi->name = real_name;
433
434     darray_foreach(iter, info->keys)
435         if (iter->name == keyi->name)
436             return MergeKeys(info, iter, keyi, same_file);
437
438     darray_append(info->keys, *keyi);
439     InitKeyInfo(info->ctx, keyi);
440     return true;
441 }
442
443 static bool
444 AddModMapEntry(SymbolsInfo *info, ModMapEntry *new)
445 {
446     ModMapEntry *old;
447     bool clobber = (new->merge != MERGE_AUGMENT);
448
449     darray_foreach(old, info->modmaps) {
450         xkb_mod_index_t use, ignore;
451
452         if ((new->haveSymbol != old->haveSymbol) ||
453             (new->haveSymbol && new->u.keySym != old->u.keySym) ||
454             (!new->haveSymbol && new->u.keyName != old->u.keyName))
455             continue;
456
457         if (new->modifier == old->modifier)
458             return true;
459
460         use = (clobber ? new->modifier : old->modifier);
461         ignore = (clobber ? old->modifier : new->modifier);
462
463         if (new->haveSymbol)
464             log_err(info->ctx,
465                     "Symbol \"%s\" added to modifier map for multiple modifiers; "
466                     "Using %s, ignoring %s\n",
467                     KeysymText(info->ctx, new->u.keySym),
468                     ModIndexText(info->ctx, &info->mods, use),
469                     ModIndexText(info->ctx, &info->mods, ignore));
470         else
471             log_err(info->ctx,
472                     "Key \"%s\" added to modifier map for multiple modifiers; "
473                     "Using %s, ignoring %s\n",
474                     KeyNameText(info->ctx, new->u.keyName),
475                     ModIndexText(info->ctx, &info->mods, use),
476                     ModIndexText(info->ctx, &info->mods, ignore));
477
478         old->modifier = use;
479         return true;
480     }
481
482     darray_append(info->modmaps, *new);
483     return true;
484 }
485
486 /***====================================================================***/
487
488 static void
489 MergeIncludedSymbols(SymbolsInfo *into, SymbolsInfo *from,
490                      enum merge_mode merge)
491 {
492     xkb_atom_t *group_name;
493     xkb_layout_index_t group_names_in_both;
494
495     if (from->errorCount > 0) {
496         into->errorCount += from->errorCount;
497         return;
498     }
499
500     into->mods = from->mods;
501
502     if (into->name == NULL) {
503         into->name = from->name;
504         from->name = NULL;
505     }
506
507     group_names_in_both = MIN(darray_size(into->group_names),
508                               darray_size(from->group_names));
509     for (xkb_layout_index_t i = 0; i < group_names_in_both; i++) {
510         if (!darray_item(from->group_names, i))
511             continue;
512
513         if (merge == MERGE_AUGMENT && darray_item(into->group_names, i))
514             continue;
515
516         darray_item(into->group_names, i) = darray_item(from->group_names, i);
517     }
518     /* If @from has more, get them as well. */
519     darray_foreach_from(group_name, from->group_names, group_names_in_both)
520         darray_append(into->group_names, *group_name);
521
522     if (darray_empty(into->keys)) {
523         into->keys = from->keys;
524         darray_init(from->keys);
525     }
526     else {
527         KeyInfo *keyi;
528         darray_foreach(keyi, from->keys) {
529             keyi->merge = (merge == MERGE_DEFAULT ? keyi->merge : merge);
530             if (!AddKeySymbols(into, keyi, false))
531                 into->errorCount++;
532         }
533     }
534
535     if (darray_empty(into->modmaps)) {
536         into->modmaps = from->modmaps;
537         darray_init(from->modmaps);
538     }
539     else {
540         ModMapEntry *mm;
541         darray_foreach(mm, from->modmaps) {
542             mm->merge = (merge == MERGE_DEFAULT ? mm->merge : merge);
543             if (!AddModMapEntry(into, mm))
544                 into->errorCount++;
545         }
546     }
547 }
548
549 static void
550 HandleSymbolsFile(SymbolsInfo *info, XkbFile *file, enum merge_mode merge);
551
552 static bool
553 HandleIncludeSymbols(SymbolsInfo *info, IncludeStmt *include)
554 {
555     SymbolsInfo included;
556
557     InitSymbolsInfo(&included, info->keymap, info->actions, &info->mods);
558     included.name = include->stmt;
559     include->stmt = NULL;
560
561     for (IncludeStmt *stmt = include; stmt; stmt = stmt->next_incl) {
562         SymbolsInfo next_incl;
563         XkbFile *file;
564
565         file = ProcessIncludeFile(info->ctx, stmt, FILE_TYPE_SYMBOLS);
566         if (!file) {
567             info->errorCount += 10;
568             ClearSymbolsInfo(&included);
569             return false;
570         }
571
572         InitSymbolsInfo(&next_incl, info->keymap, info->actions,
573                         &included.mods);
574         if (stmt->modifier) {
575             next_incl.explicit_group = atoi(stmt->modifier) - 1;
576             if (next_incl.explicit_group >= XKB_MAX_GROUPS) {
577                 log_err(info->ctx,
578                         "Cannot set explicit group to %d - must be between 1..%d; "
579                         "Ignoring group number\n",
580                         next_incl.explicit_group + 1, XKB_MAX_GROUPS);
581                 next_incl.explicit_group = info->explicit_group;
582             }
583         }
584         else {
585             next_incl.explicit_group = info->explicit_group;
586         }
587
588         HandleSymbolsFile(&next_incl, file, MERGE_OVERRIDE);
589
590         MergeIncludedSymbols(&included, &next_incl, stmt->merge);
591
592         ClearSymbolsInfo(&next_incl);
593         FreeXkbFile(file);
594     }
595
596     MergeIncludedSymbols(info, &included, include->merge);
597     ClearSymbolsInfo(&included);
598
599     return (info->errorCount == 0);
600 }
601
602 #define SYMBOLS 1
603 #define ACTIONS 2
604
605 static bool
606 GetGroupIndex(SymbolsInfo *info, KeyInfo *keyi, ExprDef *arrayNdx,
607               unsigned what, xkb_layout_index_t *ndx_rtrn)
608 {
609     const char *name = (what == SYMBOLS ? "symbols" : "actions");
610
611     if (arrayNdx == NULL) {
612         xkb_layout_index_t i;
613         GroupInfo *groupi;
614         enum group_field field = (what == SYMBOLS ?
615                                   GROUP_FIELD_SYMS : GROUP_FIELD_ACTS);
616
617         darray_enumerate(i, groupi, keyi->groups) {
618             if (!(groupi->defined & field)) {
619                 *ndx_rtrn = i;
620                 return true;
621             }
622         }
623
624         if (i >= XKB_MAX_GROUPS) {
625             log_err(info->ctx,
626                     "Too many groups of %s for key %s (max %u); "
627                     "Ignoring %s defined for extra groups\n",
628                     name, KeyInfoText(info, keyi), XKB_MAX_GROUPS, name);
629             return false;
630         }
631
632         darray_resize0(keyi->groups, darray_size(keyi->groups) + 1);
633         *ndx_rtrn = darray_size(keyi->groups) - 1;
634         return true;
635     }
636
637     if (!ExprResolveGroup(info->ctx, arrayNdx, ndx_rtrn)) {
638         log_err(info->ctx,
639                 "Illegal group index for %s of key %s\n"
640                 "Definition with non-integer array index ignored\n",
641                 name, KeyInfoText(info, keyi));
642         return false;
643     }
644
645     (*ndx_rtrn)--;
646     if (*ndx_rtrn >= darray_size(keyi->groups))
647         darray_resize0(keyi->groups, *ndx_rtrn + 1);
648
649     return true;
650 }
651
652 static bool
653 AddSymbolsToKey(SymbolsInfo *info, KeyInfo *keyi, ExprDef *arrayNdx,
654                 ExprDef *value)
655 {
656     xkb_layout_index_t ndx;
657     GroupInfo *groupi;
658     xkb_level_index_t nLevels;
659
660     if (!GetGroupIndex(info, keyi, arrayNdx, SYMBOLS, &ndx))
661         return false;
662
663     groupi = &darray_item(keyi->groups, ndx);
664
665     if (value == NULL) {
666         groupi->defined |= GROUP_FIELD_SYMS;
667         return true;
668     }
669
670     if (value->expr.op != EXPR_KEYSYM_LIST) {
671         log_err(info->ctx,
672                 "Expected a list of symbols, found %s; "
673                 "Ignoring symbols for group %u of %s\n",
674                 expr_op_type_to_string(value->expr.op), ndx + 1,
675                 KeyInfoText(info, keyi));
676         return false;
677     }
678
679     if (groupi->defined & GROUP_FIELD_SYMS) {
680         log_err(info->ctx,
681                 "Symbols for key %s, group %u already defined; "
682                 "Ignoring duplicate definition\n",
683                 KeyInfoText(info, keyi), ndx + 1);
684         return false;
685     }
686
687     nLevels = darray_size(value->keysym_list.symsMapIndex);
688     if (darray_size(groupi->levels) < nLevels)
689         darray_resize0(groupi->levels, nLevels);
690
691     groupi->defined |= GROUP_FIELD_SYMS;
692
693     for (xkb_level_index_t i = 0; i < nLevels; i++) {
694         unsigned int sym_index;
695         struct xkb_level *leveli = &darray_item(groupi->levels, i);
696
697         sym_index = darray_item(value->keysym_list.symsMapIndex, i);
698         leveli->num_syms = darray_item(value->keysym_list.symsNumEntries, i);
699         if (leveli->num_syms > 1)
700             leveli->u.syms = calloc(leveli->num_syms, sizeof(*leveli->u.syms));
701
702         for (unsigned j = 0; j < leveli->num_syms; j++) {
703             xkb_keysym_t keysym = darray_item(value->keysym_list.syms,
704                                               sym_index + j);
705
706             if (leveli->num_syms == 1) {
707                 if (keysym == XKB_KEY_NoSymbol)
708                     leveli->num_syms = 0;
709                 else
710                     leveli->u.sym = keysym;
711             }
712             else if (leveli->num_syms > 1) {
713                 leveli->u.syms[j] = keysym;
714             }
715         }
716     }
717
718     return true;
719 }
720
721 static bool
722 AddActionsToKey(SymbolsInfo *info, KeyInfo *keyi, ExprDef *arrayNdx,
723                 ExprDef *value)
724 {
725     xkb_layout_index_t ndx;
726     GroupInfo *groupi;
727     unsigned int nActs;
728     ExprDef *act;
729
730     if (!GetGroupIndex(info, keyi, arrayNdx, ACTIONS, &ndx))
731         return false;
732
733     groupi = &darray_item(keyi->groups, ndx);
734
735     if (value == NULL) {
736         groupi->defined |= GROUP_FIELD_ACTS;
737         return true;
738     }
739
740     if (value->expr.op != EXPR_ACTION_LIST) {
741         log_wsgo(info->ctx,
742                  "Bad expression type (%d) for action list value; "
743                  "Ignoring actions for group %u of %s\n",
744                  value->expr.op, ndx, KeyInfoText(info, keyi));
745         return false;
746     }
747
748     if (groupi->defined & GROUP_FIELD_ACTS) {
749         log_wsgo(info->ctx,
750                  "Actions for key %s, group %u already defined\n",
751                  KeyInfoText(info, keyi), ndx);
752         return false;
753     }
754
755     nActs = 0;
756     for (act = value->actions.actions; act; act = (ExprDef *) act->common.next)
757         nActs++;
758
759     if (darray_size(groupi->levels) < nActs)
760         darray_resize0(groupi->levels, nActs);
761
762     groupi->defined |= GROUP_FIELD_ACTS;
763
764     act = value->actions.actions;
765     for (unsigned i = 0; i < nActs; i++) {
766         union xkb_action *toAct = &darray_item(groupi->levels, i).action;
767
768         if (!HandleActionDef(info->ctx, info->actions, &info->mods, act, toAct))
769             log_err(info->ctx,
770                     "Illegal action definition for %s; "
771                     "Action for group %u/level %u ignored\n",
772                     KeyInfoText(info, keyi), ndx + 1, i + 1);
773
774         act = (ExprDef *) act->common.next;
775     }
776
777     return true;
778 }
779
780 static const LookupEntry repeatEntries[] = {
781     { "true", KEY_REPEAT_YES },
782     { "yes", KEY_REPEAT_YES },
783     { "on", KEY_REPEAT_YES },
784     { "false", KEY_REPEAT_NO },
785     { "no", KEY_REPEAT_NO },
786     { "off", KEY_REPEAT_NO },
787     { "default", KEY_REPEAT_UNDEFINED },
788     { NULL, 0 }
789 };
790
791 static bool
792 SetSymbolsField(SymbolsInfo *info, KeyInfo *keyi, const char *field,
793                 ExprDef *arrayNdx, ExprDef *value)
794 {
795     if (istreq(field, "type")) {
796         xkb_layout_index_t ndx;
797         xkb_atom_t val;
798
799         if (!ExprResolveString(info->ctx, value, &val)) {
800             log_err(info->ctx,
801                     "The type field of a key symbol map must be a string; "
802                     "Ignoring illegal type definition\n");
803             return false;
804         }
805
806         if (!arrayNdx) {
807             keyi->default_type = val;
808             keyi->defined |= KEY_FIELD_DEFAULT_TYPE;
809         }
810         else if (!ExprResolveGroup(info->ctx, arrayNdx, &ndx)) {
811             log_err(info->ctx,
812                     "Illegal group index for type of key %s; "
813                     "Definition with non-integer array index ignored\n",
814                     KeyInfoText(info, keyi));
815             return false;
816         }
817         else {
818             ndx--;
819             if (ndx >= darray_size(keyi->groups))
820                 darray_resize0(keyi->groups, ndx + 1);
821             darray_item(keyi->groups, ndx).type = val;
822             darray_item(keyi->groups, ndx).defined |= GROUP_FIELD_TYPE;
823         }
824     }
825     else if (istreq(field, "symbols")) {
826         return AddSymbolsToKey(info, keyi, arrayNdx, value);
827     }
828     else if (istreq(field, "actions")) {
829         return AddActionsToKey(info, keyi, arrayNdx, value);
830     }
831     else if (istreq(field, "vmods") ||
832              istreq(field, "virtualmods") ||
833              istreq(field, "virtualmodifiers")) {
834         xkb_mod_mask_t mask;
835
836         if (!ExprResolveModMask(info->ctx, value, MOD_VIRT, &info->mods,
837                                 &mask)) {
838             log_err(info->ctx,
839                     "Expected a virtual modifier mask, found %s; "
840                     "Ignoring virtual modifiers definition for key %s\n",
841                     expr_op_type_to_string(value->expr.op),
842                     KeyInfoText(info, keyi));
843             return false;
844         }
845
846         keyi->vmodmap = mask;
847         keyi->defined |= KEY_FIELD_VMODMAP;
848     }
849     else if (istreq(field, "locking") ||
850              istreq(field, "lock") ||
851              istreq(field, "locks")) {
852         log_vrb(info->ctx, 1,
853                 "Key behaviors not supported; "
854                 "Ignoring locking specification for key %s\n",
855                 KeyInfoText(info, keyi));
856     }
857     else if (istreq(field, "radiogroup") ||
858              istreq(field, "permanentradiogroup") ||
859              istreq(field, "allownone")) {
860         log_vrb(info->ctx, 1,
861                 "Radio groups not supported; "
862                 "Ignoring radio group specification for key %s\n",
863                 KeyInfoText(info, keyi));
864     }
865     else if (istreq_prefix("overlay", field) ||
866              istreq_prefix("permanentoverlay", field)) {
867         log_vrb(info->ctx, 1,
868                 "Overlays not supported; "
869                 "Ignoring overlay specification for key %s\n",
870                 KeyInfoText(info, keyi));
871     }
872     else if (istreq(field, "repeating") ||
873              istreq(field, "repeats") ||
874              istreq(field, "repeat")) {
875         unsigned int val;
876
877         if (!ExprResolveEnum(info->ctx, value, &val, repeatEntries)) {
878             log_err(info->ctx,
879                     "Illegal repeat setting for %s; "
880                     "Non-boolean repeat setting ignored\n",
881                     KeyInfoText(info, keyi));
882             return false;
883         }
884
885         keyi->repeat = val;
886         keyi->defined |= KEY_FIELD_REPEAT;
887     }
888     else if (istreq(field, "groupswrap") ||
889              istreq(field, "wrapgroups")) {
890         bool set;
891
892         if (!ExprResolveBoolean(info->ctx, value, &set)) {
893             log_err(info->ctx,
894                     "Illegal groupsWrap setting for %s; "
895                     "Non-boolean value ignored\n",
896                     KeyInfoText(info, keyi));
897             return false;
898         }
899
900         keyi->out_of_range_group_action = (set ? RANGE_WRAP : RANGE_SATURATE);
901         keyi->defined |= KEY_FIELD_GROUPINFO;
902     }
903     else if (istreq(field, "groupsclamp") ||
904              istreq(field, "clampgroups")) {
905         bool set;
906
907         if (!ExprResolveBoolean(info->ctx, value, &set)) {
908             log_err(info->ctx,
909                     "Illegal groupsClamp setting for %s; "
910                     "Non-boolean value ignored\n",
911                     KeyInfoText(info, keyi));
912             return false;
913         }
914
915         keyi->out_of_range_group_action = (set ? RANGE_SATURATE : RANGE_WRAP);
916         keyi->defined |= KEY_FIELD_GROUPINFO;
917     }
918     else if (istreq(field, "groupsredirect") ||
919              istreq(field, "redirectgroups")) {
920         xkb_layout_index_t grp;
921
922         if (!ExprResolveGroup(info->ctx, value, &grp)) {
923             log_err(info->ctx,
924                     "Illegal group index for redirect of key %s; "
925                     "Definition with non-integer group ignored\n",
926                     KeyInfoText(info, keyi));
927             return false;
928         }
929
930         keyi->out_of_range_group_action = RANGE_REDIRECT;
931         keyi->out_of_range_group_number = grp - 1;
932         keyi->defined |= KEY_FIELD_GROUPINFO;
933     }
934     else {
935         log_err(info->ctx,
936                 "Unknown field %s in a symbol interpretation; "
937                 "Definition ignored\n",
938                 field);
939         return false;
940     }
941
942     return true;
943 }
944
945 static bool
946 SetGroupName(SymbolsInfo *info, ExprDef *arrayNdx, ExprDef *value)
947 {
948     xkb_layout_index_t group, group_to_use;
949     xkb_atom_t name;
950
951     if (!arrayNdx) {
952         log_vrb(info->ctx, 1,
953                 "You must specify an index when specifying a group name; "
954                 "Group name definition without array subscript ignored\n");
955         return false;
956     }
957
958     if (!ExprResolveGroup(info->ctx, arrayNdx, &group)) {
959         log_err(info->ctx,
960                 "Illegal index in group name definition; "
961                 "Definition with non-integer array index ignored\n");
962         return false;
963     }
964
965     if (!ExprResolveString(info->ctx, value, &name)) {
966         log_err(info->ctx,
967                 "Group name must be a string; "
968                 "Illegal name for group %d ignored\n", group);
969         return false;
970     }
971
972     if (info->explicit_group == XKB_LAYOUT_INVALID) {
973         group_to_use = group - 1;
974     }
975     else if (group - 1 == 0) {
976         group_to_use = info->explicit_group;
977     }
978     else {
979         log_warn(info->ctx,
980                  "An explicit group was specified for the '%s' map, "
981                  "but it provides a name for a group other than Group1 (%d); "
982                  "Ignoring group name '%s'\n",
983                  info->name, group,
984                  xkb_atom_text(info->ctx, name));
985         return false;
986     }
987
988     if (group_to_use >= darray_size(info->group_names))
989         darray_resize0(info->group_names, group_to_use + 1);
990     darray_item(info->group_names, group_to_use) = name;
991
992     return true;
993 }
994
995 static bool
996 HandleGlobalVar(SymbolsInfo *info, VarDef *stmt)
997 {
998     const char *elem, *field;
999     ExprDef *arrayNdx;
1000     bool ret;
1001
1002     if (!ExprResolveLhs(info->ctx, stmt->name, &elem, &field, &arrayNdx))
1003         return false;
1004
1005     if (elem && istreq(elem, "key")) {
1006         ret = SetSymbolsField(info, &info->default_key, field, arrayNdx,
1007                               stmt->value);
1008     }
1009     else if (!elem && (istreq(field, "name") ||
1010                        istreq(field, "groupname"))) {
1011         ret = SetGroupName(info, arrayNdx, stmt->value);
1012     }
1013     else if (!elem && (istreq(field, "groupswrap") ||
1014                        istreq(field, "wrapgroups"))) {
1015         log_err(info->ctx,
1016                 "Global \"groupswrap\" not supported; Ignored\n");
1017         ret = true;
1018     }
1019     else if (!elem && (istreq(field, "groupsclamp") ||
1020                        istreq(field, "clampgroups"))) {
1021         log_err(info->ctx,
1022                 "Global \"groupsclamp\" not supported; Ignored\n");
1023         ret = true;
1024     }
1025     else if (!elem && (istreq(field, "groupsredirect") ||
1026                        istreq(field, "redirectgroups"))) {
1027         log_err(info->ctx,
1028                 "Global \"groupsredirect\" not supported; Ignored\n");
1029         ret = true;
1030     }
1031     else if (!elem && istreq(field, "allownone")) {
1032         log_err(info->ctx,
1033                 "Radio groups not supported; "
1034                 "Ignoring \"allownone\" specification\n");
1035         ret = true;
1036     }
1037     else {
1038         ret = SetActionField(info->ctx, info->actions, &info->mods,
1039                              elem, field, arrayNdx, stmt->value);
1040     }
1041
1042     return ret;
1043 }
1044
1045 static bool
1046 HandleSymbolsBody(SymbolsInfo *info, VarDef *def, KeyInfo *keyi)
1047 {
1048     bool ok = true;
1049     const char *elem, *field;
1050     ExprDef *arrayNdx;
1051
1052     for (; def; def = (VarDef *) def->common.next) {
1053         if (def->name && def->name->expr.op == EXPR_FIELD_REF) {
1054             log_err(info->ctx,
1055                     "Cannot set a global default value from within a key statement; "
1056                     "Move statements to the global file scope\n");
1057             continue;
1058         }
1059
1060         if (!def->name) {
1061             if (!def->value || def->value->expr.op == EXPR_KEYSYM_LIST)
1062                 field = "symbols";
1063             else
1064                 field = "actions";
1065             arrayNdx = NULL;
1066         }
1067         else {
1068             ok = ExprResolveLhs(info->ctx, def->name, &elem, &field,
1069                                 &arrayNdx);
1070         }
1071
1072         if (ok)
1073             ok = SetSymbolsField(info, keyi, field, arrayNdx, def->value);
1074     }
1075
1076     return ok;
1077 }
1078
1079 static bool
1080 SetExplicitGroup(SymbolsInfo *info, KeyInfo *keyi)
1081 {
1082     xkb_layout_index_t i;
1083     GroupInfo *groupi;
1084     bool warn = false;
1085
1086     if (info->explicit_group == XKB_LAYOUT_INVALID)
1087         return true;
1088
1089     darray_enumerate_from(i, groupi, keyi->groups, 1) {
1090         if (groupi->defined) {
1091             warn = true;
1092             ClearGroupInfo(groupi);
1093             InitGroupInfo(groupi);
1094         }
1095     }
1096
1097     if (warn)
1098         log_warn(info->ctx,
1099                  "For the map %s an explicit group specified, "
1100                  "but key %s has more than one group defined; "
1101                  "All groups except first one will be ignored\n",
1102                  info->name, KeyInfoText(info, keyi));
1103
1104     darray_resize0(keyi->groups, info->explicit_group + 1);
1105     if (info->explicit_group > 0) {
1106         darray_item(keyi->groups, info->explicit_group) =
1107             darray_item(keyi->groups, 0);
1108         InitGroupInfo(&darray_item(keyi->groups, 0));
1109     }
1110
1111     return true;
1112 }
1113
1114 static bool
1115 HandleSymbolsDef(SymbolsInfo *info, SymbolsDef *stmt)
1116 {
1117     KeyInfo keyi;
1118
1119     keyi = info->default_key;
1120     darray_init(keyi.groups);
1121     darray_copy(keyi.groups, info->default_key.groups);
1122     for (xkb_layout_index_t i = 0; i < darray_size(keyi.groups); i++)
1123         CopyGroupInfo(&darray_item(keyi.groups, i),
1124                       &darray_item(info->default_key.groups, i));
1125     keyi.merge = stmt->merge;
1126     keyi.name = stmt->keyName;
1127
1128     if (!HandleSymbolsBody(info, stmt->symbols, &keyi)) {
1129         info->errorCount++;
1130         return false;
1131     }
1132
1133     if (!SetExplicitGroup(info, &keyi)) {
1134         info->errorCount++;
1135         return false;
1136     }
1137
1138     if (!AddKeySymbols(info, &keyi, true)) {
1139         info->errorCount++;
1140         return false;
1141     }
1142
1143     return true;
1144 }
1145
1146 static bool
1147 HandleModMapDef(SymbolsInfo *info, ModMapDef *def)
1148 {
1149     ModMapEntry tmp;
1150     xkb_mod_index_t ndx;
1151     bool ok;
1152     struct xkb_context *ctx = info->ctx;
1153
1154     ndx = XkbModNameToIndex(&info->mods, def->modifier, MOD_REAL);
1155     if (ndx == XKB_MOD_INVALID) {
1156         log_err(info->ctx,
1157                 "Illegal modifier map definition; "
1158                 "Ignoring map for non-modifier \"%s\"\n",
1159                 xkb_atom_text(ctx, def->modifier));
1160         return false;
1161     }
1162
1163     ok = true;
1164     tmp.modifier = ndx;
1165     tmp.merge = def->merge;
1166
1167     for (ExprDef *key = def->keys; key; key = (ExprDef *) key->common.next) {
1168         xkb_keysym_t sym;
1169
1170         if (key->expr.op == EXPR_VALUE &&
1171             key->expr.value_type == EXPR_TYPE_KEYNAME) {
1172             tmp.haveSymbol = false;
1173             tmp.u.keyName = key->key_name.key_name;
1174         }
1175         else if (ExprResolveKeySym(ctx, key, &sym)) {
1176             tmp.haveSymbol = true;
1177             tmp.u.keySym = sym;
1178         }
1179         else {
1180             log_err(info->ctx,
1181                     "Modmap entries may contain only key names or keysyms; "
1182                     "Illegal definition for %s modifier ignored\n",
1183                     ModIndexText(info->ctx, &info->mods, tmp.modifier));
1184             continue;
1185         }
1186
1187         ok = AddModMapEntry(info, &tmp) && ok;
1188     }
1189     return ok;
1190 }
1191
1192 static void
1193 HandleSymbolsFile(SymbolsInfo *info, XkbFile *file, enum merge_mode merge)
1194 {
1195     bool ok;
1196
1197     free(info->name);
1198     info->name = strdup_safe(file->name);
1199
1200     for (ParseCommon *stmt = file->defs; stmt; stmt = stmt->next) {
1201         switch (stmt->type) {
1202         case STMT_INCLUDE:
1203             ok = HandleIncludeSymbols(info, (IncludeStmt *) stmt);
1204             break;
1205         case STMT_SYMBOLS:
1206             ok = HandleSymbolsDef(info, (SymbolsDef *) stmt);
1207             break;
1208         case STMT_VAR:
1209             ok = HandleGlobalVar(info, (VarDef *) stmt);
1210             break;
1211         case STMT_VMOD:
1212             ok = HandleVModDef(info->ctx, &info->mods, (VModDef *) stmt, merge);
1213             break;
1214         case STMT_MODMAP:
1215             ok = HandleModMapDef(info, (ModMapDef *) stmt);
1216             break;
1217         default:
1218             log_err(info->ctx,
1219                     "Symbols files may not include other types; "
1220                     "Ignoring %s\n", stmt_type_to_string(stmt->type));
1221             ok = false;
1222             break;
1223         }
1224
1225         if (!ok)
1226             info->errorCount++;
1227
1228         if (info->errorCount > 10) {
1229             log_err(info->ctx, "Abandoning symbols file \"%s\"\n",
1230                     file->name);
1231             break;
1232         }
1233     }
1234 }
1235
1236 /**
1237  * Given a keysym @sym, return a key which generates it, or NULL.
1238  * This is used for example in a modifier map definition, such as:
1239  *      modifier_map Lock           { Caps_Lock };
1240  * where we want to add the Lock modifier to the modmap of the key
1241  * which matches the keysym Caps_Lock.
1242  * Since there can be many keys which generates the keysym, the key
1243  * is chosen first by lowest group in which the keysym appears, than
1244  * by lowest level and than by lowest key code.
1245  */
1246 static struct xkb_key *
1247 FindKeyForSymbol(struct xkb_keymap *keymap, xkb_keysym_t sym)
1248 {
1249     struct xkb_key *key;
1250     xkb_layout_index_t group;
1251     bool got_one_group, got_one_level;
1252
1253     group = 0;
1254     do {
1255         xkb_level_index_t level = 0;
1256         got_one_group = false;
1257         do {
1258             got_one_level = false;
1259             xkb_keys_foreach(key, keymap) {
1260                 if (group < key->num_groups &&
1261                     level < XkbKeyNumLevels(key, group)) {
1262                     got_one_group = got_one_level = true;
1263                     if (key->groups[group].levels[level].num_syms == 1 &&
1264                         key->groups[group].levels[level].u.sym == sym)
1265                         return key;
1266                 }
1267             }
1268             level++;
1269         } while (got_one_level);
1270         group++;
1271     } while (got_one_group);
1272
1273     return NULL;
1274 }
1275
1276 /*
1277  * Find an appropriate type for a group and return its name.
1278  *
1279  * Simple recipe:
1280  * - ONE_LEVEL for width 0/1
1281  * - ALPHABETIC for 2 shift levels, with lower/upercase keysyms
1282  * - KEYPAD for keypad keys.
1283  * - TWO_LEVEL for other 2 shift level keys.
1284  * and the same for four level keys.
1285  *
1286  * FIXME: Decide how to handle multiple-syms-per-level, and do it.
1287  */
1288 static xkb_atom_t
1289 FindAutomaticType(struct xkb_context *ctx, GroupInfo *groupi)
1290 {
1291     xkb_keysym_t sym0, sym1;
1292     const xkb_level_index_t width = darray_size(groupi->levels);
1293
1294 #define GET_SYM(level) \
1295     (darray_item(groupi->levels, level).num_syms == 0 ? \
1296         XKB_KEY_NoSymbol : \
1297      darray_item(groupi->levels, level).num_syms == 1 ? \
1298         darray_item(groupi->levels, level).u.sym : \
1299      /* num_syms > 1 */ \
1300         darray_item(groupi->levels, level).u.syms[0])
1301
1302     if (width == 1 || width <= 0)
1303         return xkb_atom_intern_literal(ctx, "ONE_LEVEL");
1304
1305     sym0 = GET_SYM(0);
1306     sym1 = GET_SYM(1);
1307
1308     if (width == 2) {
1309         if (xkb_keysym_is_lower(sym0) && xkb_keysym_is_upper(sym1))
1310             return xkb_atom_intern_literal(ctx, "ALPHABETIC");
1311
1312         if (xkb_keysym_is_keypad(sym0) || xkb_keysym_is_keypad(sym1))
1313             return xkb_atom_intern_literal(ctx, "KEYPAD");
1314
1315         return xkb_atom_intern_literal(ctx, "TWO_LEVEL");
1316     }
1317
1318     if (width <= 4) {
1319         if (xkb_keysym_is_lower(sym0) && xkb_keysym_is_upper(sym1)) {
1320             xkb_keysym_t sym2, sym3;
1321             sym2 = GET_SYM(2);
1322             sym3 = (width == 4 ? GET_SYM(3) : XKB_KEY_NoSymbol);
1323
1324             if (xkb_keysym_is_lower(sym2) && xkb_keysym_is_upper(sym3))
1325                 return xkb_atom_intern_literal(ctx, "FOUR_LEVEL_ALPHABETIC");
1326
1327             return xkb_atom_intern_literal(ctx, "FOUR_LEVEL_SEMIALPHABETIC");
1328         }
1329
1330         if (xkb_keysym_is_keypad(sym0) || xkb_keysym_is_keypad(sym1))
1331             return xkb_atom_intern_literal(ctx, "FOUR_LEVEL_KEYPAD");
1332
1333         return xkb_atom_intern_literal(ctx, "FOUR_LEVEL");
1334     }
1335
1336     return XKB_ATOM_NONE;
1337
1338 #undef GET_SYM
1339 }
1340
1341 static const struct xkb_key_type *
1342 FindTypeForGroup(struct xkb_keymap *keymap, KeyInfo *keyi,
1343                  xkb_layout_index_t group, bool *explicit_type)
1344 {
1345     unsigned int i;
1346     GroupInfo *groupi = &darray_item(keyi->groups, group);
1347     xkb_atom_t type_name = groupi->type;
1348
1349     *explicit_type = true;
1350
1351     if (type_name == XKB_ATOM_NONE) {
1352         if (keyi->default_type != XKB_ATOM_NONE) {
1353             type_name  = keyi->default_type;
1354         }
1355         else {
1356             type_name = FindAutomaticType(keymap->ctx, groupi);
1357             if (type_name != XKB_ATOM_NONE)
1358                 *explicit_type = false;
1359         }
1360     }
1361
1362     if (type_name == XKB_ATOM_NONE) {
1363         log_warn(keymap->ctx,
1364                  "Couldn't find an automatic type for key '%s' group %d with %lu levels; "
1365                  "Using the default type\n",
1366                  KeyNameText(keymap->ctx, keyi->name), group + 1,
1367                  (unsigned long) darray_size(groupi->levels));
1368         goto use_default;
1369     }
1370
1371     for (i = 0; i < keymap->num_types; i++)
1372         if (keymap->types[i].name == type_name)
1373             break;
1374
1375     if (i >= keymap->num_types) {
1376         log_warn(keymap->ctx,
1377                  "The type \"%s\" for key '%s' group %d was not previously defined; "
1378                  "Using the default type\n",
1379                  xkb_atom_text(keymap->ctx, type_name),
1380                  KeyNameText(keymap->ctx, keyi->name), group + 1);
1381         goto use_default;
1382     }
1383
1384     return &keymap->types[i];
1385
1386 use_default:
1387     /*
1388      * Index 0 is guaranteed to contain something, usually
1389      * ONE_LEVEL or at least some default one-level type.
1390      */
1391     return &keymap->types[0];
1392 }
1393
1394 static bool
1395 CopySymbolsDefToKeymap(struct xkb_keymap *keymap, SymbolsInfo *info,
1396                        KeyInfo *keyi)
1397 {
1398     struct xkb_key *key;
1399     GroupInfo *groupi;
1400     const GroupInfo *group0;
1401     xkb_layout_index_t i;
1402
1403     /*
1404      * The name is guaranteed to be real and not an alias (see
1405      * AddKeySymbols), so 'false' is safe here.
1406      */
1407     key = XkbKeyByName(keymap, keyi->name, false);
1408     if (!key) {
1409         log_vrb(info->ctx, 5,
1410                 "Key %s not found in keycodes; Symbols ignored\n",
1411                 KeyInfoText(info, keyi));
1412         return false;
1413     }
1414
1415     /* Find the range of groups we need. */
1416     key->num_groups = 0;
1417     darray_enumerate(i, groupi, keyi->groups)
1418         if (groupi->defined)
1419             key->num_groups = i + 1;
1420
1421     if (key->num_groups <= 0)
1422         return false; /* WSGO */
1423
1424     darray_resize(keyi->groups, key->num_groups);
1425
1426     /*
1427      * If there are empty groups between non-empty ones, fill them with data
1428      * from the first group.
1429      * We can make a wrong assumption here. But leaving gaps is worse.
1430      */
1431     group0 = &darray_item(keyi->groups, 0);
1432     darray_foreach_from(groupi, keyi->groups, 1) {
1433         if (groupi->defined)
1434             continue;
1435
1436         CopyGroupInfo(groupi, group0);
1437     }
1438
1439     key->groups = calloc(key->num_groups, sizeof(*key->groups));
1440
1441     /* Find and assign the groups' types in the keymap. */
1442     darray_enumerate(i, groupi, keyi->groups) {
1443         const struct xkb_key_type *type;
1444         bool explicit_type;
1445
1446         type = FindTypeForGroup(keymap, keyi, i, &explicit_type);
1447
1448         /* Always have as many levels as the type specifies. */
1449         if (type->num_levels < darray_size(groupi->levels)) {
1450             struct xkb_level *leveli;
1451
1452             log_vrb(info->ctx, 1,
1453                     "Type \"%s\" has %d levels, but %s has %d levels; "
1454                     "Ignoring extra symbols\n",
1455                     xkb_atom_text(keymap->ctx, type->name), type->num_levels,
1456                     KeyInfoText(info, keyi),
1457                     (int) darray_size(groupi->levels));
1458
1459             darray_foreach_from(leveli, groupi->levels, type->num_levels)
1460                 ClearLevelInfo(leveli);
1461         }
1462         darray_resize0(groupi->levels, type->num_levels);
1463
1464         key->groups[i].explicit_type = explicit_type;
1465         key->groups[i].type = type;
1466     }
1467
1468     /* Copy levels. */
1469     darray_enumerate(i, groupi, keyi->groups)
1470         darray_steal(groupi->levels, &key->groups[i].levels, NULL);
1471
1472     key->out_of_range_group_number = keyi->out_of_range_group_number;
1473     key->out_of_range_group_action = keyi->out_of_range_group_action;
1474
1475     if (keyi->defined & KEY_FIELD_VMODMAP) {
1476         key->vmodmap = keyi->vmodmap;
1477         key->explicit |= EXPLICIT_VMODMAP;
1478     }
1479
1480     if (keyi->repeat != KEY_REPEAT_UNDEFINED) {
1481         key->repeats = (keyi->repeat == KEY_REPEAT_YES);
1482         key->explicit |= EXPLICIT_REPEAT;
1483     }
1484
1485     darray_foreach(groupi, keyi->groups) {
1486         if (groupi->defined & GROUP_FIELD_ACTS) {
1487             key->explicit |= EXPLICIT_INTERP;
1488             break;
1489         }
1490     }
1491
1492     return true;
1493 }
1494
1495 static bool
1496 CopyModMapDefToKeymap(struct xkb_keymap *keymap, SymbolsInfo *info,
1497                       ModMapEntry *entry)
1498 {
1499     struct xkb_key *key;
1500
1501     if (!entry->haveSymbol) {
1502         key = XkbKeyByName(keymap, entry->u.keyName, true);
1503         if (!key) {
1504             log_vrb(info->ctx, 5,
1505                     "Key %s not found in keycodes; "
1506                     "Modifier map entry for %s not updated\n",
1507                     KeyNameText(info->ctx, entry->u.keyName),
1508                     ModIndexText(info->ctx, &info->mods, entry->modifier));
1509             return false;
1510         }
1511     }
1512     else {
1513         key = FindKeyForSymbol(keymap, entry->u.keySym);
1514         if (!key) {
1515             log_vrb(info->ctx, 5,
1516                     "Key \"%s\" not found in symbol map; "
1517                     "Modifier map entry for %s not updated\n",
1518                     KeysymText(info->ctx, entry->u.keySym),
1519                     ModIndexText(info->ctx, &info->mods, entry->modifier));
1520             return false;
1521         }
1522     }
1523
1524     key->modmap |= (1u << entry->modifier);
1525     return true;
1526 }
1527
1528 static bool
1529 CopySymbolsToKeymap(struct xkb_keymap *keymap, SymbolsInfo *info)
1530 {
1531     KeyInfo *keyi;
1532     ModMapEntry *mm;
1533
1534     keymap->symbols_section_name = strdup_safe(info->name);
1535     XkbEscapeMapName(keymap->symbols_section_name);
1536
1537     keymap->mods = info->mods;
1538
1539     darray_steal(info->group_names,
1540                  &keymap->group_names, &keymap->num_group_names);
1541
1542     darray_foreach(keyi, info->keys)
1543         if (!CopySymbolsDefToKeymap(keymap, info, keyi))
1544             info->errorCount++;
1545
1546     if (xkb_context_get_log_verbosity(keymap->ctx) > 3) {
1547         struct xkb_key *key;
1548
1549         xkb_keys_foreach(key, keymap) {
1550             if (key->name == XKB_ATOM_NONE)
1551                 continue;
1552
1553             if (key->num_groups < 1)
1554                 log_info(info->ctx,
1555                          "No symbols defined for %s\n",
1556                          KeyNameText(info->ctx, key->name));
1557         }
1558     }
1559
1560     darray_foreach(mm, info->modmaps)
1561         if (!CopyModMapDefToKeymap(keymap, info, mm))
1562             info->errorCount++;
1563
1564     /* XXX: If we don't ignore errorCount, things break. */
1565     return true;
1566 }
1567
1568 bool
1569 CompileSymbols(XkbFile *file, struct xkb_keymap *keymap,
1570                enum merge_mode merge)
1571 {
1572     SymbolsInfo info;
1573     ActionsInfo *actions;
1574
1575     actions = NewActionsInfo();
1576     if (!actions)
1577         return false;
1578
1579     InitSymbolsInfo(&info, keymap, actions, &keymap->mods);
1580     info.default_key.merge = merge;
1581
1582     HandleSymbolsFile(&info, file, merge);
1583
1584     if (info.errorCount != 0)
1585         goto err_info;
1586
1587     if (!CopySymbolsToKeymap(keymap, &info))
1588         goto err_info;
1589
1590     ClearSymbolsInfo(&info);
1591     FreeActionsInfo(actions);
1592     return true;
1593
1594 err_info:
1595     FreeActionsInfo(actions);
1596     ClearSymbolsInfo(&info);
1597     return false;
1598 }