Class: SyntaxTree::Search

Inherits:
Object
  • Object
show all
Defined in:
lib/syntax_tree/search.rb

Overview

Provides an interface for searching for a pattern of nodes against a subtree of an AST.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(pattern) ⇒ Search

Returns a new instance of Search.



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

def initialize(pattern)
  @pattern = pattern
end

Instance Attribute Details

#patternObject (readonly)

Returns the value of attribute pattern.



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

def pattern
  @pattern
end

Instance Method Details

#scan(root) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/syntax_tree/search.rb', line 13

def scan(root)
  return to_enum(__method__, root) unless block_given?
  queue = [root]

  until queue.empty?
    node = queue.shift
    next unless node

    yield node if pattern.call(node)
    queue += node.child_nodes
  end
end