Class: BfInterpreter
- Inherits:
-
Object
show all
- Defined in:
- lib/yarbf.rb
Defined Under Namespace
Classes: BfCell, BfProgramUnit
Instance Method Summary
collapse
Constructor Details
#initialize(debug = false, wrap_around = true, cell_size = 8) ⇒ BfInterpreter
Returns a new instance of BfInterpreter.
10
11
12
13
14
15
|
# File 'lib/yarbf.rb', line 10
def initialize(debug = false, wrap_around = true, cell_size = 8)
@option = Hash.new
@option[KEY_DEBUG] = debug
@option[KEY_WRAP] = wrap_around
@option[KEY_CELL] = cell_size
end
|
Instance Method Details
#cell_size=(cell_size) ⇒ Object
37
38
39
|
# File 'lib/yarbf.rb', line 37
def cell_size=(cell_size)
@option[KEY_CELL] = cell_size
end
|
#cell_size? ⇒ Boolean
33
34
35
|
# File 'lib/yarbf.rb', line 33
def cell_size?
@option[KEY_CELL]
end
|
#debug=(debug) ⇒ Object
21
22
23
|
# File 'lib/yarbf.rb', line 21
def debug=(debug)
@option[KEY_DEBUG] = debug
end
|
#debug? ⇒ Boolean
17
18
19
|
# File 'lib/yarbf.rb', line 17
def debug?
@option[KEY_DEBUG]
end
|
#run(src) ⇒ Object
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
81
82
83
84
85
86
|
# File 'lib/yarbf.rb', line 41
def run(src)
units = []
File.open(src) do |file|
units = construct_program_units(file)
end
match_brackets(units)
tape = Array.new
position = 0
unit = units[0]
while unit != nil
tape[position] = BfCell.new(position) if tape[position] == nil
STDERR.printf('%s', unit.instruction) if debug?
case unit.instruction
when '+' then tape[position].increase(1, wrap_around?)
when '-' then tape[position].decrease(1, wrap_around?)
when '<' then
position -= 1
fail 'Cell position out of bound!' if position < 0
when '>' then position += 1
when ',' then
tape[position].value = STDIN.getch.ord
when '.' then STDOUT.putc tape[position].value
when '[' then
if tape[position].value == 0
unit = unit.match
next
end
when ']' then
if tape[position].value != 0
unit = unit.match
next
end
else fail "Illegal instruction '#{unit.instruction}'!"
end
unit = unit.next
end
end
|
#wrap_around=(wrap_around) ⇒ Object
29
30
31
|
# File 'lib/yarbf.rb', line 29
def wrap_around=(wrap_around)
@option[KEY_WRAP] = wrap_around
end
|
#wrap_around? ⇒ Boolean
25
26
27
|
# File 'lib/yarbf.rb', line 25
def wrap_around?
@option[KEY_WRAP]
end
|