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.

Defined Under Namespace

Classes: UncompilableError

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(query) ⇒ Search

Returns a new instance of Search.



12
13
14
15
# File 'lib/syntax_tree/search.rb', line 12

def initialize(query)
  root = SyntaxTree.parse("case nil\nin #{query}\nend")
  @matcher = compile(root.statements.body.first.consequent.pattern)
end

Instance Attribute Details

#matcherObject (readonly)

Returns the value of attribute matcher.



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

def matcher
  @matcher
end

Instance Method Details

#scan(root) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/syntax_tree/search.rb', line 17

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 matcher.call(node)
    queue += node.child_nodes
  end
end