Class: TRuby::ParserCombinator::TokenMatcher

Inherits:
TokenParser
  • Object
show all
Defined in:
lib/t_ruby/parser_combinator/token/token_matcher.rb

Overview

Match a specific token type

Instance Method Summary collapse

Methods inherited from TokenParser

#<<, #>>, #label, #many, #many1, #map, #optional, #sep_by, #sep_by1, #|

Constructor Details

#initialize(token_type) ⇒ TokenMatcher

Returns a new instance of TokenMatcher.



7
8
9
# File 'lib/t_ruby/parser_combinator/token/token_matcher.rb', line 7

def initialize(token_type)
  @token_type = token_type
end

Instance Method Details

#parse(tokens, position = 0) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/t_ruby/parser_combinator/token/token_matcher.rb', line 11

def parse(tokens, position = 0)
  return TokenParseResult.failure("End of input", tokens, position) if position >= tokens.length

  token = tokens[position]
  return TokenParseResult.failure("End of input", tokens, position) if token.type == :eof

  if token.type == @token_type
    TokenParseResult.success(token, tokens, position + 1)
  else
    TokenParseResult.failure(
      "Expected :#{@token_type}, got :#{token.type} (#{token.value.inspect})",
      tokens,
      position
    )
  end
end