Module: Furnace::AST::Visitor

Defined in:
lib/furnace/ast/visitor.rb

Instance Method Summary collapse

Instance Method Details

#visit(node) ⇒ Object



3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/furnace/ast/visitor.rb', line 3

def visit(node)
  replacements = {}

  node.children.each_with_index do |child, index|
    if child.is_a? Node
      visit child

      if child.type == :expand
        replacements[index] = child.children
      end
    end
  end

  if replacements.any?
    new_children = []

    node.children.each_with_index do |child, index|
      if replacements[index]
        new_children.concat replacements[index]
      else
        new_children.push child
      end
    end

    node.children.replace new_children
  end

  node.children.delete_if do |child|
    if child.is_a? Node
      child.parent = node

      child.type == :remove
    end
  end

  # Invoke a specific handler
  on_handler = :"on_#{node.type}"
  if respond_to? on_handler
    send on_handler, node
  end

  # Invoke a generic handler
  if respond_to? :on_any
    send :on_any, node
  end

  node
end