Class: PryCoolline::ParenMatch::AST::Node

Inherits:
Struct
  • Object
show all
Defined in:
lib/pry-coolline/paren_match.rb

Overview

A block of code that was opened by a character, and may or may not (but should!) have been closed by another token.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(parser, open) ⇒ Node

Returns a new instance of Node.



138
139
140
141
142
143
144
145
146
147
148
149
150
# File 'lib/pry-coolline/paren_match.rb', line 138

def initialize(parser, open)
  self.elements = []
  self.open     = open

  while tok = parser.next_token and !tok.is_a?(CloseToken)
    case tok
    when OpenToken then elements << Node.new(parser, tok)
    when StrToken  then elements << Leaf.new(tok)
    end
  end

  self.close = tok # might be nil, which is okay
end

Instance Attribute Details

#closeCloseToken?

Returns the current value of close.

Returns:

  • (CloseToken, nil)

    the current value of close



137
138
139
# File 'lib/pry-coolline/paren_match.rb', line 137

def close
  @close
end

#elementsArray<Leaf, Node>

Other nodes within the opening and the closing tokens.

Returns:

  • (Array<Leaf, Node>)

    the current value of elements



137
138
139
# File 'lib/pry-coolline/paren_match.rb', line 137

def elements
  @elements
end

#openOpenToken

Returns the current value of open.

Returns:



137
138
139
# File 'lib/pry-coolline/paren_match.rb', line 137

def open
  @open
end

Instance Method Details

#pair_at(pos) ⇒ Pair

Finds the opening and closing tokens that should be matched at a certain position in the string.

It is assumed you can be looking for the closing parenthesis when on the opening one, or for the opening one when selecting the character that immediately follows it.

Parameters:

  • pos (Integer)

Returns:

  • (Pair)

    An (open, close) pair. Notice both the opening and closing tokens coud be nil.



153
154
155
156
157
158
159
160
161
162
163
164
165
166
# File 'lib/pry-coolline/paren_match.rb', line 153

def pair_at(pos)
  if pos == open.pos ||
      (close && pos == close.pos + close.str.size)
    Pair.new(open, close)
  else
    elements.each do |el|
      if pair = el.pair_at(pos)
        return pair
      end
    end

    nil
  end
end