Class: Rux::Parser

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

Defined Under Namespace

Classes: TagMismatchError, UnexpectedTokenError

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(lexer) ⇒ Parser

Returns a new instance of Parser.



22
23
24
25
26
# File 'lib/rux/parser.rb', line 22

def initialize(lexer)
  @lexer = lexer
  @stack = []
  @current = get_next
end

Class Method Details

.parse(str) ⇒ Object



15
16
17
18
19
# File 'lib/rux/parser.rb', line 15

def parse(str)
  buffer = ::Parser::Source::Buffer.new('(source)', source: str)
  lexer = ::Rux::Lexer.new(buffer)
  new(lexer).parse
end

.parse_file(path) ⇒ Object



9
10
11
12
13
# File 'lib/rux/parser.rb', line 9

def parse_file(path)
  buffer = ::Parser::Source::Buffer.new(path).read
  lexer = ::Rux::Lexer.new(buffer)
  new(lexer).parse
end

Instance Method Details

#parseObject



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/rux/parser.rb', line 28

def parse
  curlies = 1
  children = []

  loop do
    type = type_of(current)
    break unless type

    case type
      when :tLCURLY, :tLBRACE, :tRUX_LITERAL_RUBY_CODE_START
        curlies += 1
      when :tRCURLY, :tRBRACE, :tRUX_LITERAL_RUBY_CODE_END
        curlies -= 1
    end

    break if curlies == 0

    if rb = ruby
      children << rb
    elsif type_of(current) == :tRUX_TAG_OPEN_START
      children << tag
    else
      raise UnexpectedTokenError,
        'expected ruby code or the start of a rux tag but found '\
          "#{type_of(current)} instead"
    end
  end

  AST::ListNode.new(children)
end