Class: Kaguya::Parser

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

Instance Method Summary collapse

Constructor Details

#initialize(input) ⇒ Parser

Returns a new instance of Parser.

Parameters:

  • input (IO)


6
7
8
# File 'lib/kaguya/parser.rb', line 6

def initialize(input)
  @input = input
end

Instance Method Details

#parseAST::Node

Returns:



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/kaguya/parser.rb', line 11

def parse
  root = AST::Node.new(type: :root, parent: nil)
  current_node = root
  context_level = 0

  @input.each_char do |ch|
    case ch
    when '>'
      AST::Node.new(type: :forward, parent: current_node)
    when '<'
      AST::Node.new(type: :backward, parent: current_node)
    when '+'
      AST::Node.new(type: :increment, parent: current_node)
    when '-'
      AST::Node.new(type: :decrement, parent: current_node)
    when '.'
      AST::Node.new(type: :output, parent: current_node)
    when ','
      AST::Node.new(type: :input, parent: current_node)
    when '['
      context_level += 1
      current_node = AST::Node.new(type: :while, parent: current_node)
    when ']'
      context_level -= 1
      current_node = current_node.parent
    when ' ', "\n", "\r"
      # read next charactor
    else
      raise "Invalid charactor `#{ch}`."
    end
  end

  if context_level != 0
    raise 'Invalid brace correspondence.'
  end

  root
end