Mercurial > lcfOS
comparison python/ppci/c3/visitor.py @ 300:158068af716c
yafm
author | Windel Bouwman |
---|---|
date | Tue, 03 Dec 2013 18:00:22 +0100 |
parents | python/c3/visitor.py@a747a45dcd78 |
children | b145f8e6050b |
comparison
equal
deleted
inserted
replaced
299:674789d9ff37 | 300:158068af716c |
---|---|
1 from .astnodes import * | |
2 | |
3 | |
4 class Visitor: | |
5 """ | |
6 Visitor that can visit all nodes in the AST | |
7 and run pre and post functions. | |
8 """ | |
9 def visit(self, node, f_pre=None, f_post=None): | |
10 self.f_pre = f_pre | |
11 self.f_post = f_post | |
12 self.do(node) | |
13 | |
14 def do(self, node): | |
15 # Run visitor: | |
16 if self.f_pre: | |
17 self.f_pre(node) | |
18 | |
19 # Descent into subnodes: | |
20 if type(node) is Package: | |
21 for decl in node.declarations: | |
22 self.do(decl) | |
23 elif type(node) is Function: | |
24 for s in node.declarations: | |
25 self.do(s) | |
26 self.do(node.body) | |
27 elif type(node) is CompoundStatement: | |
28 for s in node.statements: | |
29 self.do(s) | |
30 elif type(node) is IfStatement: | |
31 self.do(node.condition) | |
32 self.do(node.truestatement) | |
33 if node.falsestatement: | |
34 self.do(node.falsestatement) | |
35 elif type(node) is FunctionCall: | |
36 for arg in node.args: | |
37 self.do(arg) | |
38 elif type(node) is Assignment: | |
39 self.do(node.lval) | |
40 self.do(node.rval) | |
41 elif type(node) is ReturnStatement: | |
42 self.do(node.expr) | |
43 elif type(node) is Binop: | |
44 self.do(node.a) | |
45 self.do(node.b) | |
46 elif type(node) is Unop: | |
47 self.do(node.a) | |
48 elif type(node) is ExpressionStatement: | |
49 self.do(node.ex) | |
50 elif type(node) is TypeCast: | |
51 self.do(node.a) | |
52 elif type(node) is FieldRef: | |
53 self.do(node.base) | |
54 elif type(node) is Deref: | |
55 self.do(node.ptr) | |
56 elif type(node) is Constant: | |
57 self.do(node.value) | |
58 elif type(node) in [VariableUse, Variable, Literal, FunctionType, | |
59 DefinedType, FormalParameter, LocalVariable]: | |
60 # Those nodes do not have child nodes. | |
61 pass | |
62 elif type(node) is WhileStatement: | |
63 self.do(node.condition) | |
64 self.do(node.statement) | |
65 else: | |
66 raise Exception('Could not visit "{0}"'.format(node)) | |
67 | |
68 # run post function | |
69 if self.f_post: | |
70 self.f_post(node) | |
71 | |
72 | |
73 class AstPrinter: | |
74 """ Prints an AST as text """ | |
75 def printAst(self, pkg): | |
76 self.indent = 0 | |
77 visitor = Visitor() | |
78 visitor.visit(pkg, self.print1, self.print2) | |
79 | |
80 def print1(self, node): | |
81 print(' ' * self.indent + str(node)) | |
82 self.indent += 2 | |
83 | |
84 def print2(self, node): | |
85 self.indent -= 2 |