Class: RBI::Rewriters::GroupNodes

Inherits:
Visitor
  • Object
show all
Defined in:
lib/rbi/rewriters/group_nodes.rb

Instance Method Summary collapse

Methods inherited from Visitor

#visit_all, #visit_file

Instance Method Details

#visit(node) ⇒ Object

: (Node? node) -> void



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/rbi/rewriters/group_nodes.rb', line 11

def visit(node)
  return unless node

  case node
  when Tree
    # Single-pass: visit each child, compute its group_kind once, and classify.
    # We avoid calling `child.detach` in a loop (which is O(n) per call due to
    # Array#delete), and instead clear the parent's nodes array in O(1) after
    # all children have been classified.
    groups = {} #: Hash[Group::Kind, Group]
    node.nodes.each do |child|
      visit(child)
      kind = group_kind(child)
      group = groups[kind] ||= Group.new(kind)
      child.parent_tree = nil
      group << child
    end
    node.nodes.clear

    groups.each_value { |group| node << group }
  end
end