Last active
August 29, 2015 14:18
-
-
Save fasterthanlime/a55aab509a13c3211dd1 to your computer and use it in GitHub Desktop.
Brainfuck interpreter in ooc
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
import structs/[ArrayList, HashMap, Stack] | |
import io/File | |
Tape: class { | |
tape := ArrayList<Int> new() | |
pos := 0 | |
init: func { | |
tape add(0) | |
} | |
get: func -> Int { tape[pos] } | |
inc: func { tape[pos] = tape[pos] + 1 } | |
dec: func { tape[pos] = tape[pos] - 1 } | |
advance: func { | |
pos += 1 | |
if (pos >= tape size) { | |
tape add(0) | |
} | |
} | |
devance: func { pos -= 1 } | |
} | |
Program: class { | |
code := ArrayList<Char> new() | |
bracketMap := HashMap<Int, Int> new() | |
init: func (text: String) { | |
leftstack := Stack<Int> new() | |
pc := 0 | |
valid := ['[', ']', '<', '>', '+', '-', ',', '.'] as ArrayList<Char> | |
for (chr in text) { | |
if (valid contains?(chr)) { | |
code add(chr) | |
match chr { | |
case '[' => | |
leftstack push(pc) | |
case ']' => | |
left := leftstack pop() | |
right := pc | |
bracketMap[left] = right | |
bracketMap[right] = left | |
} | |
pc += 1 | |
} | |
} | |
} | |
run: func { | |
pc := 0 | |
tape := Tape new() | |
while (pc < code size) { | |
chr := code[pc] | |
match chr { | |
case '+' => tape inc() | |
case '-' => tape dec() | |
case '>' => tape advance() | |
case '<' => tape devance() | |
case '[' => if (tape get() == 0) { pc = bracketMap[pc] } | |
case ']' => if (tape get() != 0) { pc = bracketMap[pc] } | |
case '.' => tape get() as Char print() | |
} | |
pc += 1 | |
} | |
} | |
} | |
main: func (args: ArrayList<String>) { | |
if (args size < 2) { | |
"usage: #{args[0]} FILE" println() | |
exit(1) | |
} | |
source := File new(args[1]) | |
code := source read() | |
Program new(code) run() | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment