Created
December 28, 2014 14:44
-
-
Save st98/89f65244b72a79e511be to your computer and use it in GitHub Desktop.
CoffeeScript で Brainf*ck のインタプリタ。
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
class Brainfuck | |
_parse = (prog) -> | |
prog.match(/[-+><\.,\[\]]/g) | |
@run: (prog, input=prompt, output=console.log.bind(console)) -> | |
_memory = [] | |
_pointer = 0 | |
_pc = 0 | |
_depth = 0 | |
prog = _parse prog | |
while prog[_pc] | |
switch prog[_pc] | |
when '+' | |
if _memory[_pointer] | |
_memory[_pointer] = (_memory[_pointer] + 1) & 255 | |
else | |
_memory[_pointer] = 1 | |
when '-' | |
if _memory[_pointer] | |
_memory[_pointer]--; | |
else | |
_memory[_pointer] = 255 | |
when '>' then _pointer++ | |
when '<' then _pointer-- | |
when '[' | |
if !_memory[_pointer] | |
while prog[_pc] | |
if prog[_pc] == '[' | |
_depth++ | |
else if prog[_pc] == ']' | |
_depth-- | |
if !_depth | |
break | |
_pc++ | |
when ']' | |
if _memory[_pointer] | |
while prog[_pc] | |
if prog[_pc] == ']' | |
_depth++ | |
else if prog[_pc] == '[' | |
_depth-- | |
if !_depth | |
break | |
_pc-- | |
when ',' then _memory[_pointer] = input() | |
when '.' then output _memory[_pointer] | |
_pc++ | |
main = -> | |
input = -> | |
prompt(',').charCodeAt 0 | |
output = -> | |
str = [] | |
f = (c) -> | |
str.push c | |
f.out = (g = console.log.bind(console)) -> | |
g String.fromCharCode.apply(null, str) | |
return f | |
code = ''' | |
+++++++[>++++++++++<-]>++.< | |
+++[>++++++++++<-]>-. | |
+++++++.. | |
+++. | |
>+++[>++++++++++<-]>+++. | |
''' | |
o = output() | |
Brainfuck.run code, input, o | |
o.out() | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment