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