class Parser

Public Class Methods

new(code, pairs = Pairs) click to toggle source

@param (see ParenMatch#pair_at)

# File lib/pry-coolline/paren_match.rb, line 177
def initialize(code, pairs = Pairs)
  @tokens = tokenize(code, pairs)
end
parse(code, pairs = Pairs) click to toggle source

@param (see ParenMatch#pair_at) @return [AST::Root]

# File lib/pry-coolline/paren_match.rb, line 172
def self.parse(code, pairs = Pairs)
  new(code, pairs).parse
end

Public Instance Methods

next_token() click to toggle source

Returns the next token found in the array and removes it.

@return [Token] The next token, which will be removed from the queue.

# File lib/pry-coolline/paren_match.rb, line 189
def next_token
  @tokens.shift
end
parse() click to toggle source

@return [AST::Root]

# File lib/pry-coolline/paren_match.rb, line 182
def parse
  AST::Root.new self
end

Private Instance Methods

match_at(string, regexp, pos) click to toggle source

@return [Matchdata, nil] Matchdata if the regexp matches the string at

the specifed position, nil otherwise.
# File lib/pry-coolline/paren_match.rb, line 239
def match_at(string, regexp, pos)
  if m = string.match(regexp, pos) and m.begin(0) == pos
    m
  end
end
tokenize(code, pairs) click to toggle source

Generates token from a given chunk of code.

ANSI codes are ignored, as if they were comments.

@param (see ParenMatch#pair_at) @return [Array<Token>]

# File lib/pry-coolline/paren_match.rb, line 201
def tokenize(code, pairs)
  openers = Regexp.union(pairs.keys)
  closers = Regexp.union(pairs.values)

  token = Regexp.union(openers, closers, AnsiCode)

  tokens = []

  char_pos = pos = 0

  until pos == code.size
    old_pos = pos

    if m = match_at(code, AnsiCode, pos)
      pos = m.end(0)
    elsif m = match_at(code, openers, pos)
      tokens << OpenToken.new(m.to_s, char_pos, pos)
      pos = m.end(0)
      char_pos += pos - old_pos
    elsif m = match_at(code, closers, pos)
      tokens << CloseToken.new(m.to_s, char_pos, pos)
      pos = m.end(0)
      char_pos += pos - old_pos
    elsif m = code.match(token, pos)
      tokens << StrToken.new(code[pos...m.begin(0)], char_pos, pos)
      pos = m.begin(0)
      char_pos += pos - old_pos
    else
      tokens << StrToken.new(code[pos..-1], char_pos, pos)
      pos = code.size
    end
  end

  tokens
end