Class: Aspen::AbstractParser

Inherits:
Object
  • Object
show all
Defined in:
lib/aspen/abstract_parser.rb

Direct Known Subclasses

CustomGrammar::Parser, Parser

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(tokens, env = {}) ⇒ AbstractParser

Returns a new instance of AbstractParser.



16
17
18
19
20
21
# File 'lib/aspen/abstract_parser.rb', line 16

def initialize(tokens, env={})
  @tokens = tokens
  # Nothing is done with environment in the parser.
  # Calling #next will start at 0
  @position = 0
end

Instance Attribute Details

#positionObject (readonly)

Returns the value of attribute position.



14
15
16
# File 'lib/aspen/abstract_parser.rb', line 14

def position
  @position
end

#tokensObject (readonly)

Returns the value of attribute tokens.



14
15
16
# File 'lib/aspen/abstract_parser.rb', line 14

def tokens
  @tokens
end

Class Method Details

.parse(tokens, env = {}) ⇒ Object



4
5
6
# File 'lib/aspen/abstract_parser.rb', line 4

def self.parse(tokens, env={})
  new(tokens).parse
end

.parse_code(code, env = {}, lexer = Aspen::Lexer) ⇒ Object

Convenience method



9
10
11
12
# File 'lib/aspen/abstract_parser.rb', line 9

def self.parse_code(code, env={}, lexer=Aspen::Lexer)
  tokens = lexer.tokenize(code, env)
  parse(tokens, env)
end

Instance Method Details

#expect(*expected_tokens) ⇒ Object



23
24
25
26
27
28
29
30
# File 'lib/aspen/abstract_parser.rb', line 23

def expect(*expected_tokens)
  upcoming = tokens[position, expected_tokens.size]

  if upcoming.map(&:first) == expected_tokens
    advance_by expected_tokens.size
    upcoming
  end
end

#firstObject



39
40
41
# File 'lib/aspen/abstract_parser.rb', line 39

def first
  tokens.first
end

#lastObject



43
44
45
# File 'lib/aspen/abstract_parser.rb', line 43

def last
  tokens.last
end

#need(*required_tokens) ⇒ Object



32
33
34
35
36
37
# File 'lib/aspen/abstract_parser.rb', line 32

def need(*required_tokens)
  upcoming = tokens[position, required_tokens.size]
  expect(*required_tokens) or raise Aspen::ParseError, <<~ERROR
    Unexpected tokens. Expected #{required_tokens.inspect} but got #{upcoming.inspect}
  ERROR
end

#next_tokenObject



47
48
49
50
51
# File 'lib/aspen/abstract_parser.rb', line 47

def next_token
  t = tokens[position]
  advance
  return t
end

#peek(offset = 0) ⇒ Object



53
54
55
56
57
58
59
# File 'lib/aspen/abstract_parser.rb', line 53

def peek(offset = 0)
  if offset > 0
    tokens[position + 1..position + offset]
  else
    tokens[position]
  end
end