Removed build dependency on kbproto.
[platform/upstream/libxkbcommon.git] / scripts / makekeys
1 #!/usr/bin/env python
2
3 import re
4 import sys
5 import itertools
6
7 import perfect_hash
8
9 pattern = re.compile(r"^#define\s+XKB_KEY_(?P<name>\w+)\s+(?P<value>0x[0-9a-fA-F]+)\s")
10 matches = [pattern.match(line) for line in open(sys.argv[1])]
11 entries = [(m.group("name"), int(m.group("value"), 16)) for m in matches if m]
12
13 entries_isorted = sorted(entries, key=lambda e: e[0].lower())
14 entries_kssorted = sorted(entries, key=lambda e: e[1])
15
16 print(
17     """
18 /**
19  * This file comes from libxkbcommon and was generated by makekeys.py
20  * You can always fetch the latest version from:
21  * https://raw.github.com/xkbcommon/libxkbcommon/master/src/ks_tables.h
22  */
23 """
24 )
25
26 entry_offsets = {}
27
28 print(
29     """
30 #ifdef __GNUC__
31 #pragma GCC diagnostic push
32 #pragma GCC diagnostic ignored "-Woverlength-strings"
33 #endif
34 static const char *keysym_names =
35 """.strip()
36 )
37 offs = 0
38 for name, _ in entries_isorted:
39     entry_offsets[name] = offs
40     print('    "{name}\\0"'.format(name=name))
41     offs += len(name) + 1
42 print(
43     """
44 ;
45 #ifdef __GNUC__
46 #pragma GCC diagnostic pop
47 #endif
48 """.strip()
49 )
50
51
52 template = r"""
53 static const uint16_t keysym_name_G[] = {
54     $G
55 };
56
57 static size_t
58 keysym_name_hash_f(const char *key, const char *T)
59 {
60     size_t sum = 0;
61     for (size_t i = 0; key[i] != '\0'; i++)
62         sum += T[i % $NS] * key[i];
63     return sum % $NG;
64 }
65
66 static size_t
67 keysym_name_perfect_hash(const char *key)
68 {
69     return (
70         keysym_name_G[keysym_name_hash_f(key, "$S1")] +
71         keysym_name_G[keysym_name_hash_f(key, "$S2")]
72     ) % $NG;
73 }
74 """
75 print(
76     perfect_hash.generate_code(
77         keys=[name for name, value in entries_isorted],
78         template=template,
79     )
80 )
81
82 print(
83     """
84 struct name_keysym {
85     xkb_keysym_t keysym;
86     uint32_t offset;
87 };\n"""
88 )
89
90
91 def print_entries(x):
92     for name, value in x:
93         print(
94             "    {{ 0x{value:08x}, {offs} }}, /* {name} */".format(
95                 offs=entry_offsets[name], value=value, name=name
96             )
97         )
98
99
100 print("static const struct name_keysym name_to_keysym[] = {")
101 print_entries(entries_isorted)
102 print("};\n")
103
104 # *.sort() is stable so we always get the first keysym for duplicate
105 print("static const struct name_keysym keysym_to_name[] = {")
106 print_entries(
107     next(g[1]) for g in itertools.groupby(entries_kssorted, key=lambda e: e[1])
108 )
109 print("};")