Structured log messages with a message registry
[platform/upstream/libxkbcommon.git] / src / xkbcomp / symbols.c
index 4b64a82..e438139 100644 (file)
  *
  ********************************************************/
 
-#include <limits.h>
+/*
+ * Copyright © 2012 Intel Corporation
+ * Copyright © 2012 Ran Benita <ran234@gmail.com>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice (including the next
+ * paragraph) shall be included in all copies or substantial portions of the
+ * Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
+ * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ *
+ * Author: Daniel Stone <daniel@fooishbar.org>
+ *         Ran Benita <ran234@gmail.com>
+ */
+
+#include "config.h"
 
 #include "xkbcomp-priv.h"
-#include "parseutils.h"
+#include "text.h"
+#include "expr.h"
 #include "action.h"
-#include "alias.h"
-#include "keycodes.h"
 #include "vmod.h"
+#include "include.h"
+#include "keysym.h"
 
-/***====================================================================***/
 
-/* Needed to work with the typechecker. */
-typedef darray (xkb_keysym_t) darray_xkb_keysym_t;
-typedef darray (union xkb_action) darray_xkb_action;
-
-#define RepeatYes       1
-#define RepeatNo        0
-#define RepeatUndefined ~((unsigned) 0)
-
-#define _Key_Syms       (1 << 0)
-#define _Key_Acts       (1 << 1)
-#define _Key_Repeat     (1 << 2)
-#define _Key_Behavior   (1 << 3)
-#define _Key_Type_Dflt  (1 << 4)
-#define _Key_Types      (1 << 5)
-#define _Key_GroupInfo  (1 << 6)
-#define _Key_VModMap    (1 << 7)
-
-typedef struct _KeyInfo {
-    CommonInfo defs;
-    unsigned long name; /* the 4 chars of the key name, as long */
-    unsigned char typesDefined;
-    unsigned char symsDefined;
-    unsigned char actsDefined;
-    unsigned int numLevels[XkbNumKbdGroups];
-
-    /* syms[group] -> Single array for all the keysyms in the group. */
-    darray_xkb_keysym_t syms[XkbNumKbdGroups];
-    /*
-     * symsMapIndex[group][level] -> The index from which the syms for
-     * the level begin in the syms[group] array. Remember each keycode
-     * can have multiple keysyms in each level (that is, each key press
-     * can result in multiple keysyms).
-     */
-    darray(int) symsMapIndex[XkbNumKbdGroups];
-    /*
-     * symsMapNumEntries[group][level] -> How many syms are in
-     * syms[group][symsMapIndex[group][level]].
-     */
-    darray(size_t) symsMapNumEntries[XkbNumKbdGroups];
+// TODO: convert log_err to log_err_with_code
+// TODO: convert log_vrb to log_vrb_with_code
+
+enum key_repeat {
+    KEY_REPEAT_UNDEFINED = 0,
+    KEY_REPEAT_YES = 1,
+    KEY_REPEAT_NO = 2,
+};
+
+enum group_field {
+    GROUP_FIELD_SYMS = (1 << 0),
+    GROUP_FIELD_ACTS = (1 << 1),
+    GROUP_FIELD_TYPE = (1 << 2),
+};
 
-    darray_xkb_action acts[XkbNumKbdGroups];
+enum key_field {
+    KEY_FIELD_REPEAT = (1 << 0),
+    KEY_FIELD_DEFAULT_TYPE = (1 << 1),
+    KEY_FIELD_GROUPINFO = (1 << 2),
+    KEY_FIELD_VMODMAP = (1 << 3),
+};
+
+typedef struct {
+    enum group_field defined;
+    darray(struct xkb_level) levels;
+    xkb_atom_t type;
+} GroupInfo;
+
+typedef struct {
+    enum key_field defined;
+    enum merge_mode merge;
 
-    xkb_atom_t types[XkbNumKbdGroups];
-    unsigned repeat;
-    struct xkb_behavior behavior;
-    unsigned short vmodmap;
-    xkb_atom_t dfltType;
+    xkb_atom_t name;
 
-    uint8_t out_of_range_group_action;
-    uint8_t out_of_range_group_number;
+    darray(GroupInfo) groups;
+
+    enum key_repeat repeat;
+    xkb_mod_mask_t vmodmap;
+    xkb_atom_t default_type;
+
+    enum xkb_range_exceed_type out_of_range_group_action;
+    xkb_layout_index_t out_of_range_group_number;
 } KeyInfo;
 
-/**
- * Init the given key info to sane values.
- */
 static void
-InitKeyInfo(KeyInfo *keyi, unsigned file_id)
+ClearLevelInfo(struct xkb_level *leveli)
 {
-    int i;
-    static const char dflt[4] = "*";
-
-    keyi->defs.defined = 0;
-    keyi->defs.file_id = file_id;
-    keyi->defs.merge = MERGE_OVERRIDE;
-    keyi->defs.next = NULL;
-    keyi->name = KeyNameToLong(dflt);
-    keyi->typesDefined = keyi->symsDefined = keyi->actsDefined = 0;
-
-    for (i = 0; i < XkbNumKbdGroups; i++) {
-        keyi->numLevels[i] = 0;
-        keyi->types[i] = XKB_ATOM_NONE;
-        darray_init(keyi->syms[i]);
-        darray_init(keyi->symsMapIndex[i]);
-        darray_init(keyi->symsMapNumEntries[i]);
-        darray_init(keyi->acts[i]);
-    }
-
-    keyi->dfltType = XKB_ATOM_NONE;
-    keyi->behavior.type = XkbKB_Default;
-    keyi->behavior.data = 0;
-    keyi->vmodmap = 0;
-    keyi->repeat = RepeatUndefined;
-    keyi->out_of_range_group_action = 0;
-    keyi->out_of_range_group_number = 0;
+    if (leveli->num_syms > 1)
+        free(leveli->u.syms);
 }
 
 static void
-FreeKeyInfo(KeyInfo *keyi)
+InitGroupInfo(GroupInfo *groupi)
 {
-    int i;
+    memset(groupi, 0, sizeof(*groupi));
+}
 
-    for (i = 0; i < XkbNumKbdGroups; i++) {
-        darray_free(keyi->syms[i]);
-        darray_free(keyi->symsMapIndex[i]);
-        darray_free(keyi->symsMapNumEntries[i]);
-        darray_free(keyi->acts[i]);
-    }
+static void
+ClearGroupInfo(GroupInfo *groupi)
+{
+    struct xkb_level *leveli;
+    darray_foreach(leveli, groupi->levels)
+        ClearLevelInfo(leveli);
+    darray_free(groupi->levels);
 }
 
-/**
- * Copy old into new, optionally reset old to 0.
- * If old is reset, new simply re-uses old's memory. Otherwise, the memory is
- * newly allocated and new points to the new memory areas.
- */
-static bool
-CopyKeyInfo(KeyInfo * old, KeyInfo * new, bool clearOld)
+static void
+CopyGroupInfo(GroupInfo *to, const GroupInfo *from)
 {
-    int i;
-
-    *new = *old;
-    new->defs.next = NULL;
-
-    if (clearOld) {
-        for (i = 0; i < XkbNumKbdGroups; i++) {
-            old->numLevels[i] = 0;
-            darray_init(old->symsMapIndex[i]);
-            darray_init(old->symsMapNumEntries[i]);
-            darray_init(old->syms[i]);
-            darray_init(old->acts[i]);
-        }
-    }
-    else {
-        for (i = 0; i < XkbNumKbdGroups; i++) {
-            darray_copy(new->syms[i], old->syms[i]);
-            darray_copy(new->symsMapIndex[i], old->symsMapIndex[i]);
-            darray_copy(new->symsMapNumEntries[i], old->symsMapNumEntries[i]);
-            darray_copy(new->acts[i], old->acts[i]);
-        }
-    }
+    to->defined = from->defined;
+    to->type = from->type;
+    darray_init(to->levels);
+    darray_copy(to->levels, from->levels);
+    for (xkb_level_index_t j = 0; j < darray_size(to->levels); j++)
+        if (darray_item(from->levels, j).num_syms > 1)
+            darray_item(to->levels, j).u.syms =
+                memdup(darray_item(from->levels, j).u.syms,
+                       darray_item(from->levels, j).num_syms,
+                       sizeof(xkb_keysym_t));
+}
 
-    return true;
+static void
+InitKeyInfo(struct xkb_context *ctx, KeyInfo *keyi)
+{
+    memset(keyi, 0, sizeof(*keyi));
+    keyi->merge = MERGE_OVERRIDE;
+    keyi->name = xkb_atom_intern_literal(ctx, "*");
+    keyi->out_of_range_group_action = RANGE_WRAP;
+}
+
+static void
+ClearKeyInfo(KeyInfo *keyi)
+{
+    GroupInfo *groupi;
+    darray_foreach(groupi, keyi->groups)
+        ClearGroupInfo(groupi);
+    darray_free(keyi->groups);
 }
 
 /***====================================================================***/
 
-typedef struct _ModMapEntry {
-    CommonInfo defs;
+typedef struct {
+    enum merge_mode merge;
     bool haveSymbol;
-    int modifier;
+    // NOTE: Can also be XKB_MOD_NONE, meaning
+    //       “don’t add a modifier to the modmap”.
+    xkb_mod_index_t modifier;
     union {
-        unsigned long keyName;
+        xkb_atom_t keyName;
         xkb_keysym_t keySym;
     } u;
 } ModMapEntry;
 
-typedef struct _SymbolsInfo {
+typedef struct {
     char *name;         /* e.g. pc+us+inet(evdev) */
     int errorCount;
-    unsigned file_id;
     enum merge_mode merge;
-    unsigned explicit_group;
+    xkb_layout_index_t explicit_group;
     darray(KeyInfo) keys;
-    KeyInfo dflt;
-    VModInfo vmods;
-    ActionInfo *action;
-    xkb_atom_t groupNames[XkbNumKbdGroups];
-
-    ModMapEntry *modMap;
-    AliasInfo *aliases;
+    KeyInfo default_key;
+    ActionsInfo *actions;
+    darray(xkb_atom_t) group_names;
+    darray(ModMapEntry) modmaps;
+    struct xkb_mod_set mods;
+
+    struct xkb_context *ctx;
+    /* Needed for AddKeySymbols. */
+    const struct xkb_keymap *keymap;
 } SymbolsInfo;
 
 static void
-InitSymbolsInfo(SymbolsInfo * info, struct xkb_keymap *keymap,
-                unsigned file_id)
+InitSymbolsInfo(SymbolsInfo *info, const struct xkb_keymap *keymap,
+                ActionsInfo *actions, const struct xkb_mod_set *mods)
 {
-    int i;
-
-    info->name = NULL;
-    info->explicit_group = 0;
-    info->errorCount = 0;
-    info->file_id = file_id;
+    memset(info, 0, sizeof(*info));
+    info->ctx = keymap->ctx;
+    info->keymap = keymap;
     info->merge = MERGE_OVERRIDE;
-    darray_init(info->keys);
-    darray_growalloc(info->keys, 110);
-    info->modMap = NULL;
-    for (i = 0; i < XkbNumKbdGroups; i++)
-        info->groupNames[i] = XKB_ATOM_NONE;
-    InitKeyInfo(&info->dflt, file_id);
-    InitVModInfo(&info->vmods, keymap);
-    info->action = NULL;
-    info->aliases = NULL;
+    InitKeyInfo(keymap->ctx, &info->default_key);
+    info->actions = actions;
+    info->mods = *mods;
+    info->explicit_group = XKB_LAYOUT_INVALID;
 }
 
 static void
-FreeSymbolsInfo(SymbolsInfo * info)
+ClearSymbolsInfo(SymbolsInfo *info)
 {
     KeyInfo *keyi;
-
     free(info->name);
-    darray_foreach(keyi, info->keys) {
-        FreeKeyInfo(keyi);
-    }
+    darray_foreach(keyi, info->keys)
+        ClearKeyInfo(keyi);
     darray_free(info->keys);
-    if (info->modMap)
-        ClearCommonInfo(&info->modMap->defs);
-    if (info->aliases)
-        ClearAliases(&info->aliases);
-    memset(info, 0, sizeof(SymbolsInfo));
+    darray_free(info->group_names);
+    darray_free(info->modmaps);
+    ClearKeyInfo(&info->default_key);
 }
 
-static bool
-ResizeKeyGroup(KeyInfo *keyi, unsigned int group, unsigned int numLevels,
-               unsigned sizeSyms, bool forceActions)
+static const char *
+KeyInfoText(SymbolsInfo *info, KeyInfo *keyi)
 {
-    int i;
-
-    if (darray_size(keyi->syms[group]) < sizeSyms)
-        darray_resize0(keyi->syms[group], sizeSyms);
-
-    if (darray_empty(keyi->symsMapIndex[group]) ||
-        keyi->numLevels[group] < numLevels) {
-        darray_resize(keyi->symsMapIndex[group], numLevels);
-        for (i = keyi->numLevels[group]; i < numLevels; i++)
-            darray_item(keyi->symsMapIndex[group], i) = -1;
-    }
-
-    if (darray_empty(keyi->symsMapNumEntries[group]) ||
-        keyi->numLevels[group] < numLevels)
-        darray_resize0(keyi->symsMapNumEntries[group], numLevels);
-
-    if ((forceActions && (keyi->numLevels[group] < numLevels ||
-                          darray_empty(keyi->acts[group]))) ||
-        (keyi->numLevels[group] < numLevels && !darray_empty(keyi->acts[group])))
-        darray_resize0(keyi->acts[group], numLevels);
-
-    if (keyi->numLevels[group] < numLevels)
-        keyi->numLevels[group] = numLevels;
-
-    return true;
+    return KeyNameText(info->ctx, keyi->name);
 }
 
-enum key_group_selector {
-    NONE = 0,
-    FROM = (1 << 0),
-    TO = (1 << 1),
-};
-
 static bool
-MergeKeyGroups(SymbolsInfo * info,
-               KeyInfo * into, KeyInfo * from, unsigned group)
+MergeGroups(SymbolsInfo *info, GroupInfo *into, GroupInfo *from, bool clobber,
+            bool report, xkb_layout_index_t group, xkb_atom_t key_name)
 {
-    darray_xkb_keysym_t resultSyms;
-    enum key_group_selector using = NONE;
-    darray_xkb_action resultActs;
-    unsigned int resultWidth;
-    unsigned int resultSize = 0;
-    int cur_idx = 0;
-    int i;
-    bool report, clobber;
+    xkb_level_index_t i, levels_in_both;
+    struct xkb_level *level;
 
-    clobber = (from->defs.merge != MERGE_AUGMENT);
-
-    report = (warningLevel > 9) ||
-             ((into->defs.file_id == from->defs.file_id) && (warningLevel > 0));
-
-    darray_init(resultSyms);
-
-    if (into->numLevels[group] >= from->numLevels[group]) {
-        resultActs = into->acts[group];
-        resultWidth = into->numLevels[group];
-    }
-    else {
-        resultActs = from->acts[group];
-        resultWidth = from->numLevels[group];
-        darray_resize(into->symsMapIndex[group],
-                      from->numLevels[group]);
-        darray_resize0(into->symsMapNumEntries[group],
-                       from->numLevels[group]);
+    /* First find the type of the merged group. */
+    if (into->type != from->type) {
+        if (from->type == XKB_ATOM_NONE) {
+            /* it's empty for consistency with other comparisons */
+        }
+        else if (into->type == XKB_ATOM_NONE) {
+            into->type = from->type;
+        }
+        else {
+            xkb_atom_t use = (clobber ? from->type : into->type);
+            xkb_atom_t ignore = (clobber ? into->type : from->type);
+
+            if (report) {
+                log_warn_with_code(info->ctx,
+                         XKB_WARNING_CONFLICTING_KEY_TYPE,
+                         "Multiple definitions for group %d type of key %s; "
+                         "Using %s, ignoring %s\n",
+                         group + 1, KeyNameText(info->ctx, key_name),
+                         xkb_atom_text(info->ctx, use),
+                         xkb_atom_text(info->ctx, ignore));
+            }
 
-        for (i = into->numLevels[group]; i < from->numLevels[group]; i++)
-            darray_item(into->symsMapIndex[group], i) = -1;
+            into->type = use;
+        }
     }
+    into->defined |= (from->defined & GROUP_FIELD_TYPE);
 
-    if (darray_empty(resultActs) && (!darray_empty(into->acts[group]) ||
-                                     !darray_empty(from->acts[group]))) {
-        darray_resize0(resultActs, resultWidth);
-        for (i = 0; i < resultWidth; i++) {
-            union xkb_action *fromAct = NULL, *toAct = NULL;
-
-            if (!darray_empty(from->acts[group]))
-                fromAct = &darray_item(from->acts[group], i);
-
-            if (!darray_empty(into->acts[group]))
-                toAct = &darray_item(into->acts[group], i);
+    /* Now look at the levels. */
 
-            if (((fromAct == NULL) || (fromAct->type == XkbSA_NoAction))
-                && (toAct != NULL)) {
-                darray_item(resultActs, i) = *toAct;
-            }
-            else if (((toAct == NULL) || (toAct->type == XkbSA_NoAction))
-                     && (fromAct != NULL)) {
-                darray_item(resultActs, i) = *fromAct;
-            }
-            else {
-                union xkb_action *use, *ignore;
-                if (clobber) {
-                    use = fromAct;
-                    ignore = toAct;
-                }
-                else {
-                    use = toAct;
-                    ignore = fromAct;
-                }
-                if (report) {
-                    WARN
-                        ("Multiple actions for level %d/group %d on key %s\n",
-                        i + 1, group + 1, longText(into->name));
-                    ACTION("Using %s, ignoring %s\n",
-                           XkbcActionTypeText(use->type),
-                           XkbcActionTypeText(ignore->type));
-                }
-                if (use)
-                    darray_item(resultActs, i) = *use;
-            }
-        }
+    if (darray_empty(from->levels)) {
+        InitGroupInfo(from);
+        return true;
     }
 
-    for (i = 0; i < resultWidth; i++) {
-        unsigned int fromSize = 0;
-        unsigned toSize = 0;
-
-        if (!darray_empty(from->symsMapNumEntries[group]) &&
-            i < from->numLevels[group])
-            fromSize = darray_item(from->symsMapNumEntries[group], i);
+    if (darray_empty(into->levels)) {
+        from->type = into->type;
+        *into = *from;
+        InitGroupInfo(from);
+        return true;
+    }
 
-        if (!darray_empty(into->symsMapNumEntries[group]) &&
-            i < into->numLevels[group])
-            toSize = darray_item(into->symsMapNumEntries[group], i);
+    /* Merge the actions and syms. */
+    levels_in_both = MIN(darray_size(into->levels), darray_size(from->levels));
+    for (i = 0; i < levels_in_both; i++) {
+        struct xkb_level *intoLevel = &darray_item(into->levels, i);
+        struct xkb_level *fromLevel = &darray_item(from->levels, i);
 
-        if (fromSize == 0) {
-            resultSize += toSize;
-            using |= TO;
+        if (fromLevel->action.type == ACTION_TYPE_NONE) {
+            /* it's empty for consistency with other comparisons */
         }
-        else if (toSize == 0 || clobber) {
-            resultSize += fromSize;
-            using |= FROM;
+        else if (intoLevel->action.type == ACTION_TYPE_NONE) {
+            intoLevel->action = fromLevel->action;
         }
         else {
-            resultSize += toSize;
-            using |= TO;
+            union xkb_action *use, *ignore;
+            use = (clobber ? &fromLevel->action : &intoLevel->action);
+            ignore = (clobber ? &intoLevel->action : &fromLevel->action);
+
+            if (report) {
+                log_warn_with_code(info->ctx,
+                         XKB_WARNING_CONFLICTING_KEY_ACTION,
+                         "Multiple actions for level %d/group %u on key %s; "
+                         "Using %s, ignoring %s\n",
+                         i + 1, group + 1, KeyNameText(info->ctx, key_name),
+                         ActionTypeText(use->type),
+                         ActionTypeText(ignore->type));
+            }
+
+            intoLevel->action = *use;
         }
-    }
 
-    if (resultSize == 0)
-        goto out;
+        if (fromLevel->num_syms == 0) {
+            /* it's empty for consistency with other comparisons */
+        }
+        else if (intoLevel->num_syms == 0) {
+            intoLevel->num_syms = fromLevel->num_syms;
+            if (fromLevel->num_syms > 1)
+                intoLevel->u.syms = fromLevel->u.syms;
+            else
+                intoLevel->u.sym = fromLevel->u.sym;
+            fromLevel->num_syms = 0;
+        }
+        else if (!XkbLevelsSameSyms(fromLevel, intoLevel)) {
+            if (report) {
+                log_warn_with_code(info->ctx,
+                         XKB_WARNING_CONFLICTING_KEY_SYMBOL,
+                         "Multiple symbols for level %d/group %u on key %s; "
+                         "Using %s, ignoring %s\n",
+                         i + 1, group + 1, KeyNameText(info->ctx, key_name),
+                         (clobber ? "from" : "to"),
+                         (clobber ? "to" : "from"));
+            }
 
-    if (using == FROM) {
-        resultSyms = from->syms[group];
-        darray_free(into->symsMapNumEntries[group]);
-        darray_free(into->symsMapIndex[group]);
-        into->symsMapNumEntries[group] = from->symsMapNumEntries[group];
-        into->symsMapIndex[group] = from->symsMapIndex[group];
-        darray_init(from->symsMapNumEntries[group]);
-        darray_init(from->symsMapIndex[group]);
-        goto out;
+            if (clobber) {
+                ClearLevelInfo(intoLevel);
+                intoLevel->num_syms = fromLevel->num_syms;
+                if (fromLevel->num_syms > 1)
+                    intoLevel->u.syms = fromLevel->u.syms;
+                else
+                    intoLevel->u.sym = fromLevel->u.sym;
+                fromLevel->num_syms = 0;
+            }
+        }
     }
-    else if (using == TO) {
-        resultSyms = into->syms[group];
-        goto out;
+    /* If @from has extra levels, get them as well. */
+    darray_foreach_from(level, from->levels, levels_in_both) {
+        darray_append(into->levels, *level);
+        level->num_syms = 0;
     }
+    into->defined |= (from->defined & GROUP_FIELD_ACTS);
+    into->defined |= (from->defined & GROUP_FIELD_SYMS);
 
-    darray_resize0(resultSyms, resultSize);
-
-    for (i = 0; i < resultWidth; i++) {
-        enum key_group_selector use = NONE;
-        unsigned int fromSize = 0;
-        unsigned int toSize = 0;
-
-        if (i < from->numLevels[group])
-            fromSize = darray_item(from->symsMapNumEntries[group], i);
-
-        if (i < into->numLevels[group])
-            toSize = darray_item(into->symsMapNumEntries[group], i);
+    return true;
+}
 
-        if (fromSize == 0 && toSize == 0) {
-            darray_item(into->symsMapIndex[group], i) = -1;
-            darray_item(into->symsMapNumEntries[group], i) = 0;
-            continue;
-        }
+static bool
+UseNewKeyField(enum key_field field, enum key_field old, enum key_field new,
+               bool clobber, bool report, enum key_field *collide)
+{
+    if (!(old & field))
+        return (new & field);
 
-        if (fromSize == 0)
-            use = TO;
-        else if (toSize == 0 || clobber)
-            use = FROM;
-        else
-            use = TO;
-
-        if (toSize && fromSize && report) {
-            INFO("Multiple symbols for group %d, level %d on key %s\n",
-                 group + 1, i + 1, longText(into->name));
-            ACTION("Using %s, ignoring %s\n",
-                   (use == FROM ? "from" : "to"),
-                   (use == FROM ? "to" : "from"));
-        }
+    if (new & field) {
+        if (report)
+            *collide |= field;
 
-        if (use == FROM) {
-            memcpy(darray_mem(resultSyms, cur_idx),
-                   darray_mem(from->syms[group],
-                              darray_item(from->symsMapIndex[group], i)),
-                   darray_item(from->symsMapNumEntries[group],
-                               i) * sizeof(xkb_keysym_t));
-            darray_item(into->symsMapIndex[group], i) = cur_idx;
-            darray_item(into->symsMapNumEntries[group], i) =
-                darray_item(from->symsMapNumEntries[group], i);
-        }
-        else {
-            memcpy(darray_mem(resultSyms, cur_idx),
-                   darray_mem(into->syms[group],
-                              darray_item(into->symsMapIndex[group], i)),
-                   darray_item(into->symsMapNumEntries[group],
-                               i) * sizeof(xkb_keysym_t));
-            darray_item(into->symsMapIndex[group], i) = cur_idx;
-        }
-        cur_idx += darray_item(into->symsMapNumEntries[group], i);
-    }
-
-out:
-    if (!darray_same(resultActs, into->acts[group]))
-        darray_free(into->acts[group]);
-    if (!darray_same(resultActs, from->acts[group]))
-        darray_free(from->acts[group]);
-    into->numLevels[group] = resultWidth;
-    if (!darray_same(resultSyms, into->syms[group]))
-        darray_free(into->syms[group]);
-    into->syms[group] = resultSyms;
-    if (!darray_same(resultSyms, from->syms[group]))
-        darray_free(from->syms[group]);
-    darray_init(from->syms[group]);
-    darray_free(from->symsMapIndex[group]);
-    darray_free(from->symsMapNumEntries[group]);
-    into->acts[group] = resultActs;
-    darray_init(from->acts[group]);
-    if (!darray_empty(into->syms[group]))
-        into->symsDefined |= (1 << group);
-    from->symsDefined &= ~(1 << group);
-    into->actsDefined |= (1 << group);
-    from->actsDefined &= ~(1 << group);
+        if (clobber)
+            return true;
+    }
 
-    return true;
+    return false;
 }
 
 static bool
-MergeKeys(SymbolsInfo *info, struct xkb_keymap *keymap,
-          KeyInfo *into, KeyInfo *from)
+MergeKeys(SymbolsInfo *info, KeyInfo *into, KeyInfo *from, bool same_file)
 {
-    int i;
-    unsigned collide = 0;
-    bool report;
-
-    if (from->defs.merge == MERGE_REPLACE) {
-        for (i = 0; i < XkbNumKbdGroups; i++) {
-            if (into->numLevels[i] != 0) {
-                darray_free(into->syms[i]);
-                darray_free(into->acts[i]);
-            }
-        }
+    xkb_layout_index_t i;
+    xkb_layout_index_t groups_in_both;
+    enum key_field collide = 0;
+    const int verbosity = xkb_context_get_log_verbosity(info->ctx);
+    const bool clobber = (from->merge != MERGE_AUGMENT);
+    const bool report = (same_file && verbosity > 0) || verbosity > 9;
+
+    if (from->merge == MERGE_REPLACE) {
+        ClearKeyInfo(into);
         *into = *from;
-        memset(from, 0, sizeof(KeyInfo));
+        InitKeyInfo(info->ctx, from);
         return true;
     }
-    report = ((warningLevel > 9) ||
-              ((into->defs.file_id == from->defs.file_id)
-               && (warningLevel > 0)));
-    for (i = 0; i < XkbNumKbdGroups; i++) {
-        if (from->numLevels[i] > 0) {
-            if (into->numLevels[i] == 0) {
-                into->numLevels[i] = from->numLevels[i];
-                into->syms[i] = from->syms[i];
-                into->symsMapIndex[i] = from->symsMapIndex[i];
-                into->symsMapNumEntries[i] = from->symsMapNumEntries[i];
-                into->acts[i] = from->acts[i];
-                into->symsDefined |= (1 << i);
-                darray_init(from->syms[i]);
-                darray_init(from->symsMapIndex[i]);
-                darray_init(from->symsMapNumEntries[i]);
-                darray_init(from->acts[i]);
-                from->numLevels[i] = 0;
-                from->symsDefined &= ~(1 << i);
-                if (!darray_empty(into->syms[i]))
-                    into->defs.defined |= _Key_Syms;
-                if (!darray_empty(into->acts[i]))
-                    into->defs.defined |= _Key_Acts;
-            }
-            else {
-                if (report) {
-                    if (!darray_empty(into->syms[i]))
-                        collide |= _Key_Syms;
-                    if (!darray_empty(into->acts[i]))
-                        collide |= _Key_Acts;
-                }
-                MergeKeyGroups(info, into, from, (unsigned) i);
-            }
-        }
-        if (from->types[i] != XKB_ATOM_NONE) {
-            if ((into->types[i] != XKB_ATOM_NONE) && report &&
-                (into->types[i] != from->types[i])) {
-                xkb_atom_t use, ignore;
-                collide |= _Key_Types;
-                if (from->defs.merge != MERGE_AUGMENT) {
-                    use = from->types[i];
-                    ignore = into->types[i];
-                }
-                else {
-                    use = into->types[i];
-                    ignore = from->types[i];
-                }
-                WARN
-                    ("Multiple definitions for group %d type of key %s\n",
-                    i, longText(into->name));
-                ACTION("Using %s, ignoring %s\n",
-                       xkb_atom_text(keymap->ctx, use),
-                       xkb_atom_text(keymap->ctx, ignore));
-            }
-            if ((from->defs.merge != MERGE_AUGMENT)
-                || (into->types[i] == XKB_ATOM_NONE)) {
-                into->types[i] = from->types[i];
-            }
-        }
-    }
-    if (UseNewField(_Key_Behavior, &into->defs, &from->defs, &collide)) {
-        into->behavior = from->behavior;
-        into->defs.defined |= _Key_Behavior;
+
+    groups_in_both = MIN(darray_size(into->groups), darray_size(from->groups));
+    for (i = 0; i < groups_in_both; i++)
+        MergeGroups(info,
+                    &darray_item(into->groups, i),
+                    &darray_item(from->groups, i),
+                    clobber, report, i, into->name);
+    /* If @from has extra groups, just move them to @into. */
+    for (i = groups_in_both; i < darray_size(from->groups); i++) {
+        darray_append(into->groups, darray_item(from->groups, i));
+        InitGroupInfo(&darray_item(from->groups, i));
     }
-    if (UseNewField(_Key_VModMap, &into->defs, &from->defs, &collide)) {
+
+    if (UseNewKeyField(KEY_FIELD_VMODMAP, into->defined, from->defined,
+                       clobber, report, &collide)) {
         into->vmodmap = from->vmodmap;
-        into->defs.defined |= _Key_VModMap;
+        into->defined |= KEY_FIELD_VMODMAP;
     }
-    if (UseNewField(_Key_Repeat, &into->defs, &from->defs, &collide)) {
+    if (UseNewKeyField(KEY_FIELD_REPEAT, into->defined, from->defined,
+                       clobber, report, &collide)) {
         into->repeat = from->repeat;
-        into->defs.defined |= _Key_Repeat;
+        into->defined |= KEY_FIELD_REPEAT;
     }
-    if (UseNewField(_Key_Type_Dflt, &into->defs, &from->defs, &collide)) {
-        into->dfltType = from->dfltType;
-        into->defs.defined |= _Key_Type_Dflt;
+    if (UseNewKeyField(KEY_FIELD_DEFAULT_TYPE, into->defined, from->defined,
+                       clobber, report, &collide)) {
+        into->default_type = from->default_type;
+        into->defined |= KEY_FIELD_DEFAULT_TYPE;
     }
-    if (UseNewField(_Key_GroupInfo, &into->defs, &from->defs, &collide)) {
+    if (UseNewKeyField(KEY_FIELD_GROUPINFO, into->defined, from->defined,
+                       clobber, report, &collide)) {
         into->out_of_range_group_action = from->out_of_range_group_action;
         into->out_of_range_group_number = from->out_of_range_group_number;
-        into->defs.defined |= _Key_GroupInfo;
+        into->defined |= KEY_FIELD_GROUPINFO;
     }
+
     if (collide) {
-        WARN("Symbol map for key %s redefined\n",
-             longText(into->name));
-        ACTION("Using %s definition for conflicting fields\n",
-               (from->defs.merge == MERGE_AUGMENT ? "first" : "last"));
+        log_warn_with_code(info->ctx,
+                 XKB_WARNING_CONFLICTING_KEY_FIELDS,
+                 "Symbol map for key %s redefined; "
+                 "Using %s definition for conflicting fields\n",
+                 KeyNameText(info->ctx, into->name),
+                 (clobber ? "first" : "last"));
     }
+
+    ClearKeyInfo(from);
+    InitKeyInfo(info->ctx, from);
     return true;
 }
 
+/* TODO: Make it so this function doesn't need the entire keymap. */
 static bool
-AddKeySymbols(SymbolsInfo *info, KeyInfo *keyi, struct xkb_keymap *keymap)
+AddKeySymbols(SymbolsInfo *info, KeyInfo *keyi, bool same_file)
 {
-    unsigned long real_name;
-    KeyInfo *iter, *new;
+    xkb_atom_t real_name;
+    KeyInfo *iter;
+
+    /*
+     * Don't keep aliases in the keys array; this guarantees that
+     * searching for keys to merge with by straight comparison (see the
+     * following loop) is enough, and we won't get multiple KeyInfo's
+     * for the same key because of aliases.
+     */
+    real_name = XkbResolveKeyAlias(info->keymap, keyi->name);
+    if (real_name != XKB_ATOM_NONE)
+        keyi->name = real_name;
 
     darray_foreach(iter, info->keys)
         if (iter->name == keyi->name)
-            return MergeKeys(info, keymap, iter, keyi);
+            return MergeKeys(info, iter, keyi, same_file);
 
-    if (FindKeyNameForAlias(keymap, keyi->name, &real_name))
-        darray_foreach(iter, info->keys)
-            if (iter->name == real_name)
-                return MergeKeys(info, keymap, iter, keyi);
-
-    darray_resize0(info->keys, darray_size(info->keys) + 1);
-    new = &darray_item(info->keys, darray_size(info->keys) - 1);
-    return CopyKeyInfo(keyi, new, true);
+    darray_append(info->keys, *keyi);
+    InitKeyInfo(info->ctx, keyi);
+    return true;
 }
 
 static bool
-AddModMapEntry(SymbolsInfo * info, ModMapEntry * new)
+AddModMapEntry(SymbolsInfo *info, ModMapEntry *new)
 {
-    ModMapEntry *mm;
-    bool clobber;
-
-    clobber = (new->defs.merge != MERGE_AUGMENT);
-    for (mm = info->modMap; mm != NULL; mm = (ModMapEntry *) mm->defs.next) {
-        if (new->haveSymbol && mm->haveSymbol
-            && (new->u.keySym == mm->u.keySym)) {
-            unsigned use, ignore;
-            if (mm->modifier != new->modifier) {
-                if (clobber) {
-                    use = new->modifier;
-                    ignore = mm->modifier;
-                }
-                else {
-                    use = mm->modifier;
-                    ignore = new->modifier;
-                }
-                ERROR
-                    ("%s added to symbol map for multiple modifiers\n",
-                    XkbcKeysymText(new->u.keySym));
-                ACTION("Using %s, ignoring %s.\n",
-                       XkbcModIndexText(use),
-                       XkbcModIndexText(ignore));
-                mm->modifier = use;
-            }
-            return true;
-        }
-        if ((!new->haveSymbol) && (!mm->haveSymbol) &&
-            (new->u.keyName == mm->u.keyName)) {
-            unsigned use, ignore;
-            if (mm->modifier != new->modifier) {
-                if (clobber) {
-                    use = new->modifier;
-                    ignore = mm->modifier;
-                }
-                else {
-                    use = mm->modifier;
-                    ignore = new->modifier;
-                }
-                ERROR("Key %s added to map for multiple modifiers\n",
-                      longText(new->u.keyName));
-                ACTION("Using %s, ignoring %s.\n",
-                       XkbcModIndexText(use),
-                       XkbcModIndexText(ignore));
-                mm->modifier = use;
-            }
+    ModMapEntry *old;
+    bool clobber = (new->merge != MERGE_AUGMENT);
+
+    darray_foreach(old, info->modmaps) {
+        xkb_mod_index_t use, ignore;
+
+        if ((new->haveSymbol != old->haveSymbol) ||
+            (new->haveSymbol && new->u.keySym != old->u.keySym) ||
+            (!new->haveSymbol && new->u.keyName != old->u.keyName))
+            continue;
+
+        if (new->modifier == old->modifier)
             return true;
-        }
-    }
-    mm = uTypedAlloc(ModMapEntry);
-    if (mm == NULL) {
-        WSGO("Could not allocate modifier map entry\n");
-        ACTION("Modifier map for %s will be incomplete\n",
-               XkbcModIndexText(new->modifier));
-        return false;
+
+        use = (clobber ? new->modifier : old->modifier);
+        ignore = (clobber ? old->modifier : new->modifier);
+
+        if (new->haveSymbol) {
+            log_warn_with_code(info->ctx,
+                     XKB_WARNING_CONFLICTING_MODMAP,
+                     "Symbol \"%s\" added to modifier map for multiple modifiers; "
+                     "Using %s, ignoring %s\n",
+                     KeysymText(info->ctx, new->u.keySym),
+                     ModIndexText(info->ctx, &info->mods, use),
+                     ModIndexText(info->ctx, &info->mods, ignore));
+        } else {
+            log_warn_with_code(info->ctx,
+                     XKB_WARNING_CONFLICTING_MODMAP,
+                     "Key \"%s\" added to modifier map for multiple modifiers; "
+                     "Using %s, ignoring %s\n",
+                     KeyNameText(info->ctx, new->u.keyName),
+                     ModIndexText(info->ctx, &info->mods, use),
+                     ModIndexText(info->ctx, &info->mods, ignore));
+        }
+        old->modifier = use;
+        return true;
     }
-    *mm = *new;
-    mm->defs.next = &info->modMap->defs;
-    info->modMap = mm;
+
+    darray_append(info->modmaps, *new);
     return true;
 }
 
@@ -673,135 +505,115 @@ AddModMapEntry(SymbolsInfo * info, ModMapEntry * new)
 
 static void
 MergeIncludedSymbols(SymbolsInfo *into, SymbolsInfo *from,
-                     enum merge_mode merge, struct xkb_keymap *keymap)
+                     enum merge_mode merge)
 {
-    unsigned int i;
-    KeyInfo *keyi;
+    xkb_atom_t *group_name;
+    xkb_layout_index_t group_names_in_both;
 
     if (from->errorCount > 0) {
         into->errorCount += from->errorCount;
         return;
     }
+
+    into->mods = from->mods;
+
     if (into->name == NULL) {
         into->name = from->name;
         from->name = NULL;
     }
-    for (i = 0; i < XkbNumKbdGroups; i++) {
-        if (from->groupNames[i] != XKB_ATOM_NONE) {
-            if ((merge != MERGE_AUGMENT) ||
-                (into->groupNames[i] == XKB_ATOM_NONE))
-                into->groupNames[i] = from->groupNames[i];
-        }
-    }
 
-    darray_foreach(keyi, from->keys) {
-        if (merge != MERGE_DEFAULT)
-            keyi->defs.merge = merge;
+    group_names_in_both = MIN(darray_size(into->group_names),
+                              darray_size(from->group_names));
+    for (xkb_layout_index_t i = 0; i < group_names_in_both; i++) {
+        if (!darray_item(from->group_names, i))
+            continue;
 
-        if (!AddKeySymbols(into, keyi, keymap))
-            into->errorCount++;
+        if (merge == MERGE_AUGMENT && darray_item(into->group_names, i))
+            continue;
+
+        darray_item(into->group_names, i) = darray_item(from->group_names, i);
     }
+    /* If @from has more, get them as well. */
+    darray_foreach_from(group_name, from->group_names, group_names_in_both)
+        darray_append(into->group_names, *group_name);
 
-    if (from->modMap != NULL) {
-        ModMapEntry *mm, *next;
-        for (mm = from->modMap; mm != NULL; mm = next) {
-            if (merge != MERGE_DEFAULT)
-                mm->defs.merge = merge;
+    if (darray_empty(into->keys)) {
+        into->keys = from->keys;
+        darray_init(from->keys);
+    }
+    else {
+        KeyInfo *keyi;
+        darray_foreach(keyi, from->keys) {
+            keyi->merge = (merge == MERGE_DEFAULT ? keyi->merge : merge);
+            if (!AddKeySymbols(into, keyi, false))
+                into->errorCount++;
+        }
+    }
+
+    if (darray_empty(into->modmaps)) {
+        into->modmaps = from->modmaps;
+        darray_init(from->modmaps);
+    }
+    else {
+        ModMapEntry *mm;
+        darray_foreach(mm, from->modmaps) {
+            mm->merge = (merge == MERGE_DEFAULT ? mm->merge : merge);
             if (!AddModMapEntry(into, mm))
                 into->errorCount++;
-            next = (ModMapEntry *) mm->defs.next;
-            free(mm);
         }
-        from->modMap = NULL;
     }
-    if (!MergeAliases(&into->aliases, &from->aliases, merge))
-        into->errorCount++;
 }
 
 static void
-HandleSymbolsFile(XkbFile *file, struct xkb_keymap *keymap,
-                  enum merge_mode merge,
-                  SymbolsInfo *info);
+HandleSymbolsFile(SymbolsInfo *info, XkbFile *file, enum merge_mode merge);
 
 static bool
-HandleIncludeSymbols(IncludeStmt *stmt, struct xkb_keymap *keymap,
-                     SymbolsInfo *info)
+HandleIncludeSymbols(SymbolsInfo *info, IncludeStmt *include)
 {
-    enum merge_mode newMerge;
-    XkbFile *rtrn;
     SymbolsInfo included;
-    bool haveSelf;
-
-    haveSelf = false;
-    if ((stmt->file == NULL) && (stmt->map == NULL)) {
-        haveSelf = true;
-        included = *info;
-        memset(info, 0, sizeof(SymbolsInfo));
-    }
-    else if (ProcessIncludeFile(keymap->ctx, stmt, FILE_TYPE_SYMBOLS, &rtrn,
-                                &newMerge)) {
-        InitSymbolsInfo(&included, keymap, rtrn->id);
-        included.merge = included.dflt.defs.merge = MERGE_OVERRIDE;
+
+    InitSymbolsInfo(&included, info->keymap, info->actions, &info->mods);
+    included.name = include->stmt;
+    include->stmt = NULL;
+
+    for (IncludeStmt *stmt = include; stmt; stmt = stmt->next_incl) {
+        SymbolsInfo next_incl;
+        XkbFile *file;
+
+        file = ProcessIncludeFile(info->ctx, stmt, FILE_TYPE_SYMBOLS);
+        if (!file) {
+            info->errorCount += 10;
+            ClearSymbolsInfo(&included);
+            return false;
+        }
+
+        InitSymbolsInfo(&next_incl, info->keymap, info->actions,
+                        &included.mods);
         if (stmt->modifier) {
-            included.explicit_group = atoi(stmt->modifier) - 1;
+            next_incl.explicit_group = atoi(stmt->modifier) - 1;
+            if (next_incl.explicit_group >= XKB_MAX_GROUPS) {
+                log_err(info->ctx,
+                        "Cannot set explicit group to %d - must be between 1..%d; "
+                        "Ignoring group number\n",
+                        next_incl.explicit_group + 1, XKB_MAX_GROUPS);
+                next_incl.explicit_group = info->explicit_group;
+            }
         }
         else {
-            included.explicit_group = info->explicit_group;
+            next_incl.explicit_group = info->explicit_group;
         }
-        HandleSymbolsFile(rtrn, keymap, MERGE_OVERRIDE, &included);
-        if (stmt->stmt != NULL) {
-            free(included.name);
-            included.name = stmt->stmt;
-            stmt->stmt = NULL;
-        }
-        FreeXKBFile(rtrn);
-    }
-    else {
-        info->errorCount += 10;
-        return false;
-    }
-    if ((stmt->next != NULL) && (included.errorCount < 1)) {
-        IncludeStmt *next;
-        unsigned op;
-        SymbolsInfo next_incl;
 
-        for (next = stmt->next; next != NULL; next = next->next) {
-            if ((next->file == NULL) && (next->map == NULL)) {
-                haveSelf = true;
-                MergeIncludedSymbols(&included, info, next->merge, keymap);
-                FreeSymbolsInfo(info);
-            }
-            else if (ProcessIncludeFile(keymap->ctx, next, FILE_TYPE_SYMBOLS,
-                                        &rtrn, &op)) {
-                InitSymbolsInfo(&next_incl, keymap, rtrn->id);
-                next_incl.merge = next_incl.dflt.defs.merge = MERGE_OVERRIDE;
-                if (next->modifier) {
-                    next_incl.explicit_group = atoi(next->modifier) - 1;
-                }
-                else {
-                    next_incl.explicit_group = info->explicit_group;
-                }
-                HandleSymbolsFile(rtrn, keymap, MERGE_OVERRIDE, &next_incl);
-                MergeIncludedSymbols(&included, &next_incl, op, keymap);
-                FreeSymbolsInfo(&next_incl);
-                FreeXKBFile(rtrn);
-            }
-            else {
-                info->errorCount += 10;
-                FreeSymbolsInfo(&included);
-                return false;
-            }
-        }
-    }
-    else if (stmt->next) {
-        info->errorCount += included.errorCount;
-    }
-    if (haveSelf)
-        *info = included;
-    else {
-        MergeIncludedSymbols(info, &included, newMerge, keymap);
-        FreeSymbolsInfo(&included);
+        HandleSymbolsFile(&next_incl, file, MERGE_OVERRIDE);
+
+        MergeIncludedSymbols(&included, &next_incl, stmt->merge);
+
+        ClearSymbolsInfo(&next_incl);
+        FreeXkbFile(file);
     }
+
+    MergeIncludedSymbols(info, &included, include->merge);
+    ClearSymbolsInfo(&included);
+
     return (info->errorCount == 0);
 }
 
@@ -809,507 +621,532 @@ HandleIncludeSymbols(IncludeStmt *stmt, struct xkb_keymap *keymap,
 #define ACTIONS 2
 
 static bool
-GetGroupIndex(KeyInfo *keyi, struct xkb_keymap *keymap,
-              ExprDef * arrayNdx, unsigned what, unsigned *ndx_rtrn)
+GetGroupIndex(SymbolsInfo *info, KeyInfo *keyi, ExprDef *arrayNdx,
+              unsigned what, xkb_layout_index_t *ndx_rtrn)
 {
-    const char *name;
-    ExprResult tmp;
-
-    if (what == SYMBOLS)
-        name = "symbols";
-    else
-        name = "actions";
+    const char *name = (what == SYMBOLS ? "symbols" : "actions");
 
     if (arrayNdx == NULL) {
-        int i;
-        unsigned defined;
-        if (what == SYMBOLS)
-            defined = keyi->symsDefined;
-        else
-            defined = keyi->actsDefined;
-
-        for (i = 0; i < XkbNumKbdGroups; i++) {
-            if ((defined & (1 << i)) == 0) {
+        xkb_layout_index_t i;
+        GroupInfo *groupi;
+        enum group_field field = (what == SYMBOLS ?
+                                  GROUP_FIELD_SYMS : GROUP_FIELD_ACTS);
+
+        darray_enumerate(i, groupi, keyi->groups) {
+            if (!(groupi->defined & field)) {
                 *ndx_rtrn = i;
                 return true;
             }
         }
-        ERROR("Too many groups of %s for key %s (max %d)\n", name,
-              longText(keyi->name), XkbNumKbdGroups + 1);
-        ACTION("Ignoring %s defined for extra groups\n", name);
-        return false;
+
+        if (i >= XKB_MAX_GROUPS) {
+            log_err(info->ctx,
+                    "Too many groups of %s for key %s (max %u); "
+                    "Ignoring %s defined for extra groups\n",
+                    name, KeyInfoText(info, keyi), XKB_MAX_GROUPS, name);
+            return false;
+        }
+
+        darray_resize0(keyi->groups, darray_size(keyi->groups) + 1);
+        *ndx_rtrn = darray_size(keyi->groups) - 1;
+        return true;
     }
-    if (!ExprResolveGroup(keymap->ctx, arrayNdx, &tmp)) {
-        ERROR("Illegal group index for %s of key %s\n", name,
-              longText(keyi->name));
-        ACTION("Definition with non-integer array index ignored\n");
+
+    if (!ExprResolveGroup(info->ctx, arrayNdx, ndx_rtrn)) {
+        log_err_with_code(info->ctx, XKB_ERROR_UNSUPPORTED_GROUP_INDEX,
+                "Illegal group index for %s of key %s\n"
+                "Definition with non-integer array index ignored\n",
+                name, KeyInfoText(info, keyi));
         return false;
     }
-    *ndx_rtrn = tmp.uval - 1;
+
+    (*ndx_rtrn)--;
+    if (*ndx_rtrn >= darray_size(keyi->groups))
+        darray_resize0(keyi->groups, *ndx_rtrn + 1);
+
     return true;
 }
 
 static bool
-AddSymbolsToKey(KeyInfo *keyi, struct xkb_keymap *keymap,
-                ExprDef *arrayNdx, ExprDef *value, SymbolsInfo *info)
+AddSymbolsToKey(SymbolsInfo *info, KeyInfo *keyi, ExprDef *arrayNdx,
+                ExprDef *value)
 {
-    unsigned ndx, nSyms, nLevels;
-    unsigned int i;
-    long j;
+    xkb_layout_index_t ndx;
+    GroupInfo *groupi;
+    xkb_level_index_t nLevels;
 
-    if (!GetGroupIndex(keyi, keymap, arrayNdx, SYMBOLS, &ndx))
+    if (!GetGroupIndex(info, keyi, arrayNdx, SYMBOLS, &ndx))
         return false;
+
+    groupi = &darray_item(keyi->groups, ndx);
+
     if (value == NULL) {
-        keyi->symsDefined |= (1 << ndx);
+        groupi->defined |= GROUP_FIELD_SYMS;
         return true;
     }
-    if (value->op != ExprKeysymList) {
-        ERROR("Expected a list of symbols, found %s\n", exprOpText(value->op));
-        ACTION("Ignoring symbols for group %d of %s\n", ndx + 1,
-               longText(keyi->name));
-        return false;
-    }
-    if (!darray_empty(keyi->syms[ndx])) {
-        ERROR("Symbols for key %s, group %d already defined\n",
-               longText(keyi->name), ndx + 1);
-        ACTION("Ignoring duplicate definition\n");
+
+    if (value->expr.op != EXPR_KEYSYM_LIST) {
+        log_err(info->ctx,
+                "Expected a list of symbols, found %s; "
+                "Ignoring symbols for group %u of %s\n",
+                expr_op_type_to_string(value->expr.op), ndx + 1,
+                KeyInfoText(info, keyi));
         return false;
     }
-    nSyms = darray_size(value->value.list.syms);
-    nLevels = darray_size(value->value.list.symsMapIndex);
-    if ((keyi->numLevels[ndx] < nSyms || darray_empty(keyi->syms[ndx])) &&
-        (!ResizeKeyGroup(keyi, ndx, nLevels, nSyms, false))) {
-        WSGO("Could not resize group %d of key %s to contain %d levels\n",
-             ndx + 1, longText(keyi->name), nSyms);
-        ACTION("Symbols lost\n");
+
+    if (groupi->defined & GROUP_FIELD_SYMS) {
+        log_err(info->ctx,
+                "Symbols for key %s, group %u already defined; "
+                "Ignoring duplicate definition\n",
+                KeyInfoText(info, keyi), ndx + 1);
         return false;
     }
-    keyi->symsDefined |= (1 << ndx);
-    for (i = 0; i < nLevels; i++) {
-        darray_item(keyi->symsMapIndex[ndx], i) =
-            darray_item(value->value.list.symsMapIndex, i);
-        darray_item(keyi->symsMapNumEntries[ndx], i) =
-            darray_item(value->value.list.symsNumEntries, i);
-
-        for (j = 0; j < darray_item(keyi->symsMapNumEntries[ndx], i); j++) {
-            /* FIXME: What's abort() doing here? */
-            if (darray_item(keyi->symsMapIndex[ndx], i) + j >= nSyms)
-                abort();
-            if (!LookupKeysym(darray_item(value->value.list.syms,
-                                          darray_item(value->value.list.symsMapIndex,
-                                                      i) + j),
-                              &darray_item(keyi->syms[ndx],
-                                           darray_item(keyi->symsMapIndex[ndx],
-                                                       i) + j))) {
-                WARN(
-                    "Could not resolve keysym %s for key %s, group %d (%s), level %d\n",
-                    darray_item(value->value.list.syms, i),
-                    longText(keyi->name),
-                    ndx + 1,
-                    xkb_atom_text(keymap->ctx, info->groupNames[ndx]), nSyms);
-                while (--j >= 0)
-                    darray_item(keyi->syms[ndx],
-                                darray_item(keyi->symsMapIndex[ndx],
-                                            i) + j) = XKB_KEY_NoSymbol;
-                darray_item(keyi->symsMapIndex[ndx], i) = -1;
-                darray_item(keyi->symsMapNumEntries[ndx], i) = 0;
-                break;
+
+    nLevels = darray_size(value->keysym_list.symsMapIndex);
+    if (darray_size(groupi->levels) < nLevels)
+        darray_resize0(groupi->levels, nLevels);
+
+    groupi->defined |= GROUP_FIELD_SYMS;
+
+    for (xkb_level_index_t i = 0; i < nLevels; i++) {
+        unsigned int sym_index;
+        struct xkb_level *leveli = &darray_item(groupi->levels, i);
+
+        sym_index = darray_item(value->keysym_list.symsMapIndex, i);
+        leveli->num_syms = darray_item(value->keysym_list.symsNumEntries, i);
+        if (leveli->num_syms > 1)
+            leveli->u.syms = calloc(leveli->num_syms, sizeof(*leveli->u.syms));
+
+        for (unsigned j = 0; j < leveli->num_syms; j++) {
+            xkb_keysym_t keysym = darray_item(value->keysym_list.syms,
+                                              sym_index + j);
+
+            if (leveli->num_syms == 1) {
+                if (keysym == XKB_KEY_NoSymbol)
+                    leveli->num_syms = 0;
+                else
+                    leveli->u.sym = keysym;
             }
-            if (darray_item(keyi->symsMapNumEntries[ndx], i) == 1 &&
-                darray_item(keyi->syms[ndx],
-                            darray_item(keyi->symsMapIndex[ndx],
-                                        i) + j) == XKB_KEY_NoSymbol) {
-                darray_item(keyi->symsMapIndex[ndx], i) = -1;
-                darray_item(keyi->symsMapNumEntries[ndx], i) = 0;
+            else if (leveli->num_syms > 1) {
+                leveli->u.syms[j] = keysym;
             }
         }
     }
-    for (j = keyi->numLevels[ndx] - 1;
-         j >= 0 && darray_item(keyi->symsMapNumEntries[ndx], j) == 0; j--)
-        keyi->numLevels[ndx]--;
+
     return true;
 }
 
 static bool
-AddActionsToKey(KeyInfo *keyi, struct xkb_keymap *keymap, ExprDef *arrayNdx,
-                ExprDef *value, SymbolsInfo *info)
+AddActionsToKey(SymbolsInfo *info, KeyInfo *keyi, ExprDef *arrayNdx,
+                ExprDef *value)
 {
-    unsigned int i;
-    unsigned ndx, nActs;
+    xkb_layout_index_t ndx;
+    GroupInfo *groupi;
+    unsigned int nActs;
     ExprDef *act;
-    struct xkb_any_action *toAct;
 
-    if (!GetGroupIndex(keyi, keymap, arrayNdx, ACTIONS, &ndx))
+    if (!GetGroupIndex(info, keyi, arrayNdx, ACTIONS, &ndx))
         return false;
 
+    groupi = &darray_item(keyi->groups, ndx);
+
     if (value == NULL) {
-        keyi->actsDefined |= (1 << ndx);
+        groupi->defined |= GROUP_FIELD_ACTS;
         return true;
     }
-    if (value->op != ExprActionList) {
-        WSGO("Bad expression type (%d) for action list value\n", value->op);
-        ACTION("Ignoring actions for group %d of %s\n", ndx,
-               longText(keyi->name));
-        return false;
-    }
-    if (!darray_empty(keyi->acts[ndx])) {
-        WSGO("Actions for key %s, group %d already defined\n",
-             longText(keyi->name), ndx);
-        return false;
-    }
-    for (nActs = 0, act = value->value.child; act != NULL; nActs++) {
-        act = (ExprDef *) act->common.next;
-    }
-    if (nActs < 1) {
-        WSGO("Action list but not actions in AddActionsToKey\n");
+
+    if (value->expr.op != EXPR_ACTION_LIST) {
+        log_wsgo(info->ctx,
+                 "Bad expression type (%d) for action list value; "
+                 "Ignoring actions for group %u of %s\n",
+                 value->expr.op, ndx, KeyInfoText(info, keyi));
         return false;
     }
-    if ((keyi->numLevels[ndx] < nActs || darray_empty(keyi->acts[ndx])) &&
-        !ResizeKeyGroup(keyi, ndx, nActs, nActs, true)) {
-        WSGO("Could not resize group %d of key %s\n", ndx,
-              longText(keyi->name));
-        ACTION("Actions lost\n");
+
+    if (groupi->defined & GROUP_FIELD_ACTS) {
+        log_wsgo(info->ctx,
+                 "Actions for key %s, group %u already defined\n",
+                 KeyInfoText(info, keyi), ndx);
         return false;
     }
-    keyi->actsDefined |= (1 << ndx);
 
-    toAct = (struct xkb_any_action *) darray_mem(keyi->acts[ndx], 0);
-    act = value->value.child;
-    for (i = 0; i < nActs; i++, toAct++) {
-        if (!HandleActionDef(act, keymap, toAct, info->action)) {
-            ERROR("Illegal action definition for %s\n",
-                  longText(keyi->name));
-            ACTION("Action for group %d/level %d ignored\n", ndx + 1, i + 1);
-        }
+    nActs = 0;
+    for (act = value->actions.actions; act; act = (ExprDef *) act->common.next)
+        nActs++;
+
+    if (darray_size(groupi->levels) < nActs)
+        darray_resize0(groupi->levels, nActs);
+
+    groupi->defined |= GROUP_FIELD_ACTS;
+
+    act = value->actions.actions;
+    for (unsigned i = 0; i < nActs; i++) {
+        union xkb_action *toAct = &darray_item(groupi->levels, i).action;
+
+        if (!HandleActionDef(info->ctx, info->actions, &info->mods, act, toAct))
+            log_err(info->ctx,
+                    "Illegal action definition for %s; "
+                    "Action for group %u/level %u ignored\n",
+                    KeyInfoText(info, keyi), ndx + 1, i + 1);
+
         act = (ExprDef *) act->common.next;
     }
+
     return true;
 }
 
-static const LookupEntry lockingEntries[] = {
-    { "true", XkbKB_Lock },
-    { "yes", XkbKB_Lock },
-    { "on", XkbKB_Lock },
-    { "false", XkbKB_Default },
-    { "no", XkbKB_Default },
-    { "off", XkbKB_Default },
-    { "permanent", XkbKB_Lock | XkbKB_Permanent },
-    { NULL, 0 }
-};
-
 static const LookupEntry repeatEntries[] = {
-    { "true", RepeatYes },
-    { "yes", RepeatYes },
-    { "on", RepeatYes },
-    { "false", RepeatNo },
-    { "no", RepeatNo },
-    { "off", RepeatNo },
-    { "default", RepeatUndefined },
+    { "true", KEY_REPEAT_YES },
+    { "yes", KEY_REPEAT_YES },
+    { "on", KEY_REPEAT_YES },
+    { "false", KEY_REPEAT_NO },
+    { "no", KEY_REPEAT_NO },
+    { "off", KEY_REPEAT_NO },
+    { "default", KEY_REPEAT_UNDEFINED },
     { NULL, 0 }
 };
 
 static bool
-SetSymbolsField(KeyInfo *keyi, struct xkb_keymap *keymap, char *field,
-                ExprDef *arrayNdx, ExprDef *value, SymbolsInfo *info)
+SetSymbolsField(SymbolsInfo *info, KeyInfo *keyi, const char *field,
+                ExprDef *arrayNdx, ExprDef *value)
 {
-    bool ok = true;
-    ExprResult tmp;
-
-    if (strcasecmp(field, "type") == 0) {
-        ExprResult ndx;
-        if ((!ExprResolveString(keymap->ctx, value, &tmp))
-            && (warningLevel > 0)) {
-            WARN("The type field of a key symbol map must be a string\n");
-            ACTION("Ignoring illegal type definition\n");
-        }
-        if (arrayNdx == NULL) {
-            keyi->dfltType = xkb_atom_intern(keymap->ctx, tmp.str);
-            keyi->defs.defined |= _Key_Type_Dflt;
-        }
-        else if (!ExprResolveGroup(keymap->ctx, arrayNdx, &ndx)) {
-            ERROR("Illegal group index for type of key %s\n",
-                  longText(keyi->name));
-            ACTION("Definition with non-integer array index ignored\n");
-            free(tmp.str);
+    if (istreq(field, "type")) {
+        xkb_layout_index_t ndx;
+        xkb_atom_t val;
+
+        if (!ExprResolveString(info->ctx, value, &val)) {
+            log_err(info->ctx,
+                    "The type field of a key symbol map must be a string; "
+                    "Ignoring illegal type definition\n");
             return false;
         }
-        else {
-            keyi->types[ndx.uval - 1] = xkb_atom_intern(keymap->ctx, tmp.str);
-            keyi->typesDefined |= (1 << (ndx.uval - 1));
+
+        if (!arrayNdx) {
+            keyi->default_type = val;
+            keyi->defined |= KEY_FIELD_DEFAULT_TYPE;
         }
-        free(tmp.str);
-    }
-    else if (strcasecmp(field, "symbols") == 0)
-        return AddSymbolsToKey(keyi, keymap, arrayNdx, value, info);
-    else if (strcasecmp(field, "actions") == 0)
-        return AddActionsToKey(keyi, keymap, arrayNdx, value, info);
-    else if ((strcasecmp(field, "vmods") == 0) ||
-             (strcasecmp(field, "virtualmods") == 0) ||
-             (strcasecmp(field, "virtualmodifiers") == 0)) {
-        ok = ExprResolveVModMask(value, &tmp, keymap);
-        if (ok) {
-            keyi->vmodmap = (tmp.uval >> 8);
-            keyi->defs.defined |= _Key_VModMap;
+        else if (!ExprResolveGroup(info->ctx, arrayNdx, &ndx)) {
+            log_err_with_code(info->ctx, XKB_ERROR_UNSUPPORTED_GROUP_INDEX,
+                    "Illegal group index for type of key %s; "
+                    "Definition with non-integer array index ignored\n",
+                    KeyInfoText(info, keyi));
+            return false;
         }
         else {
-            ERROR("Expected a virtual modifier mask, found %s\n",
-                  exprOpText(value->op));
-            ACTION("Ignoring virtual modifiers definition for key %s\n",
-                   longText(keyi->name));
+            ndx--;
+            if (ndx >= darray_size(keyi->groups))
+                darray_resize0(keyi->groups, ndx + 1);
+            darray_item(keyi->groups, ndx).type = val;
+            darray_item(keyi->groups, ndx).defined |= GROUP_FIELD_TYPE;
+        }
+    }
+    else if (istreq(field, "symbols")) {
+        return AddSymbolsToKey(info, keyi, arrayNdx, value);
+    }
+    else if (istreq(field, "actions")) {
+        return AddActionsToKey(info, keyi, arrayNdx, value);
+    }
+    else if (istreq(field, "vmods") ||
+             istreq(field, "virtualmods") ||
+             istreq(field, "virtualmodifiers")) {
+        xkb_mod_mask_t mask;
+
+        if (!ExprResolveModMask(info->ctx, value, MOD_VIRT, &info->mods,
+                                &mask)) {
+            log_err(info->ctx,
+                    "Expected a virtual modifier mask, found %s; "
+                    "Ignoring virtual modifiers definition for key %s\n",
+                    expr_op_type_to_string(value->expr.op),
+                    KeyInfoText(info, keyi));
+            return false;
         }
-    }
-    else if ((strcasecmp(field, "locking") == 0) ||
-             (strcasecmp(field, "lock") == 0) ||
-             (strcasecmp(field, "locks") == 0)) {
-        ok = ExprResolveEnum(keymap->ctx, value, &tmp, lockingEntries);
-        if (ok)
-            keyi->behavior.type = tmp.uval;
-        keyi->defs.defined |= _Key_Behavior;
-    }
-    else if ((strcasecmp(field, "radiogroup") == 0) ||
-             (strcasecmp(field, "permanentradiogroup") == 0) ||
-             (strcasecmp(field, "allownone") == 0)) {
-        ERROR("Radio groups not supported\n");
-        ACTION("Ignoring radio group specification for key %s\n",
-               longText(keyi->name));
-        return false;
-    }
-    else if (uStrCasePrefix("overlay", field) ||
-             uStrCasePrefix("permanentoverlay", field)) {
-        ERROR("Overlays not supported\n");
-        ACTION("Ignoring overlay specification for key %s\n",
-               longText(keyi->name));
-    }
-    else if ((strcasecmp(field, "repeating") == 0) ||
-             (strcasecmp(field, "repeats") == 0) ||
-             (strcasecmp(field, "repeat") == 0)) {
-        ok = ExprResolveEnum(keymap->ctx, value, &tmp, repeatEntries);
-        if (!ok) {
-            ERROR("Illegal repeat setting for %s\n",
-                  longText(keyi->name));
-            ACTION("Non-boolean repeat setting ignored\n");
+
+        keyi->vmodmap = mask;
+        keyi->defined |= KEY_FIELD_VMODMAP;
+    }
+    else if (istreq(field, "locking") ||
+             istreq(field, "lock") ||
+             istreq(field, "locks")) {
+        log_vrb(info->ctx, 1,
+                "Key behaviors not supported; "
+                "Ignoring locking specification for key %s\n",
+                KeyInfoText(info, keyi));
+    }
+    else if (istreq(field, "radiogroup") ||
+             istreq(field, "permanentradiogroup") ||
+             istreq(field, "allownone")) {
+        log_vrb(info->ctx, 1,
+                "Radio groups not supported; "
+                "Ignoring radio group specification for key %s\n",
+                KeyInfoText(info, keyi));
+    }
+    else if (istreq_prefix("overlay", field) ||
+             istreq_prefix("permanentoverlay", field)) {
+        log_vrb(info->ctx, 1,
+                "Overlays not supported; "
+                "Ignoring overlay specification for key %s\n",
+                KeyInfoText(info, keyi));
+    }
+    else if (istreq(field, "repeating") ||
+             istreq(field, "repeats") ||
+             istreq(field, "repeat")) {
+        unsigned int val;
+
+        if (!ExprResolveEnum(info->ctx, value, &val, repeatEntries)) {
+            log_err(info->ctx,
+                    "Illegal repeat setting for %s; "
+                    "Non-boolean repeat setting ignored\n",
+                    KeyInfoText(info, keyi));
             return false;
         }
-        keyi->repeat = tmp.uval;
-        keyi->defs.defined |= _Key_Repeat;
-    }
-    else if ((strcasecmp(field, "groupswrap") == 0) ||
-             (strcasecmp(field, "wrapgroups") == 0)) {
-        ok = ExprResolveBoolean(keymap->ctx, value, &tmp);
-        if (!ok) {
-            ERROR("Illegal groupsWrap setting for %s\n",
-                  longText(keyi->name));
-            ACTION("Non-boolean value ignored\n");
+
+        keyi->repeat = val;
+        keyi->defined |= KEY_FIELD_REPEAT;
+    }
+    else if (istreq(field, "groupswrap") ||
+             istreq(field, "wrapgroups")) {
+        bool set;
+
+        if (!ExprResolveBoolean(info->ctx, value, &set)) {
+            log_err(info->ctx,
+                    "Illegal groupsWrap setting for %s; "
+                    "Non-boolean value ignored\n",
+                    KeyInfoText(info, keyi));
             return false;
         }
-        if (tmp.uval)
-            keyi->out_of_range_group_action = XkbWrapIntoRange;
-        else
-            keyi->out_of_range_group_action = XkbClampIntoRange;
-        keyi->defs.defined |= _Key_GroupInfo;
-    }
-    else if ((strcasecmp(field, "groupsclamp") == 0) ||
-             (strcasecmp(field, "clampgroups") == 0)) {
-        ok = ExprResolveBoolean(keymap->ctx, value, &tmp);
-        if (!ok) {
-            ERROR("Illegal groupsClamp setting for %s\n",
-                  longText(keyi->name));
-            ACTION("Non-boolean value ignored\n");
+
+        keyi->out_of_range_group_action = (set ? RANGE_WRAP : RANGE_SATURATE);
+        keyi->defined |= KEY_FIELD_GROUPINFO;
+    }
+    else if (istreq(field, "groupsclamp") ||
+             istreq(field, "clampgroups")) {
+        bool set;
+
+        if (!ExprResolveBoolean(info->ctx, value, &set)) {
+            log_err(info->ctx,
+                    "Illegal groupsClamp setting for %s; "
+                    "Non-boolean value ignored\n",
+                    KeyInfoText(info, keyi));
             return false;
         }
-        if (tmp.uval)
-            keyi->out_of_range_group_action = XkbClampIntoRange;
-        else
-            keyi->out_of_range_group_action = XkbWrapIntoRange;
-        keyi->defs.defined |= _Key_GroupInfo;
-    }
-    else if ((strcasecmp(field, "groupsredirect") == 0) ||
-             (strcasecmp(field, "redirectgroups") == 0)) {
-        if (!ExprResolveGroup(keymap->ctx, value, &tmp)) {
-            ERROR("Illegal group index for redirect of key %s\n",
-                  longText(keyi->name));
-            ACTION("Definition with non-integer group ignored\n");
+
+        keyi->out_of_range_group_action = (set ? RANGE_SATURATE : RANGE_WRAP);
+        keyi->defined |= KEY_FIELD_GROUPINFO;
+    }
+    else if (istreq(field, "groupsredirect") ||
+             istreq(field, "redirectgroups")) {
+        xkb_layout_index_t grp;
+
+        if (!ExprResolveGroup(info->ctx, value, &grp)) {
+            log_err_with_code(info->ctx, XKB_ERROR_UNSUPPORTED_GROUP_INDEX,
+                    "Illegal group index for redirect of key %s; "
+                    "Definition with non-integer group ignored\n",
+                    KeyInfoText(info, keyi));
             return false;
         }
-        keyi->out_of_range_group_action = XkbRedirectIntoRange;
-        keyi->out_of_range_group_number = tmp.uval - 1;
-        keyi->defs.defined |= _Key_GroupInfo;
+
+        keyi->out_of_range_group_action = RANGE_REDIRECT;
+        keyi->out_of_range_group_number = grp - 1;
+        keyi->defined |= KEY_FIELD_GROUPINFO;
     }
     else {
-        ERROR("Unknown field %s in a symbol interpretation\n", field);
-        ACTION("Definition ignored\n");
-        ok = false;
+        log_err(info->ctx,
+                "Unknown field %s in a symbol interpretation; "
+                "Definition ignored\n",
+                field);
+        return false;
     }
-    return ok;
+
+    return true;
 }
 
-static int
-SetGroupName(SymbolsInfo *info, struct xkb_keymap *keymap, ExprDef *arrayNdx,
-             ExprDef *value)
+static bool
+SetGroupName(SymbolsInfo *info, ExprDef *arrayNdx, ExprDef *value)
 {
-    ExprResult tmp, name;
+    xkb_layout_index_t group, group_to_use;
+    xkb_atom_t name;
 
-    if ((arrayNdx == NULL) && (warningLevel > 0)) {
-        WARN("You must specify an index when specifying a group name\n");
-        ACTION("Group name definition without array subscript ignored\n");
+    if (!arrayNdx) {
+        log_vrb(info->ctx, 1,
+                "You must specify an index when specifying a group name; "
+                "Group name definition without array subscript ignored\n");
         return false;
     }
-    if (!ExprResolveGroup(keymap->ctx, arrayNdx, &tmp)) {
-        ERROR("Illegal index in group name definition\n");
-        ACTION("Definition with non-integer array index ignored\n");
+
+    if (!ExprResolveGroup(info->ctx, arrayNdx, &group)) {
+        log_err_with_code(info->ctx, XKB_ERROR_UNSUPPORTED_GROUP_INDEX,
+                "Illegal index in group name definition; "
+                "Definition with non-integer array index ignored\n");
+        return false;
+    }
+
+    if (!ExprResolveString(info->ctx, value, &name)) {
+        log_err(info->ctx,
+                "Group name must be a string; "
+                "Illegal name for group %d ignored\n", group);
         return false;
     }
-    if (!ExprResolveString(keymap->ctx, value, &name)) {
-        ERROR("Group name must be a string\n");
-        ACTION("Illegal name for group %d ignored\n", tmp.uval);
+
+    if (info->explicit_group == XKB_LAYOUT_INVALID) {
+        group_to_use = group - 1;
+    }
+    else if (group - 1 == 0) {
+        group_to_use = info->explicit_group;
+    }
+    else {
+        log_warn_with_code(info->ctx,
+                 XKB_WARNING_NON_BASE_GROUP_NAME,
+                 "An explicit group was specified for the '%s' map, "
+                 "but it provides a name for a group other than Group1 (%d); "
+                 "Ignoring group name '%s'\n",
+                 info->name, group,
+                 xkb_atom_text(info->ctx, name));
         return false;
     }
-    info->groupNames[tmp.uval - 1 + info->explicit_group] =
-        xkb_atom_intern(keymap->ctx, name.str);
-    free(name.str);
+
+    if (group_to_use >= darray_size(info->group_names))
+        darray_resize0(info->group_names, group_to_use + 1);
+    darray_item(info->group_names, group_to_use) = name;
 
     return true;
 }
 
-static int
-HandleSymbolsVar(VarDef *stmt, struct xkb_keymap *keymap, SymbolsInfo *info)
+static bool
+HandleGlobalVar(SymbolsInfo *info, VarDef *stmt)
 {
-    ExprResult elem, field;
+    const char *elem, *field;
     ExprDef *arrayNdx;
     bool ret;
 
-    if (ExprResolveLhs(keymap, stmt->name, &elem, &field, &arrayNdx) == 0)
-        return 0;               /* internal error, already reported */
-    if (elem.str && (strcasecmp(elem.str, "key") == 0)) {
-        ret = SetSymbolsField(&info->dflt, keymap, field.str, arrayNdx,
-                              stmt->value, info);
-    }
-    else if ((elem.str == NULL) && ((strcasecmp(field.str, "name") == 0) ||
-                                    (strcasecmp(field.str, "groupname") ==
-                                     0))) {
-        ret = SetGroupName(info, keymap, arrayNdx, stmt->value);
-    }
-    else if ((elem.str == NULL)
-             && ((strcasecmp(field.str, "groupswrap") == 0) ||
-                 (strcasecmp(field.str, "wrapgroups") == 0))) {
-        ERROR("Global \"groupswrap\" not supported\n");
-        ACTION("Ignored\n");
+    if (!ExprResolveLhs(info->ctx, stmt->name, &elem, &field, &arrayNdx))
+        return false;
+
+    if (elem && istreq(elem, "key")) {
+        ret = SetSymbolsField(info, &info->default_key, field, arrayNdx,
+                              stmt->value);
+    }
+    else if (!elem && (istreq(field, "name") ||
+                       istreq(field, "groupname"))) {
+        ret = SetGroupName(info, arrayNdx, stmt->value);
+    }
+    else if (!elem && (istreq(field, "groupswrap") ||
+                       istreq(field, "wrapgroups"))) {
+        log_err(info->ctx,
+                "Global \"groupswrap\" not supported; Ignored\n");
         ret = true;
     }
-    else if ((elem.str == NULL)
-             && ((strcasecmp(field.str, "groupsclamp") == 0) ||
-                 (strcasecmp(field.str, "clampgroups") == 0))) {
-        ERROR("Global \"groupsclamp\" not supported\n");
-        ACTION("Ignored\n");
+    else if (!elem && (istreq(field, "groupsclamp") ||
+                       istreq(field, "clampgroups"))) {
+        log_err(info->ctx,
+                "Global \"groupsclamp\" not supported; Ignored\n");
         ret = true;
     }
-    else if ((elem.str == NULL)
-             && ((strcasecmp(field.str, "groupsredirect") == 0) ||
-                 (strcasecmp(field.str, "redirectgroups") == 0))) {
-        ERROR("Global \"groupsredirect\" not supported\n");
-        ACTION("Ignored\n");
+    else if (!elem && (istreq(field, "groupsredirect") ||
+                       istreq(field, "redirectgroups"))) {
+        log_err(info->ctx,
+                "Global \"groupsredirect\" not supported; Ignored\n");
         ret = true;
     }
-    else if ((elem.str == NULL) &&
-             (strcasecmp(field.str, "allownone") == 0)) {
-        ERROR("Radio groups not supported\n");
-        ACTION("Ignoring \"allownone\" specification\n");
+    else if (!elem && istreq(field, "allownone")) {
+        log_err(info->ctx,
+                "Radio groups not supported; "
+                "Ignoring \"allownone\" specification\n");
         ret = true;
     }
     else {
-        ret = SetActionField(keymap, elem.str, field.str, arrayNdx,
-                             stmt->value, &info->action);
+        ret = SetActionField(info->ctx, info->actions, &info->mods,
+                             elem, field, arrayNdx, stmt->value);
     }
 
-    free(elem.str);
-    free(field.str);
     return ret;
 }
 
 static bool
-HandleSymbolsBody(VarDef *def, struct xkb_keymap *keymap, KeyInfo *keyi,
-                  SymbolsInfo *info)
+HandleSymbolsBody(SymbolsInfo *info, VarDef *def, KeyInfo *keyi)
 {
     bool ok = true;
-    ExprResult tmp, field;
+    const char *elem, *field;
     ExprDef *arrayNdx;
 
-    for (; def != NULL; def = (VarDef *) def->common.next) {
-        if ((def->name) && (def->name->type == ExprFieldRef)) {
-            ok = HandleSymbolsVar(def, keymap, info);
+    for (; def; def = (VarDef *) def->common.next) {
+        if (def->name && def->name->expr.op == EXPR_FIELD_REF) {
+            log_err(info->ctx,
+                    "Cannot set a global default value from within a key statement; "
+                    "Move statements to the global file scope\n");
             continue;
         }
+
+        if (!def->name) {
+            if (!def->value || def->value->expr.op == EXPR_KEYSYM_LIST)
+                field = "symbols";
+            else
+                field = "actions";
+            arrayNdx = NULL;
+        }
         else {
-            if (def->name == NULL) {
-                if ((def->value == NULL)
-                    || (def->value->op == ExprKeysymList))
-                    field.str = strdup("symbols");
-                else
-                    field.str = strdup("actions");
-                arrayNdx = NULL;
-            }
-            else {
-                ok = ExprResolveLhs(keymap, def->name, &tmp, &field,
-                                    &arrayNdx);
-            }
-            if (ok)
-                ok = SetSymbolsField(keyi, keymap, field.str, arrayNdx,
-                                     def->value, info);
-            free(field.str);
+            ok = ExprResolveLhs(info->ctx, def->name, &elem, &field,
+                                &arrayNdx);
         }
+
+        if (ok)
+            ok = SetSymbolsField(info, keyi, field, arrayNdx, def->value);
     }
+
     return ok;
 }
 
 static bool
 SetExplicitGroup(SymbolsInfo *info, KeyInfo *keyi)
 {
-    unsigned group = info->explicit_group;
+    xkb_layout_index_t i;
+    GroupInfo *groupi;
+    bool warn = false;
 
-    if (group == 0)
+    if (info->explicit_group == XKB_LAYOUT_INVALID)
         return true;
 
-    if ((keyi->typesDefined | keyi->symsDefined | keyi->actsDefined) & ~1) {
-        int i;
-        WARN("For the map %s an explicit group specified\n", info->name);
-        WARN("but key %s has more than one group defined\n",
-             longText(keyi->name));
-        ACTION("All groups except first one will be ignored\n");
-        for (i = 1; i < XkbNumKbdGroups; i++) {
-            keyi->numLevels[i] = 0;
-            darray_free(keyi->syms[i]);
-            darray_free(keyi->acts[i]);
-            keyi->types[i] = 0;
+    darray_enumerate_from(i, groupi, keyi->groups, 1) {
+        if (groupi->defined) {
+            warn = true;
+            ClearGroupInfo(groupi);
+            InitGroupInfo(groupi);
         }
     }
-    keyi->typesDefined = keyi->symsDefined = keyi->actsDefined = 1 << group;
-
-    keyi->numLevels[group] = keyi->numLevels[0];
-    keyi->numLevels[0] = 0;
-    keyi->syms[group] = keyi->syms[0];
-    darray_init(keyi->syms[0]);
-    keyi->symsMapIndex[group] = keyi->symsMapIndex[0];
-    darray_init(keyi->symsMapIndex[0]);
-    keyi->symsMapNumEntries[group] = keyi->symsMapNumEntries[0];
-    darray_init(keyi->symsMapNumEntries[0]);
-    keyi->acts[group] = keyi->acts[0];
-    darray_init(keyi->acts[0]);
-    keyi->types[group] = keyi->types[0];
-    keyi->types[0] = 0;
+
+    if (warn) {
+        log_warn_with_code(info->ctx,
+                 XKB_WARNING_MULTIPLE_GROUPS_AT_ONCE,
+                 "For the map %s an explicit group specified, "
+                 "but key %s has more than one group defined; "
+                 "All groups except first one will be ignored\n",
+                 info->name, KeyInfoText(info, keyi));
+    }
+
+    darray_resize0(keyi->groups, info->explicit_group + 1);
+    if (info->explicit_group > 0) {
+        darray_item(keyi->groups, info->explicit_group) =
+            darray_item(keyi->groups, 0);
+        InitGroupInfo(&darray_item(keyi->groups, 0));
+    }
+
     return true;
 }
 
-static int
-HandleSymbolsDef(SymbolsDef *stmt, struct xkb_keymap *keymap,
-                 SymbolsInfo *info)
+static bool
+HandleSymbolsDef(SymbolsInfo *info, SymbolsDef *stmt)
 {
     KeyInfo keyi;
 
-    InitKeyInfo(&keyi, info->file_id);
-    CopyKeyInfo(&info->dflt, &keyi, false);
-    keyi.defs.merge = stmt->merge;
-    keyi.name = KeyNameToLong(stmt->keyName);
-    if (!HandleSymbolsBody((VarDef *) stmt->symbols, keymap, &keyi, info)) {
+    keyi = info->default_key;
+    darray_init(keyi.groups);
+    darray_copy(keyi.groups, info->default_key.groups);
+    for (xkb_layout_index_t i = 0; i < darray_size(keyi.groups); i++)
+        CopyGroupInfo(&darray_item(keyi.groups, i),
+                      &darray_item(info->default_key.groups, i));
+    keyi.merge = stmt->merge;
+    keyi.name = stmt->keyName;
+
+    if (!HandleSymbolsBody(info, stmt->symbols, &keyi)) {
         info->errorCount++;
         return false;
     }
@@ -1319,42 +1156,59 @@ HandleSymbolsDef(SymbolsDef *stmt, struct xkb_keymap *keymap,
         return false;
     }
 
-    if (!AddKeySymbols(info, &keyi, keymap)) {
+    if (!AddKeySymbols(info, &keyi, true)) {
         info->errorCount++;
         return false;
     }
+
     return true;
 }
 
 static bool
-HandleModMapDef(ModMapDef *def, struct xkb_keymap *keymap, SymbolsInfo *info)
+HandleModMapDef(SymbolsInfo *info, ModMapDef *def)
 {
-    ExprDef *key;
     ModMapEntry tmp;
-    ExprResult rtrn;
+    xkb_mod_index_t ndx;
     bool ok;
-
-    if (!LookupModIndex(keymap->ctx, NULL, def->modifier, TypeInt, &rtrn)) {
-        ERROR("Illegal modifier map definition\n");
-        ACTION("Ignoring map for non-modifier \"%s\"\n",
-               xkb_atom_text(keymap->ctx, def->modifier));
-        return false;
+    struct xkb_context *ctx = info->ctx;
+    const char *modifier_name = xkb_atom_text(ctx, def->modifier);
+
+    if (istreq(modifier_name, "none")) {
+        // Handle special "None" entry
+        ndx = XKB_MOD_NONE;
+    } else {
+        // Handle normal entry
+        ndx = XkbModNameToIndex(&info->mods, def->modifier, MOD_REAL);
+        if (ndx == XKB_MOD_INVALID) {
+            log_err(info->ctx,
+                    "Illegal modifier map definition; "
+                    "Ignoring map for non-modifier \"%s\"\n",
+                    xkb_atom_text(ctx, def->modifier));
+            return false;
+        }
     }
+
     ok = true;
-    tmp.modifier = rtrn.uval;
-    for (key = def->keys; key != NULL; key = (ExprDef *) key->common.next) {
-        if ((key->op == ExprValue) && (key->type == TypeKeyName)) {
+    tmp.modifier = ndx;
+    tmp.merge = def->merge;
+
+    for (ExprDef *key = def->keys; key; key = (ExprDef *) key->common.next) {
+        xkb_keysym_t sym;
+
+        if (key->expr.op == EXPR_VALUE &&
+            key->expr.value_type == EXPR_TYPE_KEYNAME) {
             tmp.haveSymbol = false;
-            tmp.u.keyName = KeyNameToLong(key->value.keyName);
+            tmp.u.keyName = key->key_name.key_name;
         }
-        else if (ExprResolveKeySym(keymap->ctx, key, &rtrn)) {
+        else if (ExprResolveKeySym(ctx, key, &sym)) {
             tmp.haveSymbol = true;
-            tmp.u.keySym = rtrn.uval;
+            tmp.u.keySym = sym;
         }
         else {
-            ERROR("Modmap entries may contain only key names or keysyms\n");
-            ACTION("Illegal definition for %s modifier ignored\n",
-                   XkbcModIndexText(tmp.modifier));
+            log_err(info->ctx,
+                    "Modmap entries may contain only key names or keysyms; "
+                    "Illegal definition for %s modifier ignored\n",
+                    ModIndexText(info->ctx, &info->mods, tmp.modifier));
             continue;
         }
 
@@ -1364,67 +1218,52 @@ HandleModMapDef(ModMapDef *def, struct xkb_keymap *keymap, SymbolsInfo *info)
 }
 
 static void
-HandleSymbolsFile(XkbFile *file, struct xkb_keymap *keymap,
-                  enum merge_mode merge, SymbolsInfo *info)
+HandleSymbolsFile(SymbolsInfo *info, XkbFile *file, enum merge_mode merge)
 {
-    ParseCommon *stmt;
+    bool ok;
 
     free(info->name);
-    info->name = uDupString(file->name);
-    stmt = file->defs;
-    while (stmt)
-    {
-        switch (stmt->stmtType) {
-        case StmtInclude:
-            if (!HandleIncludeSymbols((IncludeStmt *) stmt, keymap, info))
-                info->errorCount++;
+    info->name = strdup_safe(file->name);
+
+    for (ParseCommon *stmt = file->defs; stmt; stmt = stmt->next) {
+        switch (stmt->type) {
+        case STMT_INCLUDE:
+            ok = HandleIncludeSymbols(info, (IncludeStmt *) stmt);
             break;
-        case StmtSymbolsDef:
-            if (!HandleSymbolsDef((SymbolsDef *) stmt, keymap, info))
-                info->errorCount++;
+        case STMT_SYMBOLS:
+            ok = HandleSymbolsDef(info, (SymbolsDef *) stmt);
             break;
-        case StmtVarDef:
-            if (!HandleSymbolsVar((VarDef *) stmt, keymap, info))
-                info->errorCount++;
+        case STMT_VAR:
+            ok = HandleGlobalVar(info, (VarDef *) stmt);
             break;
-        case StmtVModDef:
-            if (!HandleVModDef((VModDef *) stmt, keymap, merge, &info->vmods))
-                info->errorCount++;
+        case STMT_VMOD:
+            ok = HandleVModDef(info->ctx, &info->mods, (VModDef *) stmt, merge);
             break;
-        case StmtInterpDef:
-            ERROR("Interpretation files may not include other types\n");
-            ACTION("Ignoring definition of symbol interpretation\n");
-            info->errorCount++;
-            break;
-        case StmtKeycodeDef:
-            ERROR("Interpretation files may not include other types\n");
-            ACTION("Ignoring definition of key name\n");
-            info->errorCount++;
-            break;
-        case StmtModMapDef:
-            if (!HandleModMapDef((ModMapDef *) stmt, keymap, info))
-                info->errorCount++;
+        case STMT_MODMAP:
+            ok = HandleModMapDef(info, (ModMapDef *) stmt);
             break;
         default:
-            WSGO("Unexpected statement type %d in HandleSymbolsFile\n",
-                 stmt->stmtType);
+            log_err(info->ctx,
+                    "Symbols files may not include other types; "
+                    "Ignoring %s\n", stmt_type_to_string(stmt->type));
+            ok = false;
             break;
         }
-        stmt = stmt->next;
+
+        if (!ok)
+            info->errorCount++;
+
         if (info->errorCount > 10) {
-#ifdef NOISY
-            ERROR("Too many errors\n");
-#endif
-            ACTION("Abandoning symbols file \"%s\"\n", file->topName);
+            log_err(info->ctx, "Abandoning symbols file \"%s\"\n",
+                    file->name);
             break;
         }
     }
 }
 
 /**
- * Given a keysym @sym, find the keycode which generates it
- * (returned in @kc_rtrn). This is used for example in a modifier
- * map definition, such as:
+ * Given a keysym @sym, return a key which generates it, or NULL.
+ * This is used for example in a modifier map definition, such as:
  *      modifier_map Lock           { Caps_Lock };
  * where we want to add the Lock modifier to the modmap of the key
  * which matches the keysym Caps_Lock.
@@ -1432,547 +1271,367 @@ HandleSymbolsFile(XkbFile *file, struct xkb_keymap *keymap,
  * is chosen first by lowest group in which the keysym appears, than
  * by lowest level and than by lowest key code.
  */
-static bool
-FindKeyForSymbol(struct xkb_keymap *keymap, xkb_keysym_t sym,
-                 xkb_keycode_t *kc_rtrn)
+static struct xkb_key *
+FindKeyForSymbol(struct xkb_keymap *keymap, xkb_keysym_t sym)
 {
-    xkb_keycode_t kc;
     struct xkb_key *key;
-    unsigned int group, level, min_group = UINT_MAX, min_level = UINT_MAX;
-
-    for (kc = keymap->min_key_code; kc <= keymap->max_key_code; kc++) {
-        key = XkbKey(keymap, kc);
-
-        for (group = 0; group < key->num_groups; group++) {
-            for (level = 0; level < XkbKeyGroupWidth(keymap, kc, group);
-                 level++) {
-                if (XkbKeyNumSyms(keymap, kc, group, level) != 1 ||
-                    (XkbKeySymEntry(keymap, kc, group, level))[0] != sym)
-                    continue;
-
-                /*
-                 * If the keysym was found in a group or level > 0, we must
-                 * keep looking since we might find a key in which the keysym
-                 * is in a lower group or level.
-                 */
-                if (group < min_group ||
-                    (group == min_group && level < min_level)) {
-                    *kc_rtrn = kc;
-                    if (group == 0 && level == 0) {
-                        return true;
-                    }
-                    else {
-                        min_group = group;
-                        min_level = level;
-                    }
+    xkb_layout_index_t group;
+    bool got_one_group, got_one_level;
+
+    group = 0;
+    do {
+        xkb_level_index_t level = 0;
+        got_one_group = false;
+        do {
+            got_one_level = false;
+            xkb_keys_foreach(key, keymap) {
+                if (group < key->num_groups &&
+                    level < XkbKeyNumLevels(key, group)) {
+                    got_one_group = got_one_level = true;
+                    if (key->groups[group].levels[level].num_syms == 1 &&
+                        key->groups[group].levels[level].u.sym == sym)
+                        return key;
                 }
             }
-        }
-    }
+            level++;
+        } while (got_one_level);
+        group++;
+    } while (got_one_group);
 
-    return min_group != UINT_MAX;
+    return NULL;
 }
 
-/**
- * Find the given name in the keymap->map->types and return its index.
- *
- * @param atom The atom to search for.
- * @param type_rtrn Set to the index of the name if found.
- *
- * @return true if found, false otherwise.
- */
-static bool
-FindNamedType(struct xkb_keymap *keymap, xkb_atom_t atom, unsigned *type_rtrn)
-{
-    unsigned n = 0;
-    const char *name = xkb_atom_text(keymap->ctx, atom);
-    struct xkb_key_type *type;
-
-    if (keymap) {
-        darray_foreach(type, keymap->types) {
-            if (strcmp(type->name, name) == 0) {
-                *type_rtrn = n;
-                return true;
-            }
-            n++;
-        }
-    }
-    return false;
-}
-
-/**
- * Assign a type to the given sym and return the Atom for the type assigned.
+/*
+ * Find an appropriate type for a group and return its name.
  *
  * Simple recipe:
  * - ONE_LEVEL for width 0/1
- * - ALPHABETIC for 2 shift levels, with lower/upercase
+ * - ALPHABETIC for 2 shift levels, with lower/upercase keysyms
  * - KEYPAD for keypad keys.
  * - TWO_LEVEL for other 2 shift level keys.
  * and the same for four level keys.
  *
- * @param width Number of sysms in syms.
- * @param syms The keysyms for the given key (must be size width).
- * @param typeNameRtrn Set to the Atom of the type name.
- *
- * @returns true if a type could be found, false otherwise.
- *
- * FIXME: I need to take the KeyInfo so I can look at symsMapIndex and
- *        all that fun stuff rather than just assuming there's always one
- *        symbol per level.
+ * FIXME: Decide how to handle multiple-syms-per-level, and do it.
  */
-static bool
-FindAutomaticType(struct xkb_keymap *keymap, int width,
-                  const xkb_keysym_t *syms, xkb_atom_t *typeNameRtrn,
-                  bool *autoType)
+static xkb_atom_t
+FindAutomaticType(struct xkb_context *ctx, GroupInfo *groupi)
 {
-    *autoType = false;
-    if ((width == 1) || (width == 0)) {
-        *typeNameRtrn = xkb_atom_intern(keymap->ctx, "ONE_LEVEL");
-        *autoType = true;
-    }
-    else if (width == 2) {
-        if (syms && xkb_keysym_is_lower(syms[0]) &&
-            xkb_keysym_is_upper(syms[1])) {
-            *typeNameRtrn = xkb_atom_intern(keymap->ctx, "ALPHABETIC");
-        }
-        else if (syms && (xkb_keysym_is_keypad(syms[0]) ||
-                          xkb_keysym_is_keypad(syms[1]))) {
-            *typeNameRtrn = xkb_atom_intern(keymap->ctx, "KEYPAD");
-            *autoType = true;
-        }
-        else {
-            *typeNameRtrn = xkb_atom_intern(keymap->ctx, "TWO_LEVEL");
-            *autoType = true;
-        }
+    xkb_keysym_t sym0, sym1;
+    const xkb_level_index_t width = darray_size(groupi->levels);
+
+#define GET_SYM(level) \
+    (darray_item(groupi->levels, level).num_syms == 0 ? \
+        XKB_KEY_NoSymbol : \
+     darray_item(groupi->levels, level).num_syms == 1 ? \
+        darray_item(groupi->levels, level).u.sym : \
+     /* num_syms > 1 */ \
+        darray_item(groupi->levels, level).u.syms[0])
+
+    if (width == 1 || width <= 0)
+        return xkb_atom_intern_literal(ctx, "ONE_LEVEL");
+
+    sym0 = GET_SYM(0);
+    sym1 = GET_SYM(1);
+
+    if (width == 2) {
+        if (xkb_keysym_is_lower(sym0) && xkb_keysym_is_upper(sym1))
+            return xkb_atom_intern_literal(ctx, "ALPHABETIC");
+
+        if (xkb_keysym_is_keypad(sym0) || xkb_keysym_is_keypad(sym1))
+            return xkb_atom_intern_literal(ctx, "KEYPAD");
+
+        return xkb_atom_intern_literal(ctx, "TWO_LEVEL");
     }
-    else if (width <= 4) {
-        if (syms && xkb_keysym_is_lower(syms[0]) &&
-            xkb_keysym_is_upper(syms[1]))
-            if (xkb_keysym_is_lower(syms[2]) && xkb_keysym_is_upper(syms[3]))
-                *typeNameRtrn =
-                    xkb_atom_intern(keymap->ctx, "FOUR_LEVEL_ALPHABETIC");
-            else
-                *typeNameRtrn = xkb_atom_intern(keymap->ctx,
-                                                "FOUR_LEVEL_SEMIALPHABETIC");
 
-        else if (syms && (xkb_keysym_is_keypad(syms[0]) ||
-                          xkb_keysym_is_keypad(syms[1])))
-            *typeNameRtrn = xkb_atom_intern(keymap->ctx, "FOUR_LEVEL_KEYPAD");
-        else
-            *typeNameRtrn = xkb_atom_intern(keymap->ctx, "FOUR_LEVEL");
-        /* XXX: why not set autoType here? */
+    if (width <= 4) {
+        if (xkb_keysym_is_lower(sym0) && xkb_keysym_is_upper(sym1)) {
+            xkb_keysym_t sym2, sym3;
+            sym2 = GET_SYM(2);
+            sym3 = (width == 4 ? GET_SYM(3) : XKB_KEY_NoSymbol);
+
+            if (xkb_keysym_is_lower(sym2) && xkb_keysym_is_upper(sym3))
+                return xkb_atom_intern_literal(ctx, "FOUR_LEVEL_ALPHABETIC");
+
+            return xkb_atom_intern_literal(ctx, "FOUR_LEVEL_SEMIALPHABETIC");
+        }
+
+        if (xkb_keysym_is_keypad(sym0) || xkb_keysym_is_keypad(sym1))
+            return xkb_atom_intern_literal(ctx, "FOUR_LEVEL_KEYPAD");
+
+        return xkb_atom_intern_literal(ctx, "FOUR_LEVEL");
     }
-    return ((width >= 0) && (width <= 4));
+
+    return XKB_ATOM_NONE;
+
+#undef GET_SYM
 }
 
-/**
- * Ensure the given KeyInfo is in a coherent state, i.e. no gaps between the
- * groups, and reduce to one group if all groups are identical anyway.
- */
-static void
-PrepareKeyDef(KeyInfo *keyi)
+static const struct xkb_key_type *
+FindTypeForGroup(struct xkb_keymap *keymap, KeyInfo *keyi,
+                 xkb_layout_index_t group, bool *explicit_type)
 {
-    int i, j, width, defined, lastGroup;
-    bool identical;
-
-    defined = keyi->symsDefined | keyi->actsDefined | keyi->typesDefined;
-    /* get highest group number */
-    for (i = XkbNumKbdGroups - 1; i >= 0; i--) {
-        if (defined & (1 << i))
-            break;
-    }
-    lastGroup = i;
+    unsigned int i;
+    GroupInfo *groupi = &darray_item(keyi->groups, group);
+    xkb_atom_t type_name = groupi->type;
 
-    if (lastGroup == 0)
-        return;
+    *explicit_type = true;
 
-    /* If there are empty groups between non-empty ones fill them with data */
-    /* from the first group. */
-    /* We can make a wrong assumption here. But leaving gaps is worse. */
-    for (i = lastGroup; i > 0; i--) {
-        if (defined & (1 << i))
-            continue;
-        width = keyi->numLevels[0];
-        if (keyi->typesDefined & 1) {
-            for (j = 0; j < width; j++) {
-                keyi->types[i] = keyi->types[0];
-            }
-            keyi->typesDefined |= 1 << i;
-        }
-        if ((keyi->actsDefined & 1) && !darray_empty(keyi->acts[0])) {
-            darray_copy(keyi->acts[i], keyi->acts[0]);
-            keyi->actsDefined |= 1 << i;
-        }
-        if ((keyi->symsDefined & 1) && !darray_empty(keyi->syms[0])) {
-            darray_copy(keyi->syms[i], keyi->syms[0]);
-            darray_copy(keyi->symsMapIndex[i], keyi->symsMapIndex[0]);
-            darray_copy(keyi->symsMapNumEntries[i],
-                        keyi->symsMapNumEntries[0]);
-            keyi->symsDefined |= 1 << i;
+    if (type_name == XKB_ATOM_NONE) {
+        if (keyi->default_type != XKB_ATOM_NONE) {
+            type_name  = keyi->default_type;
         }
-        if (defined & 1) {
-            keyi->numLevels[i] = keyi->numLevels[0];
+        else {
+            type_name = FindAutomaticType(keymap->ctx, groupi);
+            if (type_name != XKB_ATOM_NONE)
+                *explicit_type = false;
         }
     }
-    /* If all groups are completely identical remove them all */
-    /* exept the first one. */
-    identical = true;
-    for (i = lastGroup; i > 0; i--) {
-        if ((keyi->numLevels[i] != keyi->numLevels[0]) ||
-            (keyi->types[i] != keyi->types[0])) {
-            identical = false;
-            break;
-        }
-        if (!darray_same(keyi->syms[i], keyi->syms[0]) &&
-            (darray_empty(keyi->syms[i]) || darray_empty(keyi->syms[0]) ||
-             darray_size(keyi->syms[i]) != darray_size(keyi->syms[0]) ||
-             memcmp(darray_mem(keyi->syms[i], 0),
-                    darray_mem(keyi->syms[0], 0),
-                   sizeof(xkb_keysym_t) * darray_size(keyi->syms[0])))) {
-            identical = false;
-            break;
-        }
-        if (!darray_same(keyi->symsMapIndex[i], keyi->symsMapIndex[0]) &&
-            (darray_empty(keyi->symsMapIndex[i]) ||
-             darray_empty(keyi->symsMapIndex[0]) ||
-             memcmp(darray_mem(keyi->symsMapIndex[i], 0),
-                    darray_mem(keyi->symsMapIndex[0], 0),
-                    keyi->numLevels[0] * sizeof(int)))) {
-            identical = false;
-            continue;
-        }
-        if (!darray_same(keyi->symsMapNumEntries[i],
-                         keyi->symsMapNumEntries[0]) &&
-            (darray_empty(keyi->symsMapNumEntries[i]) ||
-             darray_empty(keyi->symsMapNumEntries[0]) ||
-             memcmp(darray_mem(keyi->symsMapNumEntries[i], 0),
-                    darray_mem(keyi->symsMapNumEntries[0], 0),
-                    keyi->numLevels[0] * sizeof(size_t)))) {
-            identical = false;
-            continue;
-        }
-        if (!darray_same(keyi->acts[i], keyi->acts[0]) &&
-            (darray_empty(keyi->acts[i]) || darray_empty(keyi->acts[0]) ||
-             memcmp(darray_mem(keyi->acts[i], 0),
-                    darray_mem(keyi->acts[0], 0),
-                    keyi->numLevels[0] * sizeof(union xkb_action)))) {
-            identical = false;
-            break;
-        }
+
+    if (type_name == XKB_ATOM_NONE) {
+        log_warn_with_code(keymap->ctx,
+                 XKB_WARNING_CANNOT_INFER_KEY_TYPE,
+                 "Couldn't find an automatic type for key '%s' group %d with %lu levels; "
+                 "Using the default type\n",
+                 KeyNameText(keymap->ctx, keyi->name), group + 1,
+                 (unsigned long) darray_size(groupi->levels));
+        goto use_default;
     }
-    if (identical) {
-        for (i = lastGroup; i > 0; i--) {
-            keyi->numLevels[i] = 0;
-            darray_free(keyi->syms[i]);
-            darray_free(keyi->symsMapIndex[i]);
-            darray_free(keyi->symsMapNumEntries[i]);
-            darray_free(keyi->acts[i]);
-            keyi->types[i] = 0;
-        }
-        keyi->symsDefined &= 1;
-        keyi->actsDefined &= 1;
-        keyi->typesDefined &= 1;
+
+    for (i = 0; i < keymap->num_types; i++)
+        if (keymap->types[i].name == type_name)
+            break;
+
+    if (i >= keymap->num_types) {
+        log_warn_with_code(keymap->ctx,
+                 XKB_WARNING_UNDEFINED_KEY_TYPE,
+                 "The type \"%s\" for key '%s' group %d was not previously defined; "
+                 "Using the default type\n",
+                 xkb_atom_text(keymap->ctx, type_name),
+                 KeyNameText(keymap->ctx, keyi->name), group + 1);
+        goto use_default;
     }
+
+    return &keymap->types[i];
+
+use_default:
+    /*
+     * Index 0 is guaranteed to contain something, usually
+     * ONE_LEVEL or at least some default one-level type.
+     */
+    return &keymap->types[0];
 }
 
-/**
- * Copy the KeyInfo into the keyboard description.
- *
- * This function recurses.
- */
 static bool
-CopySymbolsDef(struct xkb_keymap *keymap, KeyInfo *keyi, int start_from)
+CopySymbolsDefToKeymap(struct xkb_keymap *keymap, SymbolsInfo *info,
+                       KeyInfo *keyi)
 {
-    unsigned int i;
-    xkb_keycode_t kc;
     struct xkb_key *key;
-    unsigned int sizeSyms = 0;
-    unsigned width, tmp, nGroups;
-    struct xkb_key_type * type;
-    bool haveActions, autoType, useAlias;
-    unsigned types[XkbNumKbdGroups];
-    union xkb_action *outActs;
-    unsigned int symIndex = 0;
-
-    useAlias = (start_from == 0);
-
-    /* get the keycode for the key. */
-    if (!FindNamedKey(keymap, keyi->name, &kc, useAlias,
-                      CreateKeyNames(keymap), start_from)) {
-        if ((start_from == 0) && (warningLevel >= 5)) {
-            WARN("Key %s not found in keycodes\n", longText(keyi->name));
-            ACTION("Symbols ignored\n");
-        }
+    GroupInfo *groupi;
+    const GroupInfo *group0;
+    xkb_layout_index_t i;
+
+    /*
+     * The name is guaranteed to be real and not an alias (see
+     * AddKeySymbols), so 'false' is safe here.
+     */
+    key = XkbKeyByName(keymap, keyi->name, false);
+    if (!key) {
+        log_vrb_with_code(info->ctx, 5,
+                XKB_WARNING_UNDEFINED_KEYCODE,
+                "Key %s not found in keycodes; Symbols ignored\n",
+                KeyInfoText(info, keyi));
         return false;
     }
 
-    key = XkbKey(keymap, kc);
-
-    haveActions = false;
-    for (i = width = nGroups = 0; i < XkbNumKbdGroups; i++) {
-        if (((i + 1) > nGroups)
-            && (((keyi->symsDefined | keyi->actsDefined) & (1 << i))
-                || (keyi->typesDefined) & (1 << i)))
-            nGroups = i + 1;
-        if (!darray_empty(keyi->acts[i]))
-            haveActions = true;
-        autoType = false;
-        /* Assign the type to the key, if it is missing. */
-        if (keyi->types[i] == XKB_ATOM_NONE) {
-            if (keyi->dfltType != XKB_ATOM_NONE)
-                keyi->types[i] = keyi->dfltType;
-            else if (FindAutomaticType(keymap, keyi->numLevels[i],
-                                       darray_mem(keyi->syms[i], 0),
-                                       &keyi->types[i], &autoType)) { }
-            else {
-                if (warningLevel >= 5) {
-                    WARN("No automatic type for %d symbols\n",
-                          (unsigned int) keyi->numLevels[i]);
-                    ACTION("Using %s for the %s key (keycode %d)\n",
-                            xkb_atom_text(keymap->ctx, keyi->types[i]),
-                            longText(keyi->name), kc);
-                }
-            }
-        }
-        if (FindNamedType(keymap, keyi->types[i], &types[i])) {
-            if (!autoType || keyi->numLevels[i] > 2)
-                key->explicit |= (1 << i);
-        }
-        else {
-            if (warningLevel >= 3) {
-                WARN("Type \"%s\" is not defined\n",
-                     xkb_atom_text(keymap->ctx, keyi->types[i]));
-                ACTION("Using TWO_LEVEL for the %s key (keycode %d)\n",
-                       longText(keyi->name), kc);
-            }
-            types[i] = XkbTwoLevelIndex;
-        }
-        /* if the type specifies fewer levels than the key has, shrink the key */
-        type = &darray_item(keymap->types, types[i]);
-        if (type->num_levels < keyi->numLevels[i]) {
-            if (warningLevel > 0) {
-                WARN("Type \"%s\" has %d levels, but %s has %d symbols\n",
-                     type->name, type->num_levels,
-                     xkb_atom_text(keymap->ctx, keyi->name), keyi->numLevels[i]);
-                ACTION("Ignoring extra symbols\n");
-            }
-            keyi->numLevels[i] = type->num_levels;
-        }
-        if (keyi->numLevels[i] > width)
-            width = keyi->numLevels[i];
-        if (type->num_levels > width)
-            width = type->num_levels;
-        sizeSyms += darray_size(keyi->syms[i]);
+    /* Find the range of groups we need. */
+    key->num_groups = 0;
+    darray_enumerate(i, groupi, keyi->groups)
+        if (groupi->defined)
+            key->num_groups = i + 1;
+
+    if (key->num_groups <= 0)
+        return false; /* WSGO */
+
+    darray_resize(keyi->groups, key->num_groups);
+
+    /*
+     * If there are empty groups between non-empty ones, fill them with data
+     * from the first group.
+     * We can make a wrong assumption here. But leaving gaps is worse.
+     */
+    group0 = &darray_item(keyi->groups, 0);
+    darray_foreach_from(groupi, keyi->groups, 1) {
+        if (groupi->defined)
+            continue;
+
+        CopyGroupInfo(groupi, group0);
     }
 
-    darray_resize0(key->syms, sizeSyms);
+    key->groups = calloc(key->num_groups, sizeof(*key->groups));
 
-    if (haveActions) {
-        outActs = XkbcResizeKeyActions(keymap, kc, width * nGroups);
-        if (outActs == NULL) {
-            WSGO("Could not enlarge actions for %s (key %d)\n",
-                 longText(keyi->name), kc);
-            return false;
-        }
-        key->explicit |= XkbExplicitInterpretMask;
-    }
-    else
-        outActs = NULL;
-
-    key->num_groups = nGroups;
-    if (keyi->defs.defined & _Key_GroupInfo) {
-        key->out_of_range_group_number = keyi->out_of_range_group_number;
-        key->out_of_range_group_action = keyi->out_of_range_group_action;
-    }
-    key->width = width;
-    key->sym_index = calloc(nGroups * width, sizeof(*key->sym_index));
-    key->num_syms = calloc(nGroups * width, sizeof(*key->num_syms));
-
-    for (i = 0; i < nGroups; i++) {
-        /* assign kt_index[i] to the index of the type in map->types.
-         * kt_index[i] may have been set by a previous run (if we have two
-         * layouts specified). Let's not overwrite it with the ONE_LEVEL
-         * default group if we dont even have keys for this group anyway.
-         *
-         * FIXME: There should be a better fix for this.
-         */
-        if (keyi->numLevels[i])
-            key->kt_index[i] = types[i];
-        if (!darray_empty(keyi->syms[i])) {
-            /* fill key to "width" symbols*/
-            for (tmp = 0; tmp < width; tmp++) {
-                if (tmp < keyi->numLevels[i] &&
-                    darray_item(keyi->symsMapNumEntries[i], tmp) != 0) {
-                    memcpy(darray_mem(key->syms, symIndex),
-                           darray_mem(keyi->syms[i],
-                                      darray_item(keyi->symsMapIndex[i], tmp)),
-                           darray_item(keyi->symsMapNumEntries[i],
-                                       tmp) * sizeof(xkb_keysym_t));
-                    key->sym_index[(i * width) + tmp] = symIndex;
-                    key->num_syms[(i * width) + tmp] =
-                        darray_item(keyi->symsMapNumEntries[i], tmp);
-                    symIndex += key->num_syms[(i * width) + tmp];
-                }
-                else {
-                    key->sym_index[(i * width) + tmp] = -1;
-                    key->num_syms[(i * width) + tmp] = 0;
-                }
-                if (outActs != NULL && !darray_empty(keyi->acts[i])) {
-                    if (tmp < keyi->numLevels[i])
-                        outActs[tmp] = darray_item(keyi->acts[i], tmp);
-                    else
-                        outActs[tmp].type = XkbSA_NoAction;
-                }
-            }
+    /* Find and assign the groups' types in the keymap. */
+    darray_enumerate(i, groupi, keyi->groups) {
+        const struct xkb_key_type *type;
+        bool explicit_type;
+
+        type = FindTypeForGroup(keymap, keyi, i, &explicit_type);
+
+        /* Always have as many levels as the type specifies. */
+        if (type->num_levels < darray_size(groupi->levels)) {
+            struct xkb_level *leveli;
+
+            log_vrb_with_code(info->ctx, 1,
+                    XKB_WARNING_EXTRA_SYMBOLS_IGNORED,
+                    "Type \"%s\" has %d levels, but %s has %d levels; "
+                    "Ignoring extra symbols\n",
+                    xkb_atom_text(keymap->ctx, type->name), type->num_levels,
+                    KeyInfoText(info, keyi),
+                    (int) darray_size(groupi->levels));
+
+            darray_foreach_from(leveli, groupi->levels, type->num_levels)
+                ClearLevelInfo(leveli);
         }
-    }
-    switch (keyi->behavior.type & XkbKB_OpMask) {
-    case XkbKB_Default:
-        break;
+        darray_resize0(groupi->levels, type->num_levels);
 
-    default:
-        key->behavior = keyi->behavior;
-        key->explicit |= XkbExplicitBehaviorMask;
-        break;
+        key->groups[i].explicit_type = explicit_type;
+        key->groups[i].type = type;
     }
-    if (keyi->defs.defined & _Key_VModMap) {
+
+    /* Copy levels. */
+    darray_enumerate(i, groupi, keyi->groups)
+        darray_steal(groupi->levels, &key->groups[i].levels, NULL);
+
+    key->out_of_range_group_number = keyi->out_of_range_group_number;
+    key->out_of_range_group_action = keyi->out_of_range_group_action;
+
+    if (keyi->defined & KEY_FIELD_VMODMAP) {
         key->vmodmap = keyi->vmodmap;
-        key->explicit |= XkbExplicitVModMapMask;
+        key->explicit |= EXPLICIT_VMODMAP;
     }
-    if (keyi->repeat != RepeatUndefined) {
-        key->repeats = keyi->repeat == RepeatYes;
-        key->explicit |= XkbExplicitAutoRepeatMask;
+
+    if (keyi->repeat != KEY_REPEAT_UNDEFINED) {
+        key->repeats = (keyi->repeat == KEY_REPEAT_YES);
+        key->explicit |= EXPLICIT_REPEAT;
+    }
+
+    darray_foreach(groupi, keyi->groups) {
+        if (groupi->defined & GROUP_FIELD_ACTS) {
+            key->explicit |= EXPLICIT_INTERP;
+            break;
+        }
     }
 
-    /* do the same thing for the next key */
-    CopySymbolsDef(keymap, keyi, kc + 1);
     return true;
 }
 
 static bool
-CopyModMapDef(struct xkb_keymap *keymap, ModMapEntry *entry)
+CopyModMapDefToKeymap(struct xkb_keymap *keymap, SymbolsInfo *info,
+                      ModMapEntry *entry)
 {
-    xkb_keycode_t kc;
-
-    if (!entry->haveSymbol &&
-        !FindNamedKey(keymap, entry->u.keyName, &kc, true,
-                      CreateKeyNames(keymap), 0)) {
-        if (warningLevel >= 5) {
-            WARN("Key %s not found in keycodes\n",
-                 longText(entry->u.keyName));
-            ACTION("Modifier map entry for %s not updated\n",
-                   XkbcModIndexText(entry->modifier));
+    struct xkb_key *key;
+
+    if (!entry->haveSymbol) {
+        key = XkbKeyByName(keymap, entry->u.keyName, true);
+        if (!key) {
+            log_vrb_with_code(info->ctx, 5,
+                    XKB_WARNING_UNDEFINED_KEYCODE,
+                    "Key %s not found in keycodes; "
+                    "Modifier map entry for %s not updated\n",
+                    KeyNameText(info->ctx, entry->u.keyName),
+                    ModIndexText(info->ctx, &info->mods, entry->modifier));
+            return false;
         }
-        return false;
     }
-    else if (entry->haveSymbol &&
-             !FindKeyForSymbol(keymap, entry->u.keySym, &kc)) {
-        if (warningLevel > 5) {
-            WARN("Key \"%s\" not found in symbol map\n",
-                 XkbcKeysymText(entry->u.keySym));
-            ACTION("Modifier map entry for %s not updated\n",
-                   XkbcModIndexText(entry->modifier));
+    else {
+        key = FindKeyForSymbol(keymap, entry->u.keySym);
+        if (!key) {
+            log_vrb_with_code(info->ctx, 5,
+                    XKB_WARNING_UNRESOLVED_KEYMAP_SYMBOL,
+                    "Key \"%s\" not found in symbol map; "
+                    "Modifier map entry for %s not updated\n",
+                    KeysymText(info->ctx, entry->u.keySym),
+                    ModIndexText(info->ctx, &info->mods, entry->modifier));
+            return false;
         }
-        return false;
     }
 
-    XkbKey(keymap, kc)->modmap |= (1 << entry->modifier);
+    // Handle modMap None
+    if (entry->modifier != XKB_MOD_NONE) {
+        // Convert modifier index to modifier mask
+        key->modmap |= (1u << entry->modifier);
+    }
+
     return true;
 }
 
 static bool
-InitKeymapForSymbols(struct xkb_keymap *keymap)
+CopySymbolsToKeymap(struct xkb_keymap *keymap, SymbolsInfo *info)
 {
-    size_t nKeys = keymap->max_key_code + 1;
+    KeyInfo *keyi;
+    ModMapEntry *mm;
 
-    darray_resize0(keymap->keys, nKeys);
+    keymap->symbols_section_name = strdup_safe(info->name);
+    XkbEscapeMapName(keymap->symbols_section_name);
 
-    darray_resize0(keymap->acts, darray_size(keymap->acts) + 32 + 1);
+    keymap->mods = info->mods;
 
+    darray_steal(info->group_names,
+                 &keymap->group_names, &keymap->num_group_names);
+
+    darray_foreach(keyi, info->keys)
+        if (!CopySymbolsDefToKeymap(keymap, info, keyi))
+            info->errorCount++;
+
+    if (xkb_context_get_log_verbosity(keymap->ctx) > 3) {
+        struct xkb_key *key;
+
+        xkb_keys_foreach(key, keymap) {
+            if (key->name == XKB_ATOM_NONE)
+                continue;
+
+            if (key->num_groups < 1)
+                log_info(info->ctx,
+                         "No symbols defined for %s\n",
+                         KeyNameText(info->ctx, key->name));
+        }
+    }
+
+    darray_foreach(mm, info->modmaps)
+        if (!CopyModMapDefToKeymap(keymap, info, mm))
+            info->errorCount++;
+
+    /* XXX: If we don't ignore errorCount, things break. */
     return true;
 }
 
-/**
- * Handle the xkb_symbols section of an xkb file.
- *
- * @param file The parsed xkb_symbols section of the xkb file.
- * @param keymap Handle to the keyboard description to store the symbols in.
- * @param merge Merge strategy (e.g. MERGE_OVERRIDE).
- */
 bool
 CompileSymbols(XkbFile *file, struct xkb_keymap *keymap,
                enum merge_mode merge)
 {
-    int i;
-    bool ok;
-    xkb_keycode_t kc;
-    struct xkb_key *key;
     SymbolsInfo info;
-    KeyInfo *keyi;
+    ActionsInfo *actions;
 
-    InitSymbolsInfo(&info, keymap, file->id);
-    info.dflt.defs.merge = merge;
+    actions = NewActionsInfo();
+    if (!actions)
+        return false;
 
-    HandleSymbolsFile(file, keymap, merge, &info);
+    InitSymbolsInfo(&info, keymap, actions, &keymap->mods);
+    info.default_key.merge = merge;
 
-    if (darray_empty(info.keys))
-        goto err_info;
+    HandleSymbolsFile(&info, file, merge);
 
     if (info.errorCount != 0)
         goto err_info;
 
-    ok = InitKeymapForSymbols(keymap);
-    if (!ok)
+    if (!CopySymbolsToKeymap(keymap, &info))
         goto err_info;
 
-    if (info.name)
-        keymap->symbols_section_name = strdup(info.name);
-
-    /* now copy info into xkb. */
-    ApplyAliases(keymap, &info.aliases);
-
-    for (i = 0; i < XkbNumKbdGroups; i++) {
-        if (info.groupNames[i] != XKB_ATOM_NONE) {
-            free(keymap->group_names[i]);
-            keymap->group_names[i] = xkb_atom_strdup(keymap->ctx,
-                                                     info.groupNames[i]);
-        }
-    }
-
-    /* sanitize keys */
-    darray_foreach(keyi, info.keys)
-        PrepareKeyDef(keyi);
-
-    /* copy! */
-    darray_foreach(keyi, info.keys)
-        if (!CopySymbolsDef(keymap, keyi, 0))
-            info.errorCount++;
-
-    if (warningLevel > 3) {
-        for (kc = keymap->min_key_code; kc <= keymap->max_key_code; kc++) {
-            key = XkbKey(keymap, kc);
-            if (key->name[0] == '\0')
-                continue;
-
-            if (key->num_groups < 1)
-                WARN("No symbols defined for <%.4s> (keycode %d)\n",
-                     key->name, kc);
-        }
-    }
-
-    if (info.modMap) {
-        ModMapEntry *mm, *next;
-        for (mm = info.modMap; mm != NULL; mm = next) {
-            if (!CopyModMapDef(keymap, mm))
-                info.errorCount++;
-            next = (ModMapEntry *) mm->defs.next;
-        }
-    }
-
-    FreeSymbolsInfo(&info);
+    ClearSymbolsInfo(&info);
+    FreeActionsInfo(actions);
     return true;
 
 err_info:
-    FreeSymbolsInfo(&info);
+    FreeActionsInfo(actions);
+    ClearSymbolsInfo(&info);
     return false;
 }