Debian Codegraph @

scripts/generate-builtin-terminfo.py

raw
1 #!/usr/bin/env python3
2
3 import argparse
4 import os
5 import re
6
7
8 class Capability:
9 def __init__(self, name: str, value: bool | int | str):
10 self._name = name
11 self._value = value
12
13 @property
14 def name(self) -> str:
15 return self._name
16
17 @property
18 def value(self) -> bool | int | str:
19 return self._value
20
21 def __lt__(self, other: object) -> bool:
22 if not isinstance(other, Capability):
23 return NotImplemented
24 return self._name < other._name
25
26 def __le__(self, other: object) -> bool:
27 if not isinstance(other, Capability):
28 return NotImplemented
29 return self._name <= other._name
30
31 def __eq__(self, other: object) -> bool:
32 if not isinstance(other, Capability):
33 return NotImplemented
34 return self._name == other._name
35
36 def __ne__(self, other: object) -> bool:
37 if not isinstance(other, Capability):
38 return NotImplemented
39 return bool(self._name != other._name)
40
41 def __gt__(self, other: object) -> bool:
42 if not isinstance(other, Capability):
43 return NotImplemented
44 return bool(self._name > other._name)
45
46 def __ge__(self, other: object) -> bool:
47 if not isinstance(other, Capability):
48 return NotImplemented
49 return self._name >= other._name
50
51
52 class BoolCapability(Capability):
53 def __init__(self, name: str):
54 super().__init__(name, True)
55
56
57 class IntCapability(Capability):
58 pass
59
60
61 class StringCapability(Capability):
62 def __init__(self, name: str, value: str):
63 # see terminfo(5) for valid escape sequences
64
65 # Control characters
66 def translate_ctrl_chr(m: re.Match[str]) -> str:
67 ctrl = m.group(1)
68 if ctrl == '?':
69 return '\\x7f'
70 return f'\\x{ord(ctrl) - ord("@"):02x}'
71 value = re.sub(r'\^([@A-Z[\\\\\]^_?])', translate_ctrl_chr, value)
72
73 # Ensure e.g. \E7 (or \e7) doesn’t get translated to “\0337”,
74 # which would be interpreted as octal 337 by the C compiler
75 value = re.sub(r'(\\E|\\e)([0-7])', r'\\033" "\2', value)
76
77 # Replace \E and \e with ESC
78 value = re.sub(r'\\E|\\e', r'\\033', value)
79
80 # Unescape ,:^
81 value = re.sub(r'\\(,|:|\^)', r'\1', value)
82
83 # Replace \s with space
84 value = value.replace('\\s', ' ')
85
86 # Let \\, \n, \r, \t, \b and \f "fall through", to the C string literal
87
88 if re.search(r'\\l', value):
89 raise NotImplementedError('\\l escape sequence')
90
91 super().__init__(name, value)
92
93
94 class Fragment:
95 def __init__(self, name: str, description: str):
96 self._name = name
97 self._description = description
98 self._caps = dict[str, Capability]()
99
100 @property
101 def name(self) -> str:
102 return self._name
103
104 @property
105 def description(self) -> str:
106 return self._description
107
108 @property
109 def caps(self) -> dict[str, Capability]:
110 return self._caps
111
112 def add_capability(self, cap: Capability) -> None:
113 assert cap.name not in self._caps
114 self._caps[cap.name] = cap
115
116 def del_capability(self, name: str) -> None:
117 del self._caps[name]
118
119
120 def main() -> None:
121 parser = argparse.ArgumentParser()
122 parser.add_argument('source_entry_name')
123 parser.add_argument('source', type=argparse.FileType('r'))
124 parser.add_argument('target_entry_name')
125 parser.add_argument('target', type=argparse.FileType('w'))
126
127 opts = parser.parse_args()
128 source_entry_name = opts.source_entry_name
129 target_entry_name = opts.target_entry_name
130 source = opts.source
131 target = opts.target
132
133 lines = list[str]()
134 for line in source.readlines():
135 line = line.strip()
136 if line.startswith('#'):
137 continue
138 lines.append(line)
139
140 fragments = dict[str, Fragment]()
141 cur_fragment: Fragment | None = None
142
143 for m in re.finditer(
144 r'(?P<name>(?P<entry_name>[-+\w@]+)\|(?P<entry_desc>.+?),)|'
145 r'(?P<bool_cap>(?P<bool_name>\w+),)|'
146 r'(?P<int_cap>(?P<int_name>\w+)#(?P<int_val>(0x)?[0-9a-fA-F]+),)|'
147 r'(?P<str_cap>(?P<str_name>\w+)=(?P<str_val>(.+?)),)',
148 ''.join(lines)):
149
150 if m.group('name') is not None:
151 name = m.group('entry_name')
152 description = m.group('entry_desc')
153
154 assert name not in fragments
155 fragments[name] = Fragment(name, description)
156 cur_fragment = fragments[name]
157
158 elif m.group('bool_cap') is not None:
159 name = m.group('bool_name')
160 assert cur_fragment is not None
161 cur_fragment.add_capability(BoolCapability(name))
162
163 elif m.group('int_cap') is not None:
164 name = m.group('int_name')
165 int_value = int(m.group('int_val'), 0)
166 assert cur_fragment is not None
167 cur_fragment.add_capability(IntCapability(name, int_value))
168
169 elif m.group('str_cap') is not None:
170 name = m.group('str_name')
171 str_value = m.group('str_val')
172 assert cur_fragment is not None
173 cur_fragment.add_capability(StringCapability(name, str_value))
174
175 else:
176 assert False
177
178 # Expand ‘use’ capabilities
179 for frag in fragments.values():
180 for cap in frag.caps.values():
181 if cap.name == 'use':
182 assert isinstance(cap, StringCapability)
183 assert isinstance(cap.value, str)
184
185 use_frag = fragments[cap.value]
186 for use_cap in use_frag.caps.values():
187 frag.add_capability(use_cap)
188
189
190 frag.del_capability(cap.name)
191 break
192
193 entry = fragments[source_entry_name]
194
195 try:
196 entry.del_capability('RGB')
197 except KeyError:
198 pass
199
200 entry.add_capability(IntCapability('Co', 256))
201 entry.add_capability(StringCapability('TN', target_entry_name))
202 entry.add_capability(StringCapability('name', target_entry_name))
203 entry.add_capability(IntCapability('RGB', 8)) # 8 bits per channel
204 entry.add_capability(StringCapability('query-os-name', os.uname().sysname))
205
206 terminfo_parts = list[str]()
207 for cap in sorted(entry.caps.values()):
208 name = cap.name
209 value = str(cap.value)
210
211 # Escape ‘“‘
212 name = name.replace('"', '\"')
213 value = value.replace('"', '\"')
214
215 terminfo_parts.append(name)
216 if isinstance(cap, BoolCapability):
217 terminfo_parts.append('')
218 else:
219 terminfo_parts.append(value)
220
221 terminfo = '\\0" "'.join(terminfo_parts)
222
223 target.write('#pragma once\n')
224 target.write('\n')
225 target.write(f'static const char terminfo_capabilities[] = "{terminfo}";')
226 target.write('\n')
227
228
229 if __name__ == '__main__':
230 main()