72 lines
1.9 KiB
Plaintext
72 lines
1.9 KiB
Plaintext
program brainfuck;
|
|
if command_line(1) = om then
|
|
print("error: no program file given");
|
|
stop;
|
|
end if;
|
|
|
|
if (f := open(command_line(1), "r")) = om then
|
|
print("error: cannot open file");
|
|
stop;
|
|
end if;
|
|
|
|
[pgm, loopmap] := read_program(f);
|
|
close(f);
|
|
|
|
mem_left := [];
|
|
mem_right := [];
|
|
mem_cur := 0;
|
|
pc := 1;
|
|
loop while pc <= #pgm do
|
|
case pgm(pc) of
|
|
("+"): mem_cur +:= 1;
|
|
mem_cur mod:= 256;
|
|
("-"): mem_cur -:= 1;
|
|
mem_cur mod:= 256;
|
|
(">"): mem_left with:= mem_cur;
|
|
mem_cur frome mem_right;
|
|
mem_cur ?:= 0;
|
|
("<"): mem_right with:= mem_cur;
|
|
mem_cur frome mem_left;
|
|
mem_cur ?:= 0;
|
|
("."): putchar(char mem_cur);
|
|
(","): mem_cur := ichar (getchar ? '\x00');
|
|
("["): if mem_cur = 0 then pc := loopmap(pc); end if;
|
|
("]"): if mem_cur /= 0 then pc := loopmap(pc); end if;
|
|
end case;
|
|
pc +:= 1;
|
|
end loop;
|
|
|
|
proc read_program(f);
|
|
pgm := [];
|
|
loop doing ch := getc(f); while ch /= om do
|
|
if ch in "+-<>.,[]" then
|
|
pgm with:= ch;
|
|
end if;
|
|
end loop;
|
|
|
|
stack := [];
|
|
loopmap := {};
|
|
loop for i in [1..#pgm] do
|
|
case pgm(i) of
|
|
("["):
|
|
stack with:= i;
|
|
("]"):
|
|
j frome stack;
|
|
if j=om then
|
|
print("mismatched brackets");
|
|
stop;
|
|
end if;
|
|
loopmap(i) := j;
|
|
loopmap(j) := i;
|
|
end case;
|
|
end loop;
|
|
|
|
if stack /= [] then
|
|
print("mismatched brackets");
|
|
stop;
|
|
end if;
|
|
|
|
return [pgm, loopmap];
|
|
end proc;
|
|
end program;
|