Class: SyntaxTree::MutationVisitor

Inherits:
BasicVisitor show all
Defined in:
lib/syntax_tree/mutation_visitor.rb

Overview

This visitor walks through the tree and copies each node as it is being visited. This is useful for mutating the tree before it is formatted.

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods inherited from BasicVisitor

valid_visit_methods, #visit_all, #visit_child_nodes, visit_method, visit_methods

Constructor Details

#initializeMutationVisitor

Returns a new instance of MutationVisitor.



9
10
11
# File 'lib/syntax_tree/mutation_visitor.rb', line 9

def initialize
  @mutations = []
end

Instance Attribute Details

#mutationsObject (readonly)

Returns the value of attribute mutations.



7
8
9
# File 'lib/syntax_tree/mutation_visitor.rb', line 7

def mutations
  @mutations
end

Instance Method Details

#mutate(query, &block) ⇒ Object

Create a new mutation based on the given query that will mutate the node using the given block. The block should return a new node that will take the place of the given node in the tree. These blocks frequently make use of the ‘copy` method on nodes to create a new node with the same properties as the original node.



18
19
20
# File 'lib/syntax_tree/mutation_visitor.rb', line 18

def mutate(query, &block)
  mutations << [Pattern.new(query).compile, block]
end

#visit(node) ⇒ Object

This is the base visit method for each node in the tree. It first creates a copy of the node using the visit_* methods defined below. Then it checks each mutation in sequence and calls it if it finds a match.



25
26
27
28
29
30
31
32
33
34
# File 'lib/syntax_tree/mutation_visitor.rb', line 25

def visit(node)
  return unless node
  result = node.accept(self)

  mutations.each do |(pattern, mutation)|
    result = mutation.call(result) if pattern.call(result)
  end

  result
end