Skip to content

Commit dc9a924

Browse files
committed
Make read-only visitor more visitor-like.
By moving the descend logic into generic_visit, read-only visitors have the ability to do pre and post descend logic. This is also matching what python's ast.Visitor does.
1 parent edb282e commit dc9a924

File tree

2 files changed

+8
-12
lines changed

2 files changed

+8
-12
lines changed

fluent.syntax/fluent/syntax/ast.py

+5-8
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,8 @@ class Visitor(object):
1010
To generally define which nodes not to descend in to, overload
1111
`generic_visit`.
1212
To handle specific node types, add methods like `visit_Pattern`.
13-
The boolean value of the returned value determines if the visitor
14-
descends into the children of the given AST node.
13+
If you want to still descend into the children of the node, call
14+
`generic_visit` of the superclass.
1515
'''
1616
def visit(self, node):
1717
if isinstance(node, list):
@@ -22,14 +22,11 @@ def visit(self, node):
2222
return
2323
nodename = type(node).__name__
2424
visit = getattr(self, 'visit_{}'.format(nodename), self.generic_visit)
25-
should_descend = visit(node)
26-
if not should_descend:
27-
return
28-
for propname, propvalue in vars(node).items():
29-
self.visit(propvalue)
25+
visit(node)
3026

3127
def generic_visit(self, node):
32-
return True
28+
for propname, propvalue in vars(node).items():
29+
self.visit(propvalue)
3330

3431

3532
class Transformer(Visitor):

fluent.syntax/tests/syntax/test_visitor.py

+3-4
Original file line numberDiff line numberDiff line change
@@ -18,11 +18,10 @@ def __init__(self):
1818

1919
def generic_visit(self, node):
2020
self.calls[type(node).__name__] += 1
21-
return super(MockVisitor, self).generic_visit(node)
21+
super(MockVisitor, self).generic_visit(node)
2222

2323
def visit_Pattern(self, node):
2424
self.pattern_calls += 1
25-
return False
2625

2726

2827
class TestVisitor(unittest.TestCase):
@@ -87,11 +86,11 @@ def __init__(self):
8786
self.word_count = 0
8887

8988
def generic_visit(self, node):
90-
return not isinstance(node, (ast.Span, ast.Annotation))
89+
if not isinstance(node, (ast.Span, ast.Annotation)):
90+
super(VisitorCounter, self).generic_visit(node)
9191

9292
def visit_TextElement(self, node):
9393
self.word_count += len(node.value.split())
94-
return False
9594

9695

9796
class ReplaceText(object):

0 commit comments

Comments
 (0)