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