Class: ORB::Parser

Inherits:
Object
  • Object
show all
Defined in:
lib/orb/parser.rb

Overview

The ‘Parser` is responsible for converting a list of tokens produced by the `Lexer` into an Abstract Syntax Tree (AST). Any errors encountered during parsing are stored in `@errors` and can be accessed after parsing.

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(tokens, options = {}) ⇒ Parser

Create a new parser instance, use ‘Parser.parse` instead.



19
20
21
22
23
24
25
26
# File 'lib/orb/parser.rb', line 19

def initialize(tokens, options = {})
  @tokens = tokens
  @options = options
  @errors = []

  @root = ORB::AST::RootNode.new
  @nodes = [@root]
end

Instance Attribute Details

#errorsObject (readonly)

Returns the value of attribute errors.



10
11
12
# File 'lib/orb/parser.rb', line 10

def errors
  @errors
end

#tokensObject (readonly)

Returns the value of attribute tokens.



10
11
12
# File 'lib/orb/parser.rb', line 10

def tokens
  @tokens
end

Class Method Details

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



13
14
15
# File 'lib/orb/parser.rb', line 13

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

Instance Method Details

#parseObject Also known as: parse!

Parse the tokens into a tree of nodes. The ‘@current` index is used to keep track of the current token being parsed within the stream of tokens.

Raises:



30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/orb/parser.rb', line 30

def parse
  return @root if @tokens.empty?

  @current = 0
  next_token while @current < @tokens.length

  # If there are any nodes left in the stack, they are unmatched tokens
  raise ORB::ParserError, "Unmatched #{@nodes.last.class}" if @nodes.length > 1

  # Return the root node
  @root
end