Class: RBI::Rewriters::SortNodes

Inherits:
Visitor
  • Object
show all
Extended by:
T::Sig
Defined in:
lib/rbi/rewriters/sort_nodes.rb

Instance Method Summary collapse

Methods inherited from Visitor

#visit_all

Instance Method Details

#visit(node) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/rbi/rewriters/sort_nodes.rb', line 10

def visit(node)
  return unless node.is_a?(Tree)
  visit_all(node.nodes)
  original_order = node.nodes.map.with_index.to_h
  node.nodes.sort! do |a, b|
    # First we try to compare the nodes by their node rank (based on the node type)
    res = node_rank(a) <=> node_rank(b)
    next res if res != 0 # we can sort the nodes by their rank, let's stop here

    # Then, if the nodes ranks are the same (res == 0), we try to compare the nodes by their name
    res = node_name(a) <=> node_name(b)
    next res if res && res != 0 # we can sort the nodes by their name, let's stop here

    # Finally, if the two nodes have the same rank and the same name or at least one node is anonymous then,
    T.must(original_order[a]) <=> T.must(original_order[b]) # we keep the original order
  end
end