Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 6c41e75

Browse files
committed
Track parent context in the mutation visitor
1 parent bab6417 commit 6c41e75

File tree

1 file changed

+27
-1
lines changed

1 file changed

+27
-1
lines changed

lib/syntax_tree/visitor/mutation_visitor.rb

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,33 @@ module SyntaxTree
44
class Visitor
55
# This visitor walks through the tree and copies each node as it is being
66
# visited. This is useful for mutating the tree before it is formatted.
7-
class MutationVisitor < Visitor
7+
class MutationVisitor < BasicVisitor
8+
# Here we maintain a stack of parent nodes so that it's easy to reflect on
9+
# the context of a given node while mutating it.
10+
attr_reader :stack
11+
12+
def initialize
13+
@stack = []
14+
end
15+
16+
# This is the main entrypoint that's going to be called when we're
17+
# recursing down through the tree.
18+
def visit(node)
19+
return unless node
20+
21+
stack << node
22+
result = node.accept(self)
23+
24+
stack.pop
25+
result
26+
end
27+
28+
# This is a small helper to visit an array of nodes and return the result
29+
# of visiting them all.
30+
def visit_all(nodes)
31+
nodes.map { |node| visit(node) }
32+
end
33+
834
# Visit a BEGINBlock node.
935
def visit_BEGIN(node)
1036
node.copy(

0 commit comments

Comments
 (0)