Mercurial > lcfOS
annotate python/c3/visitor.py @ 288:a747a45dcd78
Various styling work
author | Windel Bouwman |
---|---|
date | Thu, 21 Nov 2013 14:26:13 +0100 |
parents | e64bae57cda8 |
children |
rev | line source |
---|---|
163 | 1 from .astnodes import * |
2 | |
288 | 3 |
163 | 4 class Visitor: |
228 | 5 """ |
215 | 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): | |
228 | 15 # Run visitor: |
16 if self.f_pre: | |
215 | 17 self.f_pre(node) |
18 | |
228 | 19 # Descent into subnodes: |
20 if type(node) is Package: | |
215 | 21 for decl in node.declarations: |
22 self.do(decl) | |
228 | 23 elif type(node) is Function: |
215 | 24 for s in node.declarations: |
25 self.do(s) | |
26 self.do(node.body) | |
228 | 27 elif type(node) is CompoundStatement: |
230 | 28 for s in node.statements: |
29 self.do(s) | |
228 | 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: | |
220
3f6c30a5d234
Major change in expression parsing to enable pointers and structs
Windel Bouwman
parents:
215
diff
changeset
|
44 self.do(node.a) |
228 | 45 self.do(node.b) |
46 elif type(node) is Unop: | |
47 self.do(node.a) | |
48 elif type(node) is ExpressionStatement: | |
222 | 49 self.do(node.ex) |
228 | 50 elif type(node) is TypeCast: |
222 | 51 self.do(node.a) |
228 | 52 elif type(node) is FieldRef: |
225 | 53 self.do(node.base) |
228 | 54 elif type(node) is Deref: |
225 | 55 self.do(node.ptr) |
228 | 56 elif type(node) is Constant: |
230 | 57 self.do(node.value) |
288 | 58 elif type(node) in [VariableUse, Variable, Literal, FunctionType, |
59 DefinedType, FormalParameter, LocalVariable]: | |
230 | 60 # Those nodes do not have child nodes. |
61 pass | |
228 | 62 elif type(node) is WhileStatement: |
230 | 63 self.do(node.condition) |
64 self.do(node.statement) | |
228 | 65 else: |
230 | 66 raise Exception('Could not visit "{0}"'.format(node)) |
163 | 67 |
228 | 68 # run post function |
69 if self.f_post: | |
215 | 70 self.f_post(node) |
71 | |
288 | 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 |