163
|
1 from .astnodes import *
|
|
2
|
|
3 class Visitor:
|
|
4 """ Visitor that visits all nodes in the ast and runs the function 'f' """
|
|
5 def __init__(self, f1, f2):
|
|
6 self.f1 = f1
|
|
7 self.f2 = f2
|
|
8 def visit(self, node):
|
|
9 # Run visitor:
|
|
10 self.f1(node)
|
|
11 # Descent into subnodes:
|
|
12 if type(node) is Package:
|
|
13 for s in node.scope:
|
|
14 self.visit(s)
|
|
15 elif type(node) is Function:
|
|
16 for s in node.scope:
|
|
17 self.visit(s)
|
|
18 self.visit(node.typ)
|
|
19 self.visit(node.body)
|
|
20 elif type(node) is CompoundStatement:
|
|
21 for s in node.statements:
|
|
22 self.visit(s)
|
|
23 elif type(node) is IfStatement:
|
|
24 self.visit(node.condition)
|
|
25 self.visit(node.truestatement)
|
|
26 self.visit(node.falsestatement)
|
167
|
27 elif type(node) is FunctionCall:
|
|
28 for arg in node.args:
|
|
29 self.visit(arg)
|
163
|
30 elif type(node) is Assignment:
|
|
31 self.visit(node.lval)
|
|
32 self.visit(node.rval)
|
|
33 elif type(node) is ReturnStatement:
|
|
34 self.visit(node.expr)
|
|
35 elif type(node) is Binop:
|
|
36 self.visit(node.a)
|
|
37 self.visit(node.b)
|
166
|
38 elif type(node) is Constant:
|
|
39 self.visit(node.value)
|
|
40 elif type(node) in [EmptyStatement, VariableUse, Variable, Literal, FunctionType]:
|
163
|
41 # Those nodes do not have child nodes.
|
|
42 pass
|
|
43 else:
|
|
44 print('UNK visit', node)
|
|
45 self.f2(node)
|
|
46
|
|
47
|