keymap-dump: unbreak some complex lines
[platform/upstream/libxkbcommon.git] / src / xkbcomp / rules.c
1 /************************************************************
2  * Copyright (c) 1996 by Silicon Graphics Computer Systems, Inc.
3  *
4  * Permission to use, copy, modify, and distribute this
5  * software and its documentation for any purpose and without
6  * fee is hereby granted, provided that the above copyright
7  * notice appear in all copies and that both that copyright
8  * notice and this permission notice appear in supporting
9  * documentation, and that the name of Silicon Graphics not be
10  * used in advertising or publicity pertaining to distribution
11  * of the software without specific prior written permission.
12  * Silicon Graphics makes no representation about the suitability
13  * of this software for any purpose. It is provided "as is"
14  * without any express or implied warranty.
15  *
16  * SILICON GRAPHICS DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS
17  * SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
18  * AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL SILICON
19  * GRAPHICS BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL
20  * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
21  * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
22  * OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION  WITH
23  * THE USE OR PERFORMANCE OF THIS SOFTWARE.
24  *
25  ********************************************************/
26
27 /*
28  * Copyright © 2012 Ran Benita <ran234@gmail.com>
29  *
30  * Permission is hereby granted, free of charge, to any person obtaining a
31  * copy of this software and associated documentation files (the "Software"),
32  * to deal in the Software without restriction, including without limitation
33  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
34  * and/or sell copies of the Software, and to permit persons to whom the
35  * Software is furnished to do so, subject to the following conditions:
36  *
37  * The above copyright notice and this permission notice (including the next
38  * paragraph) shall be included in all copies or substantial portions of the
39  * Software.
40  *
41  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
42  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
43  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
44  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
45  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
46  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
47  * DEALINGS IN THE SOFTWARE.
48  */
49
50 #include "xkbcomp-priv.h"
51 #include "rules.h"
52 #include "include.h"
53 #include "scanner-utils.h"
54
55 /* Scanner / Lexer */
56
57 /* Values returned with some tokens, like yylval. */
58 union lvalue {
59     struct sval string;
60 };
61
62 enum rules_token {
63     TOK_END_OF_FILE = 0,
64     TOK_END_OF_LINE,
65     TOK_IDENTIFIER,
66     TOK_GROUP_NAME,
67     TOK_BANG,
68     TOK_EQUALS,
69     TOK_STAR,
70     TOK_ERROR
71 };
72
73 static inline bool
74 is_ident(char ch)
75 {
76     return is_graph(ch) && ch != '\\';
77 }
78
79 static enum rules_token
80 lex(struct scanner *s, union lvalue *val)
81 {
82 skip_more_whitespace_and_comments:
83     /* Skip spaces. */
84     while (chr(s, ' ') || chr(s, '\t'));
85
86     /* Skip comments. */
87     if (lit(s, "//")) {
88         while (!eof(s) && !eol(s)) next(s);
89     }
90
91     /* New line. */
92     if (eol(s)) {
93         while (eol(s)) next(s);
94         return TOK_END_OF_LINE;
95     }
96
97     /* Escaped line continuation. */
98     if (chr(s, '\\')) {
99         if (!eol(s)) {
100             scanner_err(s, "illegal new line escape; must appear at end of line");
101             return TOK_ERROR;
102         }
103         next(s);
104         goto skip_more_whitespace_and_comments;
105     }
106
107     /* See if we're done. */
108     if (eof(s)) return TOK_END_OF_FILE;
109
110     /* New token. */
111     s->token_line = s->line;
112     s->token_column = s->column;
113
114     /* Operators and punctuation. */
115     if (chr(s, '!')) return TOK_BANG;
116     if (chr(s, '=')) return TOK_EQUALS;
117     if (chr(s, '*')) return TOK_STAR;
118
119     /* Group name. */
120     if (chr(s, '$')) {
121         val->string.start = s->s + s->pos;
122         val->string.len = 0;
123         while (is_ident(peek(s))) {
124             next(s);
125             val->string.len++;
126         }
127         if (val->string.len == 0) {
128             scanner_err(s, "unexpected character after \'$\'; expected name");
129             return TOK_ERROR;
130         }
131         return TOK_GROUP_NAME;
132     }
133
134     /* Identifier. */
135     if (is_ident(peek(s))) {
136         val->string.start = s->s + s->pos;
137         val->string.len = 0;
138         while (is_ident(peek(s))) {
139             next(s);
140             val->string.len++;
141         }
142         return TOK_IDENTIFIER;
143     }
144
145     scanner_err(s, "unrecognized token");
146     return TOK_ERROR;
147 }
148
149 /***====================================================================***/
150
151 enum rules_mlvo {
152     MLVO_MODEL,
153     MLVO_LAYOUT,
154     MLVO_VARIANT,
155     MLVO_OPTION,
156     _MLVO_NUM_ENTRIES
157 };
158
159 #define SVAL_LIT(literal) { literal, sizeof(literal) - 1 }
160
161 static const struct sval rules_mlvo_svals[_MLVO_NUM_ENTRIES] = {
162     [MLVO_MODEL] = SVAL_LIT("model"),
163     [MLVO_LAYOUT] = SVAL_LIT("layout"),
164     [MLVO_VARIANT] = SVAL_LIT("variant"),
165     [MLVO_OPTION] = SVAL_LIT("option"),
166 };
167
168 enum rules_kccgst {
169     KCCGST_KEYCODES,
170     KCCGST_TYPES,
171     KCCGST_COMPAT,
172     KCCGST_SYMBOLS,
173     KCCGST_GEOMETRY,
174     _KCCGST_NUM_ENTRIES
175 };
176
177 static const struct sval rules_kccgst_svals[_KCCGST_NUM_ENTRIES] = {
178     [KCCGST_KEYCODES] = SVAL_LIT("keycodes"),
179     [KCCGST_TYPES] = SVAL_LIT("types"),
180     [KCCGST_COMPAT] = SVAL_LIT("compat"),
181     [KCCGST_SYMBOLS] = SVAL_LIT("symbols"),
182     [KCCGST_GEOMETRY] = SVAL_LIT("geometry"),
183 };
184
185 /*
186  * A broken-down version of xkb_rule_names (without the rules,
187  * obviously).
188  */
189 struct rule_names {
190     struct sval model;
191     darray_sval layouts;
192     darray_sval variants;
193     darray_sval options;
194 };
195
196 struct group {
197     struct sval name;
198     darray_sval elements;
199 };
200
201 struct mapping {
202     int mlvo_at_pos[_MLVO_NUM_ENTRIES];
203     unsigned int num_mlvo;
204     unsigned int defined_mlvo_mask;
205     xkb_layout_index_t layout_idx, variant_idx;
206     int kccgst_at_pos[_KCCGST_NUM_ENTRIES];
207     unsigned int num_kccgst;
208     unsigned int defined_kccgst_mask;
209     bool skip;
210 };
211
212 enum mlvo_match_type {
213     MLVO_MATCH_NORMAL = 0,
214     MLVO_MATCH_WILDCARD,
215     MLVO_MATCH_GROUP,
216 };
217
218 struct rule {
219     struct sval mlvo_value_at_pos[_MLVO_NUM_ENTRIES];
220     enum mlvo_match_type match_type_at_pos[_MLVO_NUM_ENTRIES];
221     unsigned int num_mlvo_values;
222     struct sval kccgst_value_at_pos[_KCCGST_NUM_ENTRIES];
223     unsigned int num_kccgst_values;
224     bool skip;
225 };
226
227 /*
228  * This is the main object used to match a given RMLVO against a rules
229  * file and aggragate the results in a KcCGST. It goes through a simple
230  * matching state machine, with tokens as transitions (see
231  * matcher_match()).
232  */
233 struct matcher {
234     struct xkb_context *ctx;
235     /* Input.*/
236     struct rule_names rmlvo;
237     union lvalue val;
238     struct scanner scanner;
239     darray(struct group) groups;
240     /* Current mapping. */
241     struct mapping mapping;
242     /* Current rule. */
243     struct rule rule;
244     /* Output. */
245     darray_char kccgst[_KCCGST_NUM_ENTRIES];
246 };
247
248 static struct sval
249 strip_spaces(struct sval v)
250 {
251     while (v.len > 0 && is_space(v.start[0])) { v.len--; v.start++; }
252     while (v.len > 0 && is_space(v.start[v.len - 1])) v.len--;
253     return v;
254 }
255
256 static darray_sval
257 split_comma_separated_string(const char *s)
258 {
259     darray_sval arr = darray_new();
260
261     /*
262      * Make sure the array returned by this function always includes at
263      * least one value, e.g. "" -> { "" } and "," -> { "", "" }.
264      */
265
266     if (!s) {
267         struct sval val = { NULL, 0 };
268         darray_append(arr, val);
269         return arr;
270     }
271
272     while (true) {
273         struct sval val = { s, 0 };
274         while (*s != '\0' && *s != ',') { s++; val.len++; }
275         darray_append(arr, strip_spaces(val));
276         if (*s == '\0') break;
277         if (*s == ',') s++;
278     }
279
280     return arr;
281 }
282
283 static struct matcher *
284 matcher_new(struct xkb_context *ctx,
285             const struct xkb_rule_names *rmlvo)
286 {
287     struct matcher *m = calloc(1, sizeof(*m));
288     if (!m)
289         return NULL;
290
291     m->ctx = ctx;
292     m->rmlvo.model.start = rmlvo->model;
293     m->rmlvo.model.len = strlen_safe(rmlvo->model);
294     m->rmlvo.layouts = split_comma_separated_string(rmlvo->layout);
295     m->rmlvo.variants = split_comma_separated_string(rmlvo->variant);
296     m->rmlvo.options = split_comma_separated_string(rmlvo->options);
297
298     return m;
299 }
300
301 static void
302 matcher_free(struct matcher *m)
303 {
304     struct group *group;
305     if (!m)
306         return;
307     darray_free(m->rmlvo.layouts);
308     darray_free(m->rmlvo.variants);
309     darray_free(m->rmlvo.options);
310     darray_foreach(group, m->groups)
311         darray_free(group->elements);
312     darray_free(m->groups);
313     free(m);
314 }
315
316 #define matcher_err(matcher, fmt, ...) \
317     scanner_err(&(matcher)->scanner, fmt, ## __VA_ARGS__)
318
319 static void
320 matcher_group_start_new(struct matcher *m, struct sval name)
321 {
322     struct group group = { .name = name, .elements = darray_new() };
323     darray_append(m->groups, group);
324 }
325
326 static void
327 matcher_group_add_element(struct matcher *m, struct sval element)
328 {
329     darray_append(darray_item(m->groups, darray_size(m->groups) - 1).elements,
330                   element);
331 }
332
333 static void
334 matcher_mapping_start_new(struct matcher *m)
335 {
336     for (unsigned i = 0; i < _MLVO_NUM_ENTRIES; i++)
337         m->mapping.mlvo_at_pos[i] = -1;
338     for (unsigned i = 0; i < _KCCGST_NUM_ENTRIES; i++)
339         m->mapping.kccgst_at_pos[i] = -1;
340     m->mapping.layout_idx = m->mapping.variant_idx = XKB_LAYOUT_INVALID;
341     m->mapping.num_mlvo = m->mapping.num_kccgst = 0;
342     m->mapping.defined_mlvo_mask = 0;
343     m->mapping.defined_kccgst_mask = 0;
344     m->mapping.skip = false;
345 }
346
347 static int
348 extract_layout_index(const char *s, size_t max_len, xkb_layout_index_t *out)
349 {
350     /* This function is pretty stupid, but works for now. */
351     *out = XKB_LAYOUT_INVALID;
352     if (max_len < 3)
353         return -1;
354     if (s[0] != '[' || !is_digit(s[1]) || s[2] != ']')
355         return -1;
356     if (s[1] - '0' < 1 || s[1] - '0' > XKB_MAX_GROUPS)
357         return -1;
358     /* To zero-based index. */
359     *out = s[1] - '0' - 1;
360     return 3;
361 }
362
363 static void
364 matcher_mapping_set_mlvo(struct matcher *m, struct sval ident)
365 {
366     enum rules_mlvo mlvo;
367     struct sval mlvo_sval;
368
369     for (mlvo = 0; mlvo < _MLVO_NUM_ENTRIES; mlvo++) {
370         mlvo_sval = rules_mlvo_svals[mlvo];
371
372         if (svaleq_prefix(mlvo_sval, ident))
373             break;
374     }
375
376     /* Not found. */
377     if (mlvo >= _MLVO_NUM_ENTRIES) {
378         matcher_err(m, "invalid mapping: %.*s is not a valid value here; ignoring rule set",
379                     ident.len, ident.start);
380         m->mapping.skip = true;
381         return;
382     }
383
384     if (m->mapping.defined_mlvo_mask & (1u << mlvo)) {
385         matcher_err(m, "invalid mapping: %.*s appears twice on the same line; ignoring rule set",
386                     mlvo_sval.len, mlvo_sval.start);
387         m->mapping.skip = true;
388         return;
389     }
390
391     /* If there are leftovers still, it must be an index. */
392     if (mlvo_sval.len < ident.len) {
393         xkb_layout_index_t idx;
394         int consumed = extract_layout_index(ident.start + mlvo_sval.len,
395                                             ident.len - mlvo_sval.len, &idx);
396         if ((int) (ident.len - mlvo_sval.len) != consumed) {
397             matcher_err(m, "invalid mapping: \"%.*s\" may only be followed by a valid group index; ignoring rule set",
398                         mlvo_sval.len, mlvo_sval.start);
399             m->mapping.skip = true;
400             return;
401         }
402
403         if (mlvo == MLVO_LAYOUT) {
404             m->mapping.layout_idx = idx;
405         }
406         else if (mlvo == MLVO_VARIANT) {
407             m->mapping.variant_idx = idx;
408         }
409         else {
410             matcher_err(m, "invalid mapping: \"%.*s\" cannot be followed by a group index; ignoring rule set",
411                         mlvo_sval.len, mlvo_sval.start);
412             m->mapping.skip = true;
413             return;
414         }
415     }
416
417     m->mapping.mlvo_at_pos[m->mapping.num_mlvo] = mlvo;
418     m->mapping.defined_mlvo_mask |= 1u << mlvo;
419     m->mapping.num_mlvo++;
420 }
421
422 static void
423 matcher_mapping_set_kccgst(struct matcher *m, struct sval ident)
424 {
425     enum rules_kccgst kccgst;
426     struct sval kccgst_sval;
427
428     for (kccgst = 0; kccgst < _KCCGST_NUM_ENTRIES; kccgst++) {
429         kccgst_sval = rules_kccgst_svals[kccgst];
430
431         if (svaleq(rules_kccgst_svals[kccgst], ident))
432             break;
433     }
434
435     /* Not found. */
436     if (kccgst >= _KCCGST_NUM_ENTRIES) {
437         matcher_err(m, "invalid mapping: %.*s is not a valid value here; ignoring rule set",
438                     ident.len, ident.start);
439         m->mapping.skip = true;
440         return;
441     }
442
443     if (m->mapping.defined_kccgst_mask & (1u << kccgst)) {
444         matcher_err(m, "invalid mapping: %.*s appears twice on the same line; ignoring rule set",
445                     kccgst_sval.len, kccgst_sval.start);
446         m->mapping.skip = true;
447         return;
448     }
449
450     m->mapping.kccgst_at_pos[m->mapping.num_kccgst] = kccgst;
451     m->mapping.defined_kccgst_mask |= 1u << kccgst;
452     m->mapping.num_kccgst++;
453 }
454
455 static void
456 matcher_mapping_verify(struct matcher *m)
457 {
458     if (m->mapping.num_mlvo == 0) {
459         matcher_err(m, "invalid mapping: must have at least one value on the left hand side; ignoring rule set");
460         goto skip;
461     }
462
463     if (m->mapping.num_kccgst == 0) {
464         matcher_err(m, "invalid mapping: must have at least one value on the right hand side; ignoring rule set");
465         goto skip;
466     }
467
468     /*
469      * This following is very stupid, but this is how it works.
470      * See the "Notes" section in the overview above.
471      */
472
473     if (m->mapping.defined_mlvo_mask & (1u << MLVO_LAYOUT)) {
474         if (m->mapping.layout_idx == XKB_LAYOUT_INVALID) {
475             if (darray_size(m->rmlvo.layouts) > 1)
476                 goto skip;
477         }
478         else {
479             if (darray_size(m->rmlvo.layouts) == 1 ||
480                 m->mapping.layout_idx >= darray_size(m->rmlvo.layouts))
481                 goto skip;
482         }
483     }
484
485     if (m->mapping.defined_mlvo_mask & (1u << MLVO_VARIANT)) {
486         if (m->mapping.variant_idx == XKB_LAYOUT_INVALID) {
487             if (darray_size(m->rmlvo.variants) > 1)
488                 goto skip;
489         }
490         else {
491             if (darray_size(m->rmlvo.variants) == 1 ||
492                 m->mapping.variant_idx >= darray_size(m->rmlvo.variants))
493                 goto skip;
494         }
495     }
496
497     return;
498
499 skip:
500     m->mapping.skip = true;
501 }
502
503 static void
504 matcher_rule_start_new(struct matcher *m)
505 {
506     memset(&m->rule, 0, sizeof(m->rule));
507     m->rule.skip = m->mapping.skip;
508 }
509
510 static void
511 matcher_rule_set_mlvo_common(struct matcher *m, struct sval ident,
512                              enum mlvo_match_type match_type)
513 {
514     if (m->rule.num_mlvo_values + 1 > m->mapping.num_mlvo) {
515         matcher_err(m, "invalid rule: has more values than the mapping line; ignoring rule");
516         m->rule.skip = true;
517         return;
518     }
519     m->rule.match_type_at_pos[m->rule.num_mlvo_values] = match_type;
520     m->rule.mlvo_value_at_pos[m->rule.num_mlvo_values] = ident;
521     m->rule.num_mlvo_values++;
522 }
523
524 static void
525 matcher_rule_set_mlvo_wildcard(struct matcher *m)
526 {
527     struct sval dummy = { NULL, 0 };
528     matcher_rule_set_mlvo_common(m, dummy, MLVO_MATCH_WILDCARD);
529 }
530
531 static void
532 matcher_rule_set_mlvo_group(struct matcher *m, struct sval ident)
533 {
534     matcher_rule_set_mlvo_common(m, ident, MLVO_MATCH_GROUP);
535 }
536
537 static void
538 matcher_rule_set_mlvo(struct matcher *m, struct sval ident)
539 {
540     matcher_rule_set_mlvo_common(m, ident, MLVO_MATCH_NORMAL);
541 }
542
543 static void
544 matcher_rule_set_kccgst(struct matcher *m, struct sval ident)
545 {
546     if (m->rule.num_kccgst_values + 1 > m->mapping.num_kccgst) {
547         matcher_err(m, "invalid rule: has more values than the mapping line; ignoring rule");
548         m->rule.skip = true;
549         return;
550     }
551     m->rule.kccgst_value_at_pos[m->rule.num_kccgst_values] = ident;
552     m->rule.num_kccgst_values++;
553 }
554
555 static bool
556 match_group(struct matcher *m, struct sval group_name, struct sval to)
557 {
558     struct group *group;
559     struct sval *element;
560     bool found = false;
561
562     darray_foreach(group, m->groups) {
563         if (svaleq(group->name, group_name)) {
564             found = true;
565             break;
566         }
567     }
568
569     if (!found) {
570         /*
571          * rules/evdev intentionally uses some undeclared group names
572          * in rules (e.g. commented group definitions which may be
573          * uncommented if needed). So we continue silently.
574          */
575         return false;
576     }
577
578     darray_foreach(element, group->elements)
579         if (svaleq(to, *element))
580             return true;
581
582     return false;
583 }
584
585 static bool
586 match_value(struct matcher *m, struct sval val, struct sval to,
587           enum mlvo_match_type match_type)
588 {
589     if (match_type == MLVO_MATCH_WILDCARD)
590         return true;
591     if (match_type == MLVO_MATCH_GROUP)
592         return match_group(m, val, to);
593     return svaleq(val, to);
594 }
595
596 /*
597  * This function performs %-expansion on @value (see overview above),
598  * and appends the result to @to.
599  */
600 static bool
601 append_expanded_kccgst_value(struct matcher *m, darray_char *to,
602                              struct sval value)
603 {
604     const char *s = value.start;
605     darray_char expanded = darray_new();
606     char ch;
607     bool expanded_plus, to_plus;
608
609     /*
610      * Some ugly hand-lexing here, but going through the scanner is more
611      * trouble than it's worth, and the format is ugly on its own merit.
612      */
613     for (unsigned i = 0; i < value.len; ) {
614         enum rules_mlvo mlv;
615         xkb_layout_index_t idx;
616         char pfx, sfx;
617         struct sval expanded_value;
618
619         /* Check if that's a start of an expansion. */
620         if (s[i] != '%') {
621             /* Just a normal character. */
622             darray_appends_nullterminate(expanded, &s[i++], 1);
623             continue;
624         }
625         if (++i >= value.len) goto error;
626
627         pfx = sfx = 0;
628
629         /* Check for prefix. */
630         if (s[i] == '(' || s[i] == '+' || s[i] == '|' ||
631             s[i] == '_' || s[i] == '-') {
632             pfx = s[i];
633             if (s[i] == '(') sfx = ')';
634             if (++i >= value.len) goto error;
635         }
636
637         /* Mandatory model/layout/variant specifier. */
638         switch (s[i++]) {
639         case 'm': mlv = MLVO_MODEL; break;
640         case 'l': mlv = MLVO_LAYOUT; break;
641         case 'v': mlv = MLVO_VARIANT; break;
642         default: goto error;
643         }
644
645         /* Check for index. */
646         idx = XKB_LAYOUT_INVALID;
647         if (i < value.len && s[i] == '[') {
648             int consumed;
649
650             if (mlv != MLVO_LAYOUT && mlv != MLVO_VARIANT) {
651                 matcher_err(m, "invalid index in %%-expansion; may only index layout or variant");
652                 goto error;
653             }
654
655             consumed = extract_layout_index(s + i, value.len - i, &idx);
656             if (consumed == -1) goto error;
657             i += consumed;
658         }
659
660         /* Check for suffix, if there supposed to be one. */
661         if (sfx != 0) {
662             if (i >= value.len) goto error;
663             if (s[i++] != sfx) goto error;
664         }
665
666         /* Get the expanded value. */
667         expanded_value.len = 0;
668
669         if (mlv == MLVO_LAYOUT) {
670             if (idx != XKB_LAYOUT_INVALID &&
671                 idx < darray_size(m->rmlvo.layouts) &&
672                 darray_size(m->rmlvo.layouts) > 1)
673                 expanded_value = darray_item(m->rmlvo.layouts, idx);
674             else if (idx == XKB_LAYOUT_INVALID &&
675                      darray_size(m->rmlvo.layouts) == 1)
676                 expanded_value = darray_item(m->rmlvo.layouts, 0);
677         }
678         else if (mlv == MLVO_VARIANT) {
679             if (idx != XKB_LAYOUT_INVALID &&
680                 idx < darray_size(m->rmlvo.variants) &&
681                 darray_size(m->rmlvo.variants) > 1)
682                 expanded_value = darray_item(m->rmlvo.variants, idx);
683             else if (idx == XKB_LAYOUT_INVALID &&
684                      darray_size(m->rmlvo.variants) == 1)
685                 expanded_value = darray_item(m->rmlvo.variants, 0);
686         }
687         else if (mlv == MLVO_MODEL) {
688             expanded_value = m->rmlvo.model;
689         }
690
691         /* If we didn't get one, skip silently. */
692         if (expanded_value.len <= 0)
693             continue;
694
695         if (pfx != 0)
696             darray_appends_nullterminate(expanded, &pfx, 1);
697         darray_appends_nullterminate(expanded,
698                                      expanded_value.start, expanded_value.len);
699         if (sfx != 0)
700             darray_appends_nullterminate(expanded, &sfx, 1);
701     }
702
703     /*
704      * Appending  bar to  foo ->  foo (not an error if this happens)
705      * Appending +bar to  foo ->  foo+bar
706      * Appending  bar to +foo ->  bar+foo
707      * Appending +bar to +foo -> +foo+bar
708      */
709
710     ch = (darray_empty(expanded) ? '\0' : darray_item(expanded, 0));
711     expanded_plus = (ch == '+' || ch == '|');
712     ch = (darray_empty(*to) ? '\0' : darray_item(*to, 0));
713     to_plus = (ch == '+' || ch == '|');
714
715     if (expanded_plus || darray_empty(*to))
716         darray_appends_nullterminate(*to, expanded.item, expanded.size);
717     else if (to_plus)
718         darray_prepends_nullterminate(*to, expanded.item, expanded.size);
719
720     darray_free(expanded);
721     return true;
722
723 error:
724     darray_free(expanded);
725     matcher_err(m, "invalid %%-expansion in value; not used");
726     return false;
727 }
728
729 static void
730 matcher_rule_verify(struct matcher *m)
731 {
732     if (m->rule.num_mlvo_values != m->mapping.num_mlvo ||
733         m->rule.num_kccgst_values != m->mapping.num_kccgst) {
734         matcher_err(m, "invalid rule: must have same number of values as mapping line; ignoring rule");
735         m->rule.skip = true;
736     }
737 }
738
739 static void
740 matcher_rule_apply_if_matches(struct matcher *m)
741 {
742     for (unsigned i = 0; i < m->mapping.num_mlvo; i++) {
743         enum rules_mlvo mlvo = m->mapping.mlvo_at_pos[i];
744         struct sval value = m->rule.mlvo_value_at_pos[i];
745         enum mlvo_match_type match_type = m->rule.match_type_at_pos[i];
746         bool matched = false;
747
748         if (mlvo == MLVO_MODEL) {
749             matched = match_value(m, value, m->rmlvo.model, match_type);
750         }
751         else if (mlvo == MLVO_LAYOUT) {
752             xkb_layout_index_t idx = m->mapping.layout_idx;
753             idx = (idx == XKB_LAYOUT_INVALID ? 0 : idx);
754             matched = match_value(m, value,
755                                   darray_item(m->rmlvo.layouts, idx),
756                                   match_type);
757         }
758         else if (mlvo == MLVO_VARIANT) {
759             xkb_layout_index_t idx = m->mapping.layout_idx;
760             idx = (idx == XKB_LAYOUT_INVALID ? 0 : idx);
761             matched = match_value(m, value,
762                                   darray_item(m->rmlvo.variants, idx),
763                                   match_type);
764         }
765         else if (mlvo == MLVO_OPTION) {
766             struct sval *option;
767             darray_foreach(option, m->rmlvo.options) {
768                 matched = match_value(m, value, *option, match_type);
769                 if (matched)
770                     break;
771             }
772         }
773
774         if (!matched)
775             return;
776     }
777
778     for (unsigned i = 0; i < m->mapping.num_kccgst; i++) {
779         enum rules_kccgst kccgst = m->mapping.kccgst_at_pos[i];
780         struct sval value = m->rule.kccgst_value_at_pos[i];
781         append_expanded_kccgst_value(m, &m->kccgst[kccgst], value);
782     }
783
784     /*
785      * If a rule matches in a rule set, the rest of the set should be
786      * skipped. However, rule sets matching against options may contain
787      * several legitimate rules, so they are processed entirely.
788      */
789     if (!(m->mapping.defined_mlvo_mask & (1 << MLVO_OPTION)))
790         m->mapping.skip = true;
791 }
792
793 static enum rules_token
794 gettok(struct matcher *m)
795 {
796     return lex(&m->scanner, &m->val);
797 }
798
799 static bool
800 matcher_match(struct matcher *m, const char *string, size_t len,
801               const char *file_name, struct xkb_component_names *out)
802 {
803     enum rules_token tok;
804
805     if (!m)
806         return false;
807
808     scanner_init(&m->scanner, m->ctx, string, len, file_name);
809
810 initial:
811     switch (tok = gettok(m)) {
812     case TOK_BANG:
813         goto bang;
814     case TOK_END_OF_LINE:
815         goto initial;
816     case TOK_END_OF_FILE:
817         goto finish;
818     default:
819         goto unexpected;
820     }
821
822 bang:
823     switch (tok = gettok(m)) {
824     case TOK_GROUP_NAME:
825         matcher_group_start_new(m, m->val.string);
826         goto group_name;
827     case TOK_IDENTIFIER:
828         matcher_mapping_start_new(m);
829         matcher_mapping_set_mlvo(m, m->val.string);
830         goto mapping_mlvo;
831     default:
832         goto unexpected;
833     }
834
835 group_name:
836     switch (tok = gettok(m)) {
837     case TOK_EQUALS:
838         goto group_element;
839     default:
840         goto unexpected;
841     }
842
843 group_element:
844     switch (tok = gettok(m)) {
845     case TOK_IDENTIFIER:
846         matcher_group_add_element(m, m->val.string);
847         goto group_element;
848     case TOK_END_OF_LINE:
849         goto initial;
850     default:
851         goto unexpected;
852     }
853
854 mapping_mlvo:
855     switch (tok = gettok(m)) {
856     case TOK_IDENTIFIER:
857         if (!m->mapping.skip)
858             matcher_mapping_set_mlvo(m, m->val.string);
859         goto mapping_mlvo;
860     case TOK_EQUALS:
861         goto mapping_kccgst;
862     default:
863         goto unexpected;
864     }
865
866 mapping_kccgst:
867     switch (tok = gettok(m)) {
868     case TOK_IDENTIFIER:
869         if (!m->mapping.skip)
870             matcher_mapping_set_kccgst(m, m->val.string);
871         goto mapping_kccgst;
872     case TOK_END_OF_LINE:
873         if (!m->mapping.skip)
874             matcher_mapping_verify(m);
875         goto rule_mlvo_first;
876     default:
877         goto unexpected;
878     }
879
880 rule_mlvo_first:
881     switch (tok = gettok(m)) {
882     case TOK_BANG:
883         goto bang;
884     case TOK_END_OF_LINE:
885         goto rule_mlvo_first;
886     case TOK_END_OF_FILE:
887         goto finish;
888     default:
889         matcher_rule_start_new(m);
890         goto rule_mlvo_no_tok;
891     }
892
893 rule_mlvo:
894     tok = gettok(m);
895 rule_mlvo_no_tok:
896     switch (tok) {
897     case TOK_IDENTIFIER:
898         if (!m->rule.skip)
899             matcher_rule_set_mlvo(m, m->val.string);
900         goto rule_mlvo;
901     case TOK_STAR:
902         if (!m->rule.skip)
903             matcher_rule_set_mlvo_wildcard(m);
904         goto rule_mlvo;
905     case TOK_GROUP_NAME:
906         if (!m->rule.skip)
907             matcher_rule_set_mlvo_group(m, m->val.string);
908         goto rule_mlvo;
909     case TOK_EQUALS:
910         goto rule_kccgst;
911     default:
912         goto unexpected;
913     }
914
915 rule_kccgst:
916     switch (tok = gettok(m)) {
917     case TOK_IDENTIFIER:
918         if (!m->rule.skip)
919             matcher_rule_set_kccgst(m, m->val.string);
920         goto rule_kccgst;
921     case TOK_END_OF_LINE:
922         if (!m->rule.skip)
923             matcher_rule_verify(m);
924         if (!m->rule.skip)
925             matcher_rule_apply_if_matches(m);
926         goto rule_mlvo_first;
927     default:
928         goto unexpected;
929     }
930
931 unexpected:
932     switch (tok) {
933     case TOK_ERROR:
934         goto error;
935     default:
936         goto state_error;
937     }
938
939 finish:
940     if (darray_empty(m->kccgst[KCCGST_KEYCODES]) ||
941         darray_empty(m->kccgst[KCCGST_TYPES]) ||
942         darray_empty(m->kccgst[KCCGST_COMPAT]) ||
943         /* darray_empty(m->kccgst[KCCGST_GEOMETRY]) || */
944         darray_empty(m->kccgst[KCCGST_SYMBOLS]))
945         goto error;
946
947     out->keycodes = darray_mem(m->kccgst[KCCGST_KEYCODES], 0);
948     out->types = darray_mem(m->kccgst[KCCGST_TYPES], 0);
949     out->compat = darray_mem(m->kccgst[KCCGST_COMPAT], 0);
950     /* out->geometry = darray_mem(m->kccgst[KCCGST_GEOMETRY], 0); */
951     darray_free(m->kccgst[KCCGST_GEOMETRY]);
952     out->symbols = darray_mem(m->kccgst[KCCGST_SYMBOLS], 0);
953
954     return true;
955
956 state_error:
957     matcher_err(m, "unexpected token");
958 error:
959     return false;
960 }
961
962 bool
963 xkb_components_from_rules(struct xkb_context *ctx,
964                           const struct xkb_rule_names *rmlvo,
965                           struct xkb_component_names *out)
966 {
967     bool ret = false;
968     FILE *file;
969     char *path;
970     const char *string;
971     size_t size;
972     struct matcher *matcher;
973
974     file = FindFileInXkbPath(ctx, rmlvo->rules, FILE_TYPE_RULES, &path);
975     if (!file)
976         goto err_out;
977
978     ret = map_file(file, &string, &size);
979     if (!ret) {
980         log_err(ctx, "Couldn't read rules file \"%s\": %s\n",
981                 path, strerror(errno));
982         goto err_file;
983     }
984
985     matcher = matcher_new(ctx, rmlvo);
986     ret = matcher_match(matcher, string, size, path, out);
987     if (!ret)
988         log_err(ctx, "No components returned from XKB rules \"%s\"\n", path);
989     matcher_free(matcher);
990
991     unmap_file(string, size);
992 err_file:
993     free(path);
994     fclose(file);
995 err_out:
996     return ret;
997 }