1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
|
# Copyright 2019 The Meson development team
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# This class contains the basic functionality needed to run any interpreter
# or an interpreter-based tool
from __future__ import annotations
from .. import mparser
from .visitor import AstVisitor
import re
import typing as T
arithmic_map = {
'add': '+',
'sub': '-',
'mod': '%',
'mul': '*',
'div': '/'
}
class AstPrinter(AstVisitor):
def __init__(self, indent: int = 2, arg_newline_cutoff: int = 5, update_ast_line_nos: bool = False):
self.result = ''
self.indent = indent
self.arg_newline_cutoff = arg_newline_cutoff
self.ci = ''
self.is_newline = True
self.last_level = 0
self.curr_line = 1 if update_ast_line_nos else None
def post_process(self) -> None:
self.result = re.sub(r'\s+\n', '\n', self.result)
def append(self, data: str, node: mparser.BaseNode) -> None:
self.last_level = node.level
if self.is_newline:
self.result += ' ' * (node.level * self.indent)
self.result += data
self.is_newline = False
def append_padded(self, data: str, node: mparser.BaseNode) -> None:
if self.result and self.result[-1] not in [' ', '\n']:
data = ' ' + data
self.append(data + ' ', node)
def newline(self) -> None:
self.result += '\n'
self.is_newline = True
if self.curr_line is not None:
self.curr_line += 1
def visit_BooleanNode(self, node: mparser.BooleanNode) -> None:
self.append('true' if node.value else 'false', node)
node.lineno = self.curr_line or node.lineno
def visit_IdNode(self, node: mparser.IdNode) -> None:
assert isinstance(node.value, str)
self.append(node.value, node)
node.lineno = self.curr_line or node.lineno
def visit_NumberNode(self, node: mparser.NumberNode) -> None:
self.append(str(node.value), node)
node.lineno = self.curr_line or node.lineno
def escape(self, val: str) -> str:
return val.translate(str.maketrans({'\'': '\\\'',
'\\': '\\\\'}))
def visit_StringNode(self, node: mparser.StringNode) -> None:
assert isinstance(node.value, str)
self.append("'" + self.escape(node.value) + "'", node)
node.lineno = self.curr_line or node.lineno
def visit_FormatStringNode(self, node: mparser.FormatStringNode) -> None:
assert isinstance(node.value, str)
self.append("f'" + node.value + "'", node)
node.lineno = self.curr_line or node.lineno
def visit_ContinueNode(self, node: mparser.ContinueNode) -> None:
self.append('continue', node)
node.lineno = self.curr_line or node.lineno
def visit_BreakNode(self, node: mparser.BreakNode) -> None:
self.append('break', node)
node.lineno = self.curr_line or node.lineno
def visit_ArrayNode(self, node: mparser.ArrayNode) -> None:
node.lineno = self.curr_line or node.lineno
self.append('[', node)
node.args.accept(self)
self.append(']', node)
def visit_DictNode(self, node: mparser.DictNode) -> None:
node.lineno = self.curr_line or node.lineno
self.append('{', node)
node.args.accept(self)
self.append('}', node)
def visit_OrNode(self, node: mparser.OrNode) -> None:
node.left.accept(self)
self.append_padded('or', node)
node.lineno = self.curr_line or node.lineno
node.right.accept(self)
def visit_AndNode(self, node: mparser.AndNode) -> None:
node.left.accept(self)
self.append_padded('and', node)
node.lineno = self.curr_line or node.lineno
node.right.accept(self)
def visit_ComparisonNode(self, node: mparser.ComparisonNode) -> None:
node.left.accept(self)
self.append_padded(node.ctype, node)
node.lineno = self.curr_line or node.lineno
node.right.accept(self)
def visit_ArithmeticNode(self, node: mparser.ArithmeticNode) -> None:
node.left.accept(self)
self.append_padded(arithmic_map[node.operation], node)
node.lineno = self.curr_line or node.lineno
node.right.accept(self)
def visit_NotNode(self, node: mparser.NotNode) -> None:
node.lineno = self.curr_line or node.lineno
self.append_padded('not', node)
node.value.accept(self)
def visit_CodeBlockNode(self, node: mparser.CodeBlockNode) -> None:
node.lineno = self.curr_line or node.lineno
for i in node.lines:
i.accept(self)
self.newline()
def visit_IndexNode(self, node: mparser.IndexNode) -> None:
node.iobject.accept(self)
node.lineno = self.curr_line or node.lineno
self.append('[', node)
node.index.accept(self)
self.append(']', node)
def visit_MethodNode(self, node: mparser.MethodNode) -> None:
node.lineno = self.curr_line or node.lineno
node.source_object.accept(self)
self.append('.' + node.name + '(', node)
node.args.accept(self)
self.append(')', node)
def visit_FunctionNode(self, node: mparser.FunctionNode) -> None:
node.lineno = self.curr_line or node.lineno
self.append(node.func_name + '(', node)
node.args.accept(self)
self.append(')', node)
def visit_AssignmentNode(self, node: mparser.AssignmentNode) -> None:
node.lineno = self.curr_line or node.lineno
self.append(node.var_name + ' = ', node)
node.value.accept(self)
def visit_PlusAssignmentNode(self, node: mparser.PlusAssignmentNode) -> None:
node.lineno = self.curr_line or node.lineno
self.append(node.var_name + ' += ', node)
node.value.accept(self)
def visit_ForeachClauseNode(self, node: mparser.ForeachClauseNode) -> None:
node.lineno = self.curr_line or node.lineno
self.append_padded('foreach', node)
self.append_padded(', '.join(node.varnames), node)
self.append_padded(':', node)
node.items.accept(self)
self.newline()
node.block.accept(self)
self.append('endforeach', node)
def visit_IfClauseNode(self, node: mparser.IfClauseNode) -> None:
node.lineno = self.curr_line or node.lineno
prefix = ''
for i in node.ifs:
self.append_padded(prefix + 'if', node)
prefix = 'el'
i.accept(self)
if not isinstance(node.elseblock, mparser.EmptyNode):
self.append('else', node)
node.elseblock.accept(self)
self.append('endif', node)
def visit_UMinusNode(self, node: mparser.UMinusNode) -> None:
node.lineno = self.curr_line or node.lineno
self.append_padded('-', node)
node.value.accept(self)
def visit_IfNode(self, node: mparser.IfNode) -> None:
node.lineno = self.curr_line or node.lineno
node.condition.accept(self)
self.newline()
node.block.accept(self)
def visit_TernaryNode(self, node: mparser.TernaryNode) -> None:
node.lineno = self.curr_line or node.lineno
node.condition.accept(self)
self.append_padded('?', node)
node.trueblock.accept(self)
self.append_padded(':', node)
node.falseblock.accept(self)
def visit_ArgumentNode(self, node: mparser.ArgumentNode) -> None:
node.lineno = self.curr_line or node.lineno
break_args = (len(node.arguments) + len(node.kwargs)) > self.arg_newline_cutoff
for i in node.arguments + list(node.kwargs.values()):
if not isinstance(i, (mparser.ElementaryNode, mparser.IndexNode)):
break_args = True
if break_args:
self.newline()
for i in node.arguments:
i.accept(self)
self.append(', ', node)
if break_args:
self.newline()
for key, val in node.kwargs.items():
key.accept(self)
self.append_padded(':', node)
val.accept(self)
self.append(', ', node)
if break_args:
self.newline()
if break_args:
self.result = re.sub(r', \n$', '\n', self.result)
else:
self.result = re.sub(r', $', '', self.result)
class AstJSONPrinter(AstVisitor):
def __init__(self) -> None:
self.result: T.Dict[str, T.Any] = {}
self.current = self.result
def _accept(self, key: str, node: mparser.BaseNode) -> None:
old = self.current
data: T.Dict[str, T.Any] = {}
self.current = data
node.accept(self)
self.current = old
self.current[key] = data
def _accept_list(self, key: str, nodes: T.Sequence[mparser.BaseNode]) -> None:
old = self.current
datalist: T.List[T.Dict[str, T.Any]] = []
for i in nodes:
self.current = {}
i.accept(self)
datalist += [self.current]
self.current = old
self.current[key] = datalist
def _raw_accept(self, node: mparser.BaseNode, data: T.Dict[str, T.Any]) -> None:
old = self.current
self.current = data
node.accept(self)
self.current = old
def setbase(self, node: mparser.BaseNode) -> None:
self.current['node'] = type(node).__name__
self.current['lineno'] = node.lineno
self.current['colno'] = node.colno
self.current['end_lineno'] = node.end_lineno
self.current['end_colno'] = node.end_colno
def visit_default_func(self, node: mparser.BaseNode) -> None:
self.setbase(node)
def gen_ElementaryNode(self, node: mparser.ElementaryNode) -> None:
self.current['value'] = node.value
self.setbase(node)
def visit_BooleanNode(self, node: mparser.BooleanNode) -> None:
self.gen_ElementaryNode(node)
def visit_IdNode(self, node: mparser.IdNode) -> None:
self.gen_ElementaryNode(node)
def visit_NumberNode(self, node: mparser.NumberNode) -> None:
self.gen_ElementaryNode(node)
def visit_StringNode(self, node: mparser.StringNode) -> None:
self.gen_ElementaryNode(node)
def visit_FormatStringNode(self, node: mparser.FormatStringNode) -> None:
self.gen_ElementaryNode(node)
def visit_ArrayNode(self, node: mparser.ArrayNode) -> None:
self._accept('args', node.args)
self.setbase(node)
def visit_DictNode(self, node: mparser.DictNode) -> None:
self._accept('args', node.args)
self.setbase(node)
def visit_OrNode(self, node: mparser.OrNode) -> None:
self._accept('left', node.left)
self._accept('right', node.right)
self.setbase(node)
def visit_AndNode(self, node: mparser.AndNode) -> None:
self._accept('left', node.left)
self._accept('right', node.right)
self.setbase(node)
def visit_ComparisonNode(self, node: mparser.ComparisonNode) -> None:
self._accept('left', node.left)
self._accept('right', node.right)
self.current['ctype'] = node.ctype
self.setbase(node)
def visit_ArithmeticNode(self, node: mparser.ArithmeticNode) -> None:
self._accept('left', node.left)
self._accept('right', node.right)
self.current['op'] = arithmic_map[node.operation]
self.setbase(node)
def visit_NotNode(self, node: mparser.NotNode) -> None:
self._accept('right', node.value)
self.setbase(node)
def visit_CodeBlockNode(self, node: mparser.CodeBlockNode) -> None:
self._accept_list('lines', node.lines)
self.setbase(node)
def visit_IndexNode(self, node: mparser.IndexNode) -> None:
self._accept('object', node.iobject)
self._accept('index', node.index)
self.setbase(node)
def visit_MethodNode(self, node: mparser.MethodNode) -> None:
self._accept('object', node.source_object)
self._accept('args', node.args)
self.current['name'] = node.name
self.setbase(node)
def visit_FunctionNode(self, node: mparser.FunctionNode) -> None:
self._accept('args', node.args)
self.current['name'] = node.func_name
self.setbase(node)
def visit_AssignmentNode(self, node: mparser.AssignmentNode) -> None:
self._accept('value', node.value)
self.current['var_name'] = node.var_name
self.setbase(node)
def visit_PlusAssignmentNode(self, node: mparser.PlusAssignmentNode) -> None:
self._accept('value', node.value)
self.current['var_name'] = node.var_name
self.setbase(node)
def visit_ForeachClauseNode(self, node: mparser.ForeachClauseNode) -> None:
self._accept('items', node.items)
self._accept('block', node.block)
self.current['varnames'] = node.varnames
self.setbase(node)
def visit_IfClauseNode(self, node: mparser.IfClauseNode) -> None:
self._accept_list('ifs', node.ifs)
self._accept('else', node.elseblock)
self.setbase(node)
def visit_UMinusNode(self, node: mparser.UMinusNode) -> None:
self._accept('right', node.value)
self.setbase(node)
def visit_IfNode(self, node: mparser.IfNode) -> None:
self._accept('condition', node.condition)
self._accept('block', node.block)
self.setbase(node)
def visit_TernaryNode(self, node: mparser.TernaryNode) -> None:
self._accept('condition', node.condition)
self._accept('true', node.trueblock)
self._accept('false', node.falseblock)
self.setbase(node)
def visit_ArgumentNode(self, node: mparser.ArgumentNode) -> None:
self._accept_list('positional', node.arguments)
kwargs_list: T.List[T.Dict[str, T.Dict[str, T.Any]]] = []
for key, val in node.kwargs.items():
key_res: T.Dict[str, T.Any] = {}
val_res: T.Dict[str, T.Any] = {}
self._raw_accept(key, key_res)
self._raw_accept(val, val_res)
kwargs_list += [{'key': key_res, 'val': val_res}]
self.current['kwargs'] = kwargs_list
self.setbase(node)
|