Class: Braingasm::Parser

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

Overview

Takes some input code and generates the program

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(input, compiler) ⇒ Parser

Returns a new instance of Parser.



10
11
12
13
14
# File 'lib/braingasm/parser.rb', line 10

def initialize(input, compiler)
  @input = input
  @compiler = compiler
  @program = []
end

Instance Attribute Details

#inputObject

Returns the value of attribute input.



8
9
10
# File 'lib/braingasm/parser.rb', line 8

def input
  @input
end

#programObject

Returns the value of attribute program.



8
9
10
# File 'lib/braingasm/parser.rb', line 8

def program
  @program
end

Instance Method Details

#parse_next(tokens) ⇒ Object



25
26
27
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/braingasm/parser.rb', line 25

def parse_next(tokens)
  token = tokens.next

  case token
  when :right
    @compiler.right
  when :left
    @compiler.left
  when :increment
    @compiler.inc
  when :decrement
    @compiler.dec
  when :multiply
    @compiler.multiply
  when :divide
    @compiler.divide
  when :print
    @compiler.print
  when :output
    @compiler.print_int
  when :read
    @compiler.read
  when :input
    @compiler.read_int
  when :compare
    @compiler.compare
  when :quit
    @compiler.quit
  when :tape_limit
    @compiler.tape_limit
  when :loop_start
    @compiler.loop_start(@program.size)
  when :loop_end
    @compiler.loop_end(@program.size)
  else
    case token
    when Integer, String
      @compiler.push_prefix token
    when :position
      @compiler.pos
    when :random
      @compiler.random
    when :zero
      @compiler.zero
    when :signed
      @compiler.signed
    when :parity
      @compiler.parity
    when :oddity
      @compiler.oddity
    end
    false
  end
rescue BraingasmError => e
  raise_parsing_error(e.message)
end

#parse_programObject



16
17
18
19
20
21
22
23
# File 'lib/braingasm/parser.rb', line 16

def parse_program
  loop do
    push_instruction parse_next(@input)
  end

  raise_parsing_error("Unmatched `[`") unless @compiler.loop_stack.empty?
  @program
end

#push_instruction(instruction) ⇒ Object



82
83
84
85
86
# File 'lib/braingasm/parser.rb', line 82

def push_instruction(instruction)
  return unless instruction
  @program.push(*instruction)
  @program.size - 1
end

#raise_parsing_error(message) ⇒ Object

Raises:



88
89
90
# File 'lib/braingasm/parser.rb', line 88

def raise_parsing_error(message)
  raise ParsingError.new(@input.line_numer, @input.column_number), message
end