Skip to content

Instantly share code, notes, and snippets.

@pi8027
Created July 13, 2010 19:48
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pi8027/474397 to your computer and use it in GitHub Desktop.
Save pi8027/474397 to your computer and use it in GitHub Desktop.
%!PS-Adobe-3.0
% Brainfuck Implementation in PostScript
% Author : Kazuhiko Sakaguchi (pi8027)
% Date : 2010-07-14
/initArray {
/size exch def
/arr size array def
0 1 size 1 sub {
arr exch 0 put
} for
arr
} def
/run {
/error exch def
/output exch def
/input exch def
/program exch def
/mem 4096 initArray def
1 0
{
/po exch def
/pc exch def
/instruction program pc get def
instruction 0 eq {
exit
} if
instruction (+) 0 get eq {
mem po mem po get 1 add 256 mod put
pc 1 add po
} if
instruction (-) 0 get eq {
mem po mem po get 255 add 256 mod put
pc 1 add po
} if
instruction (>) 0 get eq {
pc 1 add po 1 add
} if
instruction (<) 0 get eq {
pc 1 add po 1 sub
} if
instruction (.) 0 get eq {
output mem po get write
pc 1 add po
} if
instruction (,) 0 get eq {
mem po input read not { 0 } if put
pc 1 add po
} if
instruction ([) 0 get eq {
mem po get 0 eq {
pc 0
{
/instruction' program 3 index get def
instruction' ([) 0 get eq {
1 add
} if
instruction' (]) 0 get eq {
1 sub
} if
instruction' 0 eq {
pop pop false exit % error check
} if
dup 0 eq {
pop po true exit
} if
exch 1 add exch
} loop
not {
error (Error!) writestring exit
} if
}
{
pc 1 add po
} ifelse
} if
instruction (]) 0 get eq {
mem po get 0 ne {
pc 0
{
/instruction' program 3 index get def
instruction' ([) 0 get eq {
1 sub
} if
instruction' (]) 0 get eq {
1 add
} if
instruction' 0 eq {
pop pop false exit % error check
} if
dup 0 eq {
pop po true exit
} if
exch 1 sub exch
} loop
not {
error (Error!) writestring exit
} if
}
{
pc 1 add po
} ifelse
} if
% pointer check
} loop
} def
/element {
/elem exch def
/arr exch def
false
0 1 arr length 1 sub {
exch pop
arr exch get elem eq {
true
exit
} if
false
} for
} def
/readProgram {
/file exch (r) file def
64 string dup 1 0 put % buffer
1 % iterator
{
/iter exch def
iter 64 mod 0 eq {
/newbuf iter 64 add string def
newbuf 0 3 2 roll putinterval
newbuf
} if
/buf exch def
file read {
/ch exch def
(+-><.,[]) ch element {
buf iter ch put
iter 1 add
}
{
iter
} ifelse
buf exch
}
{
buf
exit
} ifelse
} loop
file closefile
} def
/stdin (%stdin) (r) file def
/stdout (%stdout) (w) file def
/stderr (%stderr) (w) file def
(input.bf) readProgram
stdin stdout stderr run
stdin closefile
stdout closefile
stderr closefile
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment