Debian Codegraph @

similar/main/generate-kconfig-udlr.py

raw
1 #!/usr/bin/python
2
3 import ast, os, re, sys
4
5 # Storage for the relevant fields from an initializer for a single
6 # element of a kc_item array. Fields not required for sorting or
7 # generating the output header are not captured or saved.
8 class ArrayInitializationLine:
9 def __init__(self,xinput,y,name,enum,label,idx):
10 # xinput, y are fields in the kc_item structure
11 self.xinput = xinput
12 self.y = y
13 # name is the token that will be preprocessor-defined to the
14 # appropriate udlr values
15 self.name = name
16 self.enum = enum
17 self.label = label
18 # index in the kc_item array at which this initializer was found
19 self.idx = idx
20
21 # For horizontal sorting, group elements by their vertical
22 # coordinate, then break ties using the horizontal coordinate. This
23 # causes elements from a single row to be contiguous in the sorted
24 # output, and places visually adjacent rows adjacent in the sorted
25 # output.
26 def key_horizontal(self):
27 return (self.y, self.xinput)
28
29 # For vertical sorting, group elements by their horizontal
30 # coordinate, then break ties using the vertical coordinate.
31 def key_vertical(self):
32 return (self.xinput, self.y)
33
34 # InputException is raised when the post-processed C++ table cannot be
35 # parsed using the regular expressions in this script. The table may or
36 # may not be valid C++ when this script rejects it.
37 class InputException(Exception):
38 pass
39
40 # NodeVisitor handles walking a Python Abstract Syntax Tree (AST) to
41 # emulate a few supported operations, and raise an error on anything
42 # unsupported. This is used to implement primitive support for
43 # evaluating arithmetic expressions in the table. This support covers
44 # only what is likely to be used and assumes Python syntax (which should
45 # usually match C++ syntax closely enough, for the limited forms
46 # supported).
47 class NodeVisitor(ast.NodeVisitor):
48 def __init__(self,source,lno,name,expr,constants):
49 self.source = source
50 self.lno = lno
51 self.name = name
52 self.expr = expr
53 self.constants = constants
54
55 def generic_visit(self,node):
56 raise InputException(f'{self.source}:{self.lno}: {self.name!r} expression {self.expr!r} uses unsupported node type {node.__class__.__name__}')
57
58 def visit_BinOp(self,node):
59 left = self.visit(node.left)
60 right = self.visit(node.right)
61 op = node.op
62 if isinstance(op, ast.Add):
63 return left + right
64 elif isinstance(op, ast.Sub):
65 return left - right
66 elif isinstance(op, ast.Mult):
67 return left * right
68 elif isinstance(op, ast.Div):
69 return left / right
70 else:
71 raise InputException(f'{self.source}:{self.lno}: {self.name!r} expression {self.expr!r} uses unsupported BinOp node type {op.__class__.__name__}')
72
73 # Resolve expressions by expanding them.
74 def visit_Expression(self,node):
75 return self.visit(node.body)
76
77 # Resolve names by searching the dictionary `constants`, which is
78 # initialized from C++ constexpr declarations found while scanning
79 # the file.
80 def visit_Name(self,node):
81 try:
82 return self.constants[node.id]
83 except KeyError as e:
84 raise InputException(f'{self.source}:{self.lno}: {self.name!r} expression {self.expr!r} uses undefined name {node.id}')
85
86 # Resolve numbers by returning the value as-is.
87 def visit_Constant(self,node):
88 result = node.value
89 if not isinstance(result, int):
90 raise InputException(f'{self.source}:{self.lno}: {self.name!r} expression {self.expr!r} uses unsupported constant {type(result)}')
91 return result
92
93 class Main:
94 def __init__(self):
95 # Initially, no constants are known. Elements will be added by
96 # prepare_text.
97 self.constants = {}
98
99 # Resolve an expression by parsing it into an AST, then visiting
100 # the nodes and emulating the permitted operations. Any
101 # disallowed operations will cause an exception, which will
102 # propagate through resolve_expr into the caller.
103 def resolve_expr(self,source,lno,name,expr):
104 expr = expr.strip()
105 return NodeVisitor(source, lno, name, expr, self.constants).visit(ast.parse(expr, mode='eval'))
106
107 # Given a list of C++ initializer lines, extract from those lines
108 # the position of each initialized cell, compute the u/d/l/r
109 # relations among the cells, and return a multiline string
110 # containing CPP #define statements appropriate to the cells. Each
111 # C++ initializer must be entirely contained within a single element
112 # in `lines`.
113 #
114 # array_name - C++ identifier for the array; used in a C
115 # comment and, if labels are used, as part of the name of the macro
116 # that expands to the label
117 #
118 # source - name of the file from which the lines were read
119 #
120 # lines - iterable of initializer lines
121 #
122 # _re_finditer_init_element - bound method for a regular expression to
123 # extract the required fields
124 def generate_defines(self,array_name,source,lines,_re_finditer_init_element=re.compile(r'{'
125 r'(?:[^,]+),' # x
126 r'(?P<y>[^,]+),'
127 r'(?P<xinput>[^,]+),'
128 r'(?:[^,]+),' # w2
129 r'\s*(?:DXX_KCONFIG_UI_ENUM\s*\((?P<enum>\w+)\)\s*)?(?:DXX_KCONFIG_UI_LABEL\s*\((?P<label>(?:"[^"]*")|\w*)\)\s*)?(?P<udlr>\w+)\(\),'
130 r'\s*(?:[^,]+,' # type
131 r'[^,]+,' # state_bit
132 r'[^,]+)' # state_ptr
133 r'},').finditer):
134 a = ArrayInitializationLine
135 array = []
136 append = array.append
137 resolve_expr = self.resolve_expr
138 idx = 0
139 # Iterate over the initializer lines and populate `array` with
140 # the extracted data.
141 for lno, line in lines:
142 ml = _re_finditer_init_element(line)
143 old_idx = idx
144 for m in ml:
145 m = m.group
146 append(a(
147 resolve_expr(source, lno, 'xinput', m('xinput')),
148 resolve_expr(source, lno, 'y', m('y')),
149 m('udlr'), m('enum'), m('label'), idx))
150 idx = idx + 1
151 # If the loop executes zero times, then the regular
152 # expression failed to match, `old_idx is idx` is True, and
153 # an exception should be raised, because well-formed input
154 # will always match at least once.
155 #
156 # If the loop executes at least once, then a result was
157 # found, not `old_idx is idx`, and no exception is necessary.
158 if old_idx is idx:
159 raise InputException(f'{source}:{lno}: failed to match regex for line {line!r}\n')
160 if not array:
161 # An empty array is not useful, but may exist when the
162 # developer is adding a new array and has not yet defined
163 # any elements.
164 return f'\n/* {array_name} - udlr blank */',
165 # Generate a temporary list with the elements sorted for u/d
166 # navigation. Walk the temporary and assign appropriate u/d
167 # references.
168 s = sorted(array, key=a.key_vertical)
169 p = s[-1]
170 for i in s:
171 i.next_u = p
172 p.next_d = i
173 p = i
174 # As above, but sorted for l/r navigation.
175 s = sorted(array, key=a.key_horizontal)
176 p = s[-1]
177 for i in s:
178 i.next_l = p
179 p.next_r = i
180 p = i
181 define_enum_footer = '};'
182 enum = []
183 label = []
184 # Generate the `#define` lines using the relations computed by
185 # the preceding loops. Both ordering loops must execute
186 # completely before the next_* data required by the udlr
187 # `#define` lines is available. The udlr logic cannot be folded
188 # into a prior loop.
189 #
190 # The enum member and label logic could be handled in a prior
191 # loop, but are more logical here. Moving them to an earlier
192 # loop offers no gain.
193 result = [f'/* {array_name} - udlr define */']
194 for i in array:
195 idx = i.idx
196 # This must be a `#define` since it expands to a comma-separated
197 # list of values for a structure initializer.
198 result.append(f'#define {i.name}()\t/* [{idx:2d}] */\t{i.next_u.idx:2d},{i.next_d.idx:3d},{i.next_l.idx:3d},{i.next_r.idx:3d}')
199 il = i.enum
200 if il:
201 # Generate `#define` statements to allow the consuming code to
202 # use `#ifdef` to detect which members exist.
203 enum.append(f'''\
204 #define dxx_kconfig_ui_{array_name}_{il} dxx_kconfig_ui_{array_name}::{il}
205 {il} = {idx},''')
206 il = i.label
207 if il:
208 label.append(f'\t\\\n\t/* [{idx:2d}] */\t{il} "\\0"')
209 if enum:
210 result.append(f'\n/* {array_name} - enum define */')
211 # Use an `enum class` here so that the values can only be used in
212 # arrays specifically marked for this index type. This prevents
213 # mixing types, such as indexing the mouse array with joystick
214 # index values.
215 result.append(f'enum class dxx_kconfig_ui_{array_name} : unsigned {{')
216 result.extend(enum)
217 result.append(define_enum_footer)
218 else:
219 result.append(f'\n/* {array_name} - enum blank */')
220 if label:
221 result.append(f'\n#define DXX_KCONFIG_UI_LABEL_{array_name}{"".join(label)}\n')
222 return result
223
224 # Given an iterable over a CPP-processed C++ file, find each kc_item
225 # array in the file, generate appropriate #define statements, and
226 # return the statements as a multiline string.
227 #
228 # script - path to this script
229 #
230 # fi - iterable over the CPP-processed C++ file
231 #
232 # _re_match_defn_const - bound match method for a regular expression
233 # to extract a C++ expression from the initializer of a
234 # std::integral_constant.
235 #
236 # _re_match_defn_array - bound match method for a regular expression
237 # to match the opening definition of a C++ kc_item array.
238 def prepare_text(self,script,fi,
239 _re_match_defn_const=re.compile(r'constexpr\s+std::integral_constant<\w+\s*,\s*((?:\w+\s*\+\s*)*\w+)>\s*(\w+){};').match,
240 _re_match_defn_array=re.compile(r'constexpr\s+kc_item\s+(\w+)\s*\[\]\s*=\s*{').match
241 ):
242 source = fi.name
243 result = [f'''/* This is a generated file. Do not edit.
244 * This file was generated by {script}
245 * This file was generated from {source}
246 */
247 ''']
248 lines = []
249 # Simple line reassembly is done automatically, based on the
250 # requirement that braces be balanced to complete an
251 # initializer. This is required to handle cases where the
252 # initializer split onto multiple lines due to an embedded
253 # preprocessor directive.
254 unbalanced_open_brace = 0
255 array_name = None
256 partial_line = None
257 generate_defines = self.generate_defines
258 for lno, line in enumerate(fi, 1):
259 if line.startswith('#'):
260 # Ignore line/column position information
261 continue
262 line = line.strip()
263 if not line:
264 # Ignore blank lines
265 continue
266 if line == '};':
267 # End of array found. Check for context errors.
268 # Compute #define statements for this array. Reset for
269 # the next array.
270 if array_name is None:
271 raise InputException(f'{source}:{lno}: end of array definition while no array open')
272 if unbalanced_open_brace:
273 raise InputException(f'{source}:{lno}: end of array definition while reading array initialization')
274 result.extend(generate_defines(array_name, source, lines))
275 lines = []
276 array_name = None
277 continue
278 if array_name is None:
279 # These expressions should never match outside an array
280 # definition, so apply them only when an array is open.
281 m = _re_match_defn_const(line)
282 if m is not None:
283 # Record a C++ std::integral_constant for later use
284 # evaluating table cells.
285 g = m.group
286 self.constants[g(2)] = self.resolve_expr(source, lno, 'constant', g(1))
287 continue
288 m = _re_match_defn_array(line)
289 if m is not None:
290 # Array definition found.
291 array_name = m.group(1)
292 continue
293 count = line.count
294 unbalanced_open_brace += count('{') - count('}')
295 if unbalanced_open_brace < 0:
296 raise InputException(f'{source}:{lno}: brace count becomes negative')
297 if partial_line is not None:
298 # Insert a fake whitespace to avoid combining a token at
299 # the end of one line with a token at the beginning of
300 # the next.
301 line = partial_line + ' ' + line
302 if unbalanced_open_brace:
303 # If braces are unbalanced, assume that this line is
304 # incomplete, save it for later, and proceed to the next
305 # line.
306 partial_line = line
307 continue
308 partial_line = None
309 lines.append((lno, line))
310 # Check for context error.
311 if array_name is not None:
312 raise InputException(f'{source}: end of file while array definition open')
313 # Ensure end-of-line at end-of-file.
314 result.append('')
315 return '\n'.join(result)
316
317 @staticmethod
318 def write_generated_text(target,generated_text):
319 if not target:
320 # As a special case, allow this script to be used as a
321 # filter.
322 sys.stdout.write(generated_text)
323 return
324 from tempfile import mkstemp
325 os_path = os.path
326 fd, path = mkstemp(suffix='', prefix=f'{os_path.basename(target)}.', dir=os_path.dirname(target), text=True)
327 os.write(fd, generated_text.encode())
328 os.close(fd)
329 os.rename(path, target)
330
331 def main(self,script,source,target):
332 # Read the entire file and prepare the output text before
333 # opening the output file.
334 try:
335 with (open(source, 'r') if source else sys.stdin) as fi:
336 generated_text = self.prepare_text(script,fi)
337 except InputException as e:
338 # Normally, input exceptions are presented as a simple
339 # error message. If this environment variable is set,
340 # show the full traceback.
341 if os.getenv('DXX_KCONFIG_UDLR_TRACEBACK') is not None:
342 raise
343 sys.stderr.write(f'error: {e!s}\n')
344 sys.exit(1)
345 self.write_generated_text(target,generated_text)
346
347 if __name__ == '__main__':
348 a = sys.argv
349 # As a convenience feature, if no input filename is given, read
350 # stdin. If no output filename is given, write to stdout.
351 l = len(a)
352 if l < 2:
353 a.append(None)
354 if l < 3:
355 a.append(None)
356 Main().main(*a[0:3])