Skip to content

Instantly share code, notes, and snippets.

@DuoSRX
Created July 6, 2011 16:05
Show Gist options
  • Save DuoSRX/1067618 to your computer and use it in GitHub Desktop.
Save DuoSRX/1067618 to your computer and use it in GitHub Desktop.
# A very simple Brainfuck interpreter
class BFParser
attr_accessor :memory, :loop_out, :loop_in, :code_size, :code
def initialize(code, stack_size = 10000)
@memory = [0] * stack_size
@code = code.split(//)
@code_size = code.length
@loop_in = []
@loop_out = []
end
def run
parse_loops(code)
cp = -1 #code pointer
mp = 0 #memory pointer
while cp < code_size do
cp += 1
case code[cp]
when '>' then mp += 1
when '<' then mp -= 1
when '+' then memory[mp] += 1
when '-' then memory[mp] -= 1
when '.' then $stdout.putc memory[mp]
when ',' then memory[mp] = $stdin.getc
when '[' then cp = loop_out[cp] if memory[mp] <= 0
when ']' then cp = loop_in[cp] - 1
end
end
end
# Simply pre parse the loops in the code
# loop
def parse_loops(code)
tmp = []
code.each_with_index do |op, n|
if op == '['
tmp << n
elsif op == ']'
loop_in[n] = tmp.pop
loop_out[loop_in[n]] = n
end
end
end
end
#code = ARGF.read
#hello world
code = "++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>."
parser = BFParser.new(code)
parser.run
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment