-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathvisitors.py
49 lines (44 loc) · 1.77 KB
/
visitors.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import ast
class PLPostorderVisitor():
def visit(self, node, config=None):
"""Visit a node."""
if node == None:
return None
# visit children first
for field, value in ast.iter_fields(node):
if isinstance(value, list):
for item in value:
if isinstance(item, ast.AST):
self.visit(item, config)
elif isinstance(value, ast.AST):
self.visit(value, config)
# visit current node after visiting children (postorder)
method = 'visit_' + node.__class__.__name__
visitor = getattr(self, method, self.generic_visit)
visit_return = visitor(node, config)
if config == "DEBUG" and hasattr(node, "pl_data"):
print(node.__class__.__name__+": ", node.pl_data)
return visit_return
def generic_visit(self, node, config=None):
"""Called if no explicit visitor function exists for a node."""
pass
class PLPreorderVisitor():
def visit(self, node, config=None):
"""Visit a node."""
if node == None:
return None
method = 'visit_' + node.__class__.__name__
visitor = getattr(self, method, self.generic_visit)
visit_return = visitor(node, config)
# visit children nodes
for field, value in ast.iter_fields(node):
if isinstance(value, list):
for item in value:
if isinstance(item, ast.AST):
self.visit(item, config)
elif isinstance(value, ast.AST):
self.visit(value, config)
return visit_return
def generic_visit(self, node, config=None):
"""Called if no explicit visitor function exists for a node."""
pass