Class: Parlour::TypeParser::NodePath

Inherits:
Object
  • Object
show all
Extended by:
T::Sig
Defined in:
lib/parlour/type_parser.rb

Overview

Represents a path of indices which can be traversed to reach a specific node in an AST.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(indices) ⇒ NodePath



31
32
33
# File 'lib/parlour/type_parser.rb', line 31

def initialize(indices)
  @indices = indices
end

Instance Attribute Details

#indicesArray<Integer> (readonly)



25
26
27
# File 'lib/parlour/type_parser.rb', line 25

def indices
  @indices
end

Instance Method Details

#child(index) ⇒ NodePath



48
49
50
# File 'lib/parlour/type_parser.rb', line 48

def child(index)
  NodePath.new(indices + [index])
end

#parentNodePath



37
38
39
40
41
42
43
# File 'lib/parlour/type_parser.rb', line 37

def parent
  if indices.empty?
    raise IndexError, 'cannot get parent of an empty path'
  else
    NodePath.new(T.must(indices[0...-1]))
  end
end

#sibling(offset) ⇒ NodePath



57
58
59
60
61
62
63
64
65
66
67
# File 'lib/parlour/type_parser.rb', line 57

def sibling(offset)
  if indices.empty?
    raise IndexError, 'cannot get sibling of an empty path'
  else
    *xs, x = indices
    x = T.must(x)
    raise ArgumentError, "sibling offset of #{offset} results in " \
      "negative index of #{x + offset}" if x + offset < 0
    NodePath.new(T.must(xs) + [x + offset])
  end
end

#traverse(start) ⇒ Parser::AST::Node

Follows this path of indices from an AST node.



74
75
76
77
78
79
80
81
# File 'lib/parlour/type_parser.rb', line 74

def traverse(start)
  current = T.unsafe(start)
  indices.each do |index|
    raise IndexError, 'path does not exist' if index >= current.to_a.length
    current = current.to_a[index]
  end
  current
end