Last active
July 8, 2018 15:10
-
-
Save Demonstrandum/287761159705162c8b3dc731fad0fa9a to your computer and use it in GitHub Desktop.
Fully functioning Brainf*ck interpreter in Ruby
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
$DEBUG = false | |
EOF = "\0" | |
String.class_eval { define_method(:arg?) { ARGV.include? self } } | |
ALLOC = '--alloc'.arg? ? ARGV[(ARGV.index '--alloc') + 1].to_i : 100 | |
PROGRAM = (File.read ARGV.select { |arg| File.file? arg }.first) + EOF | |
module BrainFrog | |
MEMORY = Array.new ALLOC, 0 | |
@pointer = 0 | |
def self.run | |
i = 0 | |
until PROGRAM[i] == EOF | |
if PROGRAM[i] == '[' | |
i = loop i | |
else | |
execute PROGRAM[i] | |
end | |
i += 1 | |
end | |
end | |
private def self.loop index | |
i = index + 1 | |
loop_end = nil | |
until MEMORY[@pointer].zero? | |
until PROGRAM[i] == ']' | |
if PROGRAM[i] == '[' | |
i = loop i | |
else | |
execute PROGRAM[i] | |
end | |
i += 1 | |
end | |
loop_end = i | |
i = index + 1 | |
end | |
if loop_end.nil? # Find end of loop if we don't run it. | |
until PROGRAM[i] == ']' | |
if PROGRAM[i] == '[' | |
i = loop i | |
end | |
i += 1 | |
end | |
loop_end = i | |
end | |
return loop_end | |
end | |
def self.execute index | |
case PROGRAM[index] | |
when '>'; @pointer += 1 | |
when '<'; @pointer -= 1 | |
when '+'; MEMORY[@pointer] += 1 | |
when '-'; MEMORY[@pointer] -= 1 | |
when '.'; | |
if $DEBUG | |
puts "\nCHR: #{MEMORY[@pointer].chr.inspect} | ORD: #{MEMORY[@pointer]}" | |
else | |
print MEMORY[@pointer].chr | |
end | |
when ','; MEMORY[@pointer] = gets[0].ord | |
else; return | |
end | |
debug index | |
end | |
def self.debug i | |
puts "'#{PROGRAM[i]}' => #{MEMORY} :: *POINTER = #{MEMORY[@pointer]}" if $DEBUG | |
end | |
end | |
BrainFrog.run |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment