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

Parameters:

  • indices (Array<Integer>)

    The path of indices.



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

def initialize(indices)
  @indices = indices
end

Instance Attribute Details

#indicesArray<Integer> (readonly)

Returns The path of indices.

Returns:

  • (Array<Integer>)

    The path of indices.



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

def indices
  @indices
end

Instance Method Details

#child(index) ⇒ NodePath

Returns The path to the child at the given index.

Parameters:

  • index (Integer)

    The index of the child whose path to return.

Returns:

  • (NodePath)

    The path to the child at the given index.



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

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

#parentNodePath

Returns The parent path for the node at this path.

Returns:

  • (NodePath)

    The parent path for the node at this path.



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

Returns The path to the sibling with the given context.

Parameters:

  • offset (Integer)

    The sibling offset to use. 0 is the current node, -1 is the previous node, or 3 is is the node three nodes after this one.

Returns:

  • (NodePath)

    The path to the sibling with the given context.



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.

Parameters:

  • start (Parser::AST::Node)

    The AST node to start from.

Returns:

  • (Parser::AST::Node)

    The resulting 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