class Practice::Implementation::Interpreter
Brainfuck
interpreter written in Ruby.
Constants
- Command
The
Brainfuck
command.
Public Class Methods
new(source)
click to toggle source
Initialize.
# File lib/ruby/practice/implementation/interpreter.rb, line 80 def initialize(source) syms = Interpreter.symbols tokens = source.each_char.map { |c| c }.select { |c| syms.include?(c) } @commands = tokens.map { |c| Interpreter.command(c) } @bracemap = parse(@commands) end
Private Class Methods
command(c)
click to toggle source
# File lib/ruby/practice/implementation/interpreter.rb, line 124 def command(c) @symbols[c] end
symbols()
click to toggle source
Get brainfuck symbols
# File lib/ruby/practice/implementation/interpreter.rb, line 120 def symbols @symbols.keys end
Public Instance Methods
evaluate(cxt)
click to toggle source
To evaluate the source code.
# File lib/ruby/practice/implementation/interpreter.rb, line 88 def evaluate(cxt) while cxt.counter < @commands.length command = @commands[cxt.counter] command.process(cxt, @bracemap) cxt.counter += 1 end end
Private Instance Methods
parse(commands)
click to toggle source
Parse to brainfuck code.
# File lib/ruby/practice/implementation/interpreter.rb, line 99 def parse(commands) bracestack, bracemap = [], {} commands.each_with_index do |command, index| if command.symbol == '[' bracestack << index elsif command.symbol == ']' message = "syntax error, unexpected ']'" raise ArgumentError.new message if bracestack.empty? bracepos = bracestack.pop bracemap[bracepos] = index bracemap[index] = bracepos end end message = "syntax error, unexpected '['" raise ArgumentError.new message unless bracestack.empty? bracemap end