Created
September 19, 2018 12:19
-
-
Save z-rui/aa4fb86cfb86d8813d91db3fa0d3d099 to your computer and use it in GitHub Desktop.
Brainf*** interpreter in AWK
This file contains hidden or 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
BEGIN { | |
FS = "" | |
AMOD = 65536 | |
VMOD = 256 | |
pc = 0 | |
for (ch = 0; ch < VMOD; ch++) | |
ORD[sprintf("%c", ch)] = ch | |
} | |
{ | |
for (i = 1; i <= NF; i++) { | |
if ($i == "+" || $i == "-") pair_op($i, "+", "-") | |
else if ($i == ">" || $i == "<") pair_op($i, ">", "<") | |
else if ($i == "," || $i == ".") { CODE[pc++] = $i } | |
else if ($i == "[") { stack[sp++] = pc; CODE[pc++] = $i } | |
else if ($i == "]") end_loop() | |
} | |
} | |
function pair_op(op, pos, neg) { | |
if (CODE[pc-1] != pos) | |
CODE[pc++] = pos | |
ARG[pc-1] += ($i == pos) ? 1 : -1 | |
} | |
function end_loop() { | |
if (sp == 0) { print "!Too many ]'s"; exit } | |
pc1 = stack[--sp] | |
ARG[pc] = ARG[pc1] = pc - pc1 | |
CODE[pc++] = $i | |
} | |
END { | |
if (sp != 0) { print "!Too many ['s"; exit } | |
PEND = pc | |
ptr = 0 | |
for (pc = 0; pc < PEND; pc++) { | |
op = CODE[pc] | |
if (op == "+") { DATA[ptr] = (DATA[ptr] + ARG[pc]) % VMOD } | |
else if (op == ">") { ptr = (ptr + ARG[pc]) % AMOD } | |
else if (op == "[") { if (DATA[ptr] == 0) pc += ARG[pc] } | |
else if (op == "]") { if (DATA[ptr] != 0) pc -= ARG[pc] } | |
else if (op == ",") { | |
if (length(linebuf) == 0) | |
if ((getline linebuf < "-") > 0) | |
linebuf = linebuf "\n" | |
DATA[ptr] = ORD[substr(linebuf, 1, 1)] | |
linebuf = substr(linebuf, 2) | |
} | |
else if (op == ".") { printf "%c", DATA[ptr] } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment