diff python/c3/visitor.py @ 163:8104fc8b5e90

Added visitor to c3
author Windel Bouwman
date Mon, 18 Mar 2013 20:13:57 +0100
parents
children da0087b82fbe
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/python/c3/visitor.py	Mon Mar 18 20:13:57 2013 +0100
@@ -0,0 +1,45 @@
+from .astnodes import *
+
+class Visitor:
+   """ Visitor that visits all nodes in the ast and runs the function 'f' """
+   def __init__(self, f1, f2):
+      self.f1 = f1
+      self.f2 = f2
+   def visit(self, node):
+      # Run visitor:
+      self.f1(node)
+      # Descent into subnodes:
+      if type(node) is Package:
+         for s in node.scope:
+            self.visit(s)
+      elif type(node) is Function:
+         for s in node.scope:
+            self.visit(s)
+         self.visit(node.typ)
+         self.visit(node.body)
+      elif type(node) is CompoundStatement:
+         for s in node.statements:
+            self.visit(s)
+      elif type(node) is IfStatement:
+         self.visit(node.condition)
+         self.visit(node.truestatement)
+         self.visit(node.falsestatement)
+      elif type(node) is ProcedureCall:
+         pass
+         # TODO
+      elif type(node) is Assignment:
+         self.visit(node.lval)
+         self.visit(node.rval)
+      elif type(node) is ReturnStatement:
+         self.visit(node.expr)
+      elif type(node) is Binop:
+         self.visit(node.a)
+         self.visit(node.b)
+      elif type(node) in [EmptyStatement, Constant, VariableUse, Variable, Literal, FunctionType]:
+         # Those nodes do not have child nodes.
+         pass
+      else:
+         print('UNK visit', node)
+      self.f2(node)
+
+