Debian Codegraph @

scripts/update-keysyms-names-handling.py

raw
1 #!/usr/bin/env python3
2
3 """
4 Generate C file to handle keysym names
5 """
6
7 import argparse
8 import itertools
9 import random
10 import re
11 import sys
12 from collections import defaultdict
13 from dataclasses import dataclass
14 from enum import Enum
15 from pathlib import Path
16 from typing import DefaultDict, Generator, Iterable, Iterator
17
18 import perfect_hash
19
20 # Root of the project
21 SCRIPT = Path(__file__)
22 ROOT = SCRIPT.parent.parent
23
24 # Parse commands
25 parser = argparse.ArgumentParser(description="Generate C file to handle keysym names")
26 parser.add_argument(
27 "c_header", type=Path, help="Path to the libxkbcommon keysym header"
28 )
29 parser.add_argument("gperf", type=Path, help="Path to the gperf file")
30 args = parser.parse_args()
31
32 # Set the seed explicitly, so we reduce diff
33 random.seed(b"libxkbcommon")
34
35 KEYSYM_ENTRY_PATTERN = re.compile(
36 r"""
37 ^\#define\s+
38 XKB_KEY_(?P<name>\w+)\s+
39 (?P<value>0x[0-9a-fA-F]+)\s*
40 (?:/\*\s*
41 (?:
42 (?P<deprecated>(?:D|d)eprecated)|
43 \(<U\+(?P<unicode_alt_semantics>[0-9a-fA-F]{4,}>)\)|
44 \(U\+(?P<deprecated_unicode>[0-9a-fA-F]{4,})\s(?:\s|\w|-)+\)|
45 .*
46 )
47 )?
48 """,
49 re.VERBOSE,
50 )
51
52
53 class Deprecation(Enum):
54 NONE = "none"
55 "No deprecation"
56 EXPLICIT = "explicit"
57 "Explicit deprecation in comment: /* deprecated */"
58 IMPLICIT = "implicit"
59 """
60 Implicit deprecation: the keysym has already been defined with a previous
61 name, and the present name has not been declared explicitly as an alias.
62 """
63
64
65 @dataclass
66 class Keysym:
67 name: str
68 value: int
69 deprecated: Deprecation
70 alias: bool
71
72
73 def parse_keysyms(path: Path) -> Iterator[Keysym]:
74 with path.open("rt", encoding="utf-8") as fd:
75 for line in fd:
76 if m := KEYSYM_ENTRY_PATTERN.match(line):
77 yield Keysym(
78 name=m.group("name"),
79 value=int(m.group("value"), 16),
80 deprecated=Deprecation.EXPLICIT
81 if m.group("deprecated") or m.group("deprecated_unicode")
82 else Deprecation.NONE,
83 alias="alias for" in line.casefold()
84 or m.group("unicode_alt_semantics"),
85 )
86
87
88 def get_keysyms(path: Path) -> dict[int, list[Keysym]]:
89 keysyms: DefaultDict[int, list[Keysym]] = defaultdict(list)
90 for keysym in parse_keysyms(path):
91 if (
92 (ks := keysyms.get(keysym.value))
93 and keysym.deprecated is Deprecation.NONE
94 and not keysym.alias
95 # deal with first name being deprecated
96 and any(k.deprecated is Deprecation.NONE for k in ks)
97 ):
98 keysym.deprecated = Deprecation.IMPLICIT
99 keysyms[keysym.value].append(keysym)
100 return keysyms
101
102
103 keysyms_by_value = get_keysyms(args.c_header)
104 entries = tuple(itertools.chain.from_iterable(keysyms_by_value.values()))
105
106 # Sort based on the keysym name:
107 # 1. Sort by the casefolded name: e.g. kana_ya < kana_YO.
108 # 2. If same casefolded name, then sort by cased name, i.e for
109 # ASCII: upper before lower: e.g kana_YA < kana_ya.
110 # E.g. kana_YA < kana_ya < kana_YO < kana_yo
111 # WARNING: this sort must not be changed, as some functions e.g.
112 # xkb_keysym_from_name rely on upper case variant occuring first.
113 entries_isorted = sorted(entries, key=lambda e: (e.name.casefold(), e.name))
114 # Sort based on keysym value. Sort is stable so in case of duplicate, the first
115 # keysym occurence stays first.
116 entries_kssorted = sorted(entries, key=lambda e: e.value)
117
118 print(
119 f"""
120 /**
121 * This file comes from libxkbcommon and was generated by {SCRIPT.name}
122 * You can always fetch the latest version from:
123 * https://raw.github.com/xkbcommon/libxkbcommon/master/src/ks_tables.h
124 */
125 #pragma once
126 """
127 )
128
129 entry_offsets: dict[str, int] = {}
130 UINT16_MAX = (1 << 16) - 1
131 UNICODE_KEYSYM = UINT16_MAX - 1
132 DEPRECATED_KEYSYM = UINT16_MAX
133 MAX_EXPLICIT_DEPRECATED_ALIAS_INDEX_LOG2 = 8
134 MAX_EXPLICIT_DEPRECATED_ALIAS_INDEX = 1 << MAX_EXPLICIT_DEPRECATED_ALIAS_INDEX_LOG2
135 MAX_EXPLICIT_DEPRECATED_ALIAS_COUNT_LOG2 = 4
136 MAX_EXPLICIT_DEPRECATED_ALIAS_COUNT = 1 << MAX_EXPLICIT_DEPRECATED_ALIAS_COUNT_LOG2
137 MAX_OFFSET = UNICODE_KEYSYM - 1
138 XKB_KEYSYM_UNICODE_MIN = 0x01000100
139 XKB_KEYSYM_UNICODE_MAX = 0x0110FFFF
140
141 print(
142 """
143 #include "config.h"
144
145 #include <stddef.h>
146 #include <stdint.h>
147
148 #include "xkbcommon/xkbcommon.h"
149
150 #ifdef __GNUC__
151 #pragma GCC diagnostic push
152 #pragma GCC diagnostic ignored "-Woverlength-strings"
153 #endif
154 static const char *keysym_names =
155 """.strip()
156 )
157 offs = 0
158 for keysym in entries_isorted:
159 if offs >= MAX_OFFSET:
160 raise ValueError(f"Offset must be kept under {MAX_OFFSET}, got: {offs}.")
161 entry_offsets[keysym.name] = offs
162 print(f' "{keysym.name}\\0"')
163 offs += len(keysym.name) + 1
164 print(
165 """
166 ;
167 #ifdef __GNUC__
168 #pragma GCC diagnostic pop
169 #endif
170 """.strip()
171 )
172
173 template = r"""
174 static const uint16_t keysym_name_G[] = {
175 $G
176 };
177
178 static size_t
179 keysym_name_hash_f(const char *key, const char *T)
180 {
181 size_t sum = 0;
182 for (size_t i = 0; key[i] != '\0'; i++)
183 sum += (size_t) (T[i % $NS] * key[i]);
184 return sum % $NG;
185 }
186
187 static inline size_t
188 keysym_name_perfect_hash(const char *key)
189 {
190 return (
191 keysym_name_G[keysym_name_hash_f(key, "$S1")] +
192 keysym_name_G[keysym_name_hash_f(key, "$S2")]
193 ) % $NG;
194 }
195 """
196 print(
197 perfect_hash.generate_code(
198 keys=[keysym.name for keysym in entries_isorted],
199 template=template,
200 )
201 )
202
203 print(
204 """
205 struct name_keysym {
206 xkb_keysym_t keysym;
207 uint16_t offset;
208 };\n"""
209 )
210
211
212 def print_entries(entries: Iterable[Keysym]):
213 for entry in entries:
214 print(
215 " {{ 0x{value:08x}, {offs} }}, /* {name} */".format(
216 offs=entry_offsets[entry.name], value=entry.value, name=entry.name
217 )
218 )
219
220
221 print("static const struct name_keysym name_to_keysym[] = {")
222 print_entries(entries_isorted)
223 print("};\n")
224
225 # *.sort() is stable so we always get the first keysym for duplicate
226 print("static const struct name_keysym keysym_to_name[] = {")
227 print_entries(
228 next(g[1]) for g in itertools.groupby(entries_kssorted, key=lambda e: e.value)
229 )
230 print("};\n")
231
232
233 def make_deprecated_entry(
234 value,
235 keysyms: list[Keysym],
236 entry_offsets: dict[str, int],
237 explicit_deprecated_aliases_index: int,
238 ) -> tuple[str | None, tuple[int, ...]]:
239 assert keysyms
240 non_deprecated_ks = tuple(k for k in keysyms if k.deprecated is Deprecation.NONE)
241 explicit_deprecated_aliases: tuple[int, ...] = ()
242 if non_deprecated_ks:
243 # Keysym is not deprecated. Check if none of its aliases are.
244 if len(keysyms) == 1 or all(
245 ks.alias and ks.deprecated is Deprecation.NONE for ks in keysyms[1:]
246 ):
247 return None, ()
248 ref = non_deprecated_ks[0].name
249 canonical_name = f"Reference: {ref}. "
250 assert ref in entry_offsets
251 canonical_index = str(entry_offsets[ref])
252 deprecated_ks = tuple(k for k in keysyms if k not in non_deprecated_ks)
253 if any(ks.alias and ks.deprecated is Deprecation.NONE for ks in keysyms[1:]):
254 # keysym has both explicit and deprecated aliases
255 explicit_deprecated_aliases = tuple(
256 entry_offsets[ks.name]
257 for ks in keysyms[1:]
258 if ks.deprecated is not Deprecation.NONE
259 )
260 assert (
261 explicit_deprecated_aliases_index < MAX_EXPLICIT_DEPRECATED_ALIAS_INDEX
262 )
263 assert (
264 len(explicit_deprecated_aliases) < MAX_EXPLICIT_DEPRECATED_ALIAS_COUNT
265 )
266 else:
267 explicit_deprecated_aliases_index = 0
268 else:
269 # Keysym is deprecated
270 canonical_name = ""
271 canonical_index = (
272 "DEPRECATED_KEYSYM"
273 if value < XKB_KEYSYM_UNICODE_MIN or value > XKB_KEYSYM_UNICODE_MAX
274 else "UNICODE_KEYSYM"
275 )
276 deprecated_ks = keysyms
277 explicit_deprecated_aliases_index = 0
278 if non_deprecated_ks[1:]:
279 non_deprecated = (
280 "Non deprecated aliases: "
281 + ", ".join(ks.name for ks in non_deprecated_ks[1:])
282 + ". "
283 )
284 else:
285 non_deprecated = ""
286 deprecated = ", ".join(ks.name for ks in deprecated_ks)
287 comment = f"{canonical_name}{non_deprecated}Deprecated: {deprecated}"
288 return (
289 f" {{ 0x{value:0>8x}, {canonical_index: <17}, {explicit_deprecated_aliases_index}, {len(explicit_deprecated_aliases)} }}, /* {comment} */",
290 explicit_deprecated_aliases,
291 )
292
293
294 def generate_deprecated_keysyms(
295 keysyms_by_value: dict[int, list[Keysym]], entry_offsets: dict[str, int]
296 ) -> Generator[tuple[int, ...], None, None]:
297 explicit_deprecated_aliases_index = 0
298 for value, keysyms in sorted(keysyms_by_value.items(), key=lambda e: e[0]):
299 assert keysyms
300 c_entry, explicit_deprecated_aliases = make_deprecated_entry(
301 value, keysyms, entry_offsets, explicit_deprecated_aliases_index
302 )
303 if c_entry is not None:
304 print(c_entry)
305 if explicit_deprecated_aliases:
306 yield explicit_deprecated_aliases
307 explicit_deprecated_aliases_index += len(explicit_deprecated_aliases)
308
309
310 def generate_mixed_aliases(aliases: Iterable[Iterable[int]]):
311 for xs in aliases:
312 for x in xs:
313 print(f" {x},")
314
315
316 print(f"#define UNICODE_KEYSYM 0x{UNICODE_KEYSYM:x}")
317 print(f"#define DEPRECATED_KEYSYM 0x{DEPRECATED_KEYSYM:x}")
318 # NOTE: Alternative implementation, useful the day the indices do not fit uint16_t.
319 # print(f"""
320 # struct deprecated_keysym {{
321 # xkb_keysym_t keysym;
322 # union {{
323 # uint32_t offset;
324 # struct {{
325 # uint32_t offset:{MAX_OFFSET_LOG2};
326 # /* Explicit deprecated aliases start index & count */
327 # uint8_t explicit_index:{MAX_EXPLICIT_DEPRECATED_ALIAS_INDEX_LOG2};
328 # uint8_t explicit_count:{MAX_EXPLICIT_DEPRECATED_ALIAS_COUNT_LOG2};
329 # }} details;
330 # }};
331 # }};
332 # """)
333 print("""
334 struct deprecated_keysym {
335 xkb_keysym_t keysym;
336 uint16_t offset;
337 /* Explicit deprecated aliases start index & count */
338 uint8_t explicit_index;
339 uint8_t explicit_count;
340 };
341 """)
342 print("static const struct deprecated_keysym deprecated_keysyms[] = {")
343 explicit_deprecated_aliases = tuple(
344 generate_deprecated_keysyms(keysyms_by_value, entry_offsets)
345 )
346 print("};\n")
347 print("static const uint32_t explicit_deprecated_aliases[] = {")
348 generate_mixed_aliases(explicit_deprecated_aliases)
349 print("};")
350
351 print(f"max name offset: {max(entry_offsets.values())}", file=sys.stderr)
352
353
354 # Check that the keywords of our XKB parser that clash with keysyms are handled properly
355 def parse_gperf_keywords(path: Path) -> Iterator[str]:
356 with path.open("rt", encoding="utf-8") as fd:
357 in_keyword_section = False
358 for line in fd:
359 if line.startswith(r"%%"):
360 # This is a boundary of the keywords section
361 if in_keyword_section:
362 break
363 in_keyword_section = True
364 elif in_keyword_section:
365 # Parse the keywords
366 keyword, *_ = line.split(",")
367 yield keyword.strip().casefold()
368 # Skip any line until we reach the keywords
369 else:
370 raise ValueError("Parse error: keywords section boundary not found")
371
372
373 SUPPORTED_KEYWORDS_CLASHES = {"section"}
374 UNSUPPORTED_KEYWORDS_CLASHES = frozenset(parse_gperf_keywords(args.gperf)).difference(
375 SUPPORTED_KEYWORDS_CLASHES
376 )
377 expected_clashes: set[str] = set()
378 errors = 0
379 for entry in entries:
380 if entry.name.casefold() in UNSUPPORTED_KEYWORDS_CLASHES:
381 print(
382 f"ERROR: keysym “{entry.name}” (0x{entry.value:0>4x}) clashes with keywords",
383 "and cannot be parsed properly.",
384 file=sys.stderr,
385 )
386 errors += 1
387 elif (lower := entry.name.lower()) in SUPPORTED_KEYWORDS_CLASHES:
388 if not entry.name.islower():
389 # Keywords’s atoms are registered in *lower* case, so the keysym will be
390 # replaced by the keysym with the corresponding name, but they may not match.
391 entry2: Keysym = Keysym("NoSymbol", 0, Deprecation.NONE, False)
392 if any(
393 e.name == lower
394 for e in keysyms_by_value[entry.value]
395 if e.name != entry.value
396 ):
397 # There is a keysym in lower case that is an alias
398 print(
399 f"WARNING: keysym “{entry.name}”",
400 f"will be parsed as “{lower}” (expected)",
401 file=sys.stderr,
402 )
403 else:
404 # Lookup the keysym mismatch
405 for e in entries:
406 if e.name == lower:
407 entry2 = e
408 break
409 print(
410 f"ERROR: keysym “{entry.name}” (0x{entry.value:0>4x})",
411 r"clashes with keywords and will be replaced by",
412 f"“{entry2.name}” (0x{entry2.value:0>4x}).",
413 file=sys.stderr,
414 )
415 errors += 1
416 else:
417 print(
418 f"WARNING: keysym “{entry.name}” clashing with keywords (expected)",
419 file=sys.stderr,
420 )
421 expected_clashes.add(entry.name)
422 if diff := SUPPORTED_KEYWORDS_CLASHES.difference(expected_clashes):
423 print(f"ERROR: Unexpected missing clashing keysyms: {diff}", file=sys.stderr)
424 errors += 1
425 if errors:
426 print(
427 f" {errors} ERRORS ".center(80, "-"),
428 "Please update the parser file `parser.y` to handle keysyms causing clashes.",
429 "The relevant entries are:",
430 "- Keysym",
431 "- Element (for modmap, parsed via: Expr -> Term -> Lhs -> FieldSpec -> Element)",
432 file=sys.stderr,
433 sep="\n",
434 )
435 exit(1)