Wednesday, December 02, 2009

Naive Brainf**k to Java compiler

Some time ago the brainf**k language caught my eye (I still don't feel comfortable spelling it right).

It's a turing tarpit, but one not very complicated at that (for something more esoteric see Malbolge or Whitespace).

The language is very simple, it has eight instructions. So I had to write a compiler for it. It turns out to be quite easy to do:

import static java.lang.System.out;

public class BrainFk
{
 public static void main(String[] args) {
 out.println("public class " + args[0] + "{");
 out.println("public static void main(String args[]) throws Throwable {");
 out.println("int[] memory = new int[30000];");
 out.println("int data = 0;");
 final String code = args[1];
 for(int i = 0; i < code.length(); i++) {
  char c = code.charAt(i);
  switch(c) {
   case '>':
    out.println("++data;");
    break;
   case '<':
    out.println("--data;");
    break;
   case '+':
    out.println("++memory[data];");
    break;
   case '-':
    out.println("--memory[data];");
    break;
   case '.':
    out.println("System.out.print((char)(0xFF & memory[data]));");
    break;
   case ',':
    out.println("memory[data] = System.in.read();");
    break;
   case '[':
    out.println("while(memory[data] != 0) {");
    break;
   case ']':
    out.println("}");
    break;
   }
  }
  out.println("}}");
 }
}

You can use it to compile the hello world sample from the Wikipedia page:
~>java BrainFk Hello "++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>." > Hello.java
~>javac Hello.java
~>java Hello
Hello World!

Sometime I'll have to post the Forth interpreter in Java I wrote (I know some might consider sacrilege to use both languages in the same sentence, but you can't please everyone!).