Skip to content

Instantly share code, notes, and snippets.

@kuwa72
Created January 19, 2017 15:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kuwa72/5f48d94b05c0e850922d305b44e7235a to your computer and use it in GitHub Desktop.
Save kuwa72/5f48d94b05c0e850922d305b44e7235a to your computer and use it in GitHub Desktop.
One line brainfuck compiler
{grep -o . | (echo '{ ptr=1;memory=() ';awk '/\[/{print "while [[ memory[$ptr] -ne 0 ]];do"} /\]/{print "done;"}/\+/{print "let $((memory[$ptr]++));"} /-/{print "let $((memory[$ptr]--));"} />/{print "let $((ptr++));"} /</{print "let $((ptr--));"} /\./{print "printf \"\\x$(printf %x $((memory[$ptr])))\";"} /,/{print "memory[$ptr]=$(head -c 1);"}';echo '}') | sh}
@kuwa72
Copy link
Author

kuwa72 commented Jan 20, 2017

It is part of a Hello World program(print "H")

>+++++++++[<++++++++>-]<.

It is compile result. My program compile brainfuck to shell script.

{ ptr=1;memory=()
let $((ptr++));
let $((memory[$ptr]++));
let $((memory[$ptr]++));
let $((memory[$ptr]++));
let $((memory[$ptr]++));
let $((memory[$ptr]++));
let $((memory[$ptr]++));
let $((memory[$ptr]++));
let $((memory[$ptr]++));
let $((memory[$ptr]++));
while [[ memory[$ptr] -ne 0 ]];do
let $((ptr--));
let $((memory[$ptr]++));
let $((memory[$ptr]++));
let $((memory[$ptr]++));
let $((memory[$ptr]++));
let $((memory[$ptr]++));
let $((memory[$ptr]++));
let $((memory[$ptr]++));
let $((memory[$ptr]++));
let $((ptr++));
let $((memory[$ptr]--));
done;
let $((ptr--));
printf "\x$(printf %x $((memory[$ptr])))";
}

Bash eval compile result and output "H".

$  echo \>+++++++++\[\<++++++++\>-\]\<\. | bf.sh
H

Base concept @kinaba's brainfuck page.

@kuwa72
Copy link
Author

kuwa72 commented Jan 23, 2017

@kuwa72
Copy link
Author

kuwa72 commented Nov 7, 2017

optimizer for @kou029w implementation.

(s='s/]/done:\[/while]));do:[+-]/]&&)):>/((p++)):</((p--)):\./printf 0x%x $]))|xxd -r:]/((m[p]:^.$//';gfold -b1|gsed "${s//://;s/}"| uniq -c | awk '/++|--/{print gensub(/(p|m\[p\])([-+])+/, "\\1=\\1\\2"$1, 1, $2);next}{sub($1, "")}1')

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment