Created
June 11, 2024 15:12
-
-
Save betelgeuse-7/7c29cb6a4ef8804763dcd24bf83573dc to your computer and use it in GitHub Desktop.
Brainfuck interpreter in Io
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
// There is no support for ',' which reads a byte from stdin | |
interpreter := Object clone | |
List last := method(self at((self size) - 1)) | |
interpreter eval := method(prog, | |
ds := List clone preallocateToSize(30000) setSize(30000) map(0) | |
dp := 0 | |
is := list() | |
ip := -1 | |
while (ip < prog size - 1, | |
ip = ip + 1 | |
if (prog at(ip) asCharacter == ">") then ( | |
dp = dp + 1 | |
continue | |
) | |
if (prog at(ip) asCharacter == "<") then ( | |
dp = dp - 1 | |
continue | |
) | |
if (prog at(ip) asCharacter == "+") then ( | |
ds atPut(dp, ds at(dp) + 1) | |
continue | |
) | |
if (prog at(ip) asCharacter == "-") then ( | |
ds atPut(dp, ds at(dp) - 1) | |
continue | |
) | |
if (prog at(ip) asCharacter == ".") then ( | |
ds at(dp) asCharacter print | |
continue | |
) | |
if (prog at(ip) asCharacter == "[") then ( | |
stack := 1 | |
end := ip + 1 | |
while (stack != 0, | |
if (prog at(end) asCharacter == "[") then ( | |
stack = stack + 1 | |
) else (if (prog at(end) asCharacter == "]") then ( | |
stack = stack - 1 | |
)) | |
end = end + 1 | |
) | |
if (ds at(dp) == 0) then ( | |
ip = end - 1 | |
) else ( | |
is append(ip) | |
) | |
continue | |
) | |
if (prog at(ip) asCharacter == "]") then ( | |
if (ds at(dp) != 0) then ( | |
ip = is last | |
) else ( | |
is removeLast | |
) | |
continue | |
) | |
) | |
) | |
interpreter eval \ | |
(">++++++++[<+++++++++>-]<. | |
>++++[<+++++++>-]<+. | |
+++++++.. | |
+++. | |
>>++++++[<+++++++>-]<++. | |
------------. | |
>++++++[<+++++++++>-]<+. | |
<. | |
+++. | |
------. | |
--------. | |
>>>++++[<++++++++>-]<+. | |
>++++++++++. | |
.") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment