Compile-time madness: Compile-time compiler!
Gregor Richards
Richards at codu.org
Tue Feb 20 22:10:58 PST 2007
This is a compile-time compiler for Brainfuck, the infinitely perfect
esoteric programming language ( http://www.esolangs.org/wiki/Brainfuck )
------------------------------------------------------------
ctbf.d:
------------------------------------------------------------
module ctbf;
import std.cstream;
import std.stdio;
static char[] ctbf(char[] bf)
{
char[] code = `
byte[] mem;
uint memptr = 0;
mem.length = 1;
void expand() {
if (mem.length <= memptr) {
mem.length = memptr + 1;
}
}
`;
foreach (c; bf) {
switch (c) {
case '>':
code ~= "memptr++; expand();\n";
break;
case '<':
code ~= "memptr--;\n";
break;
case '+':
code ~= "mem[memptr]++;\n";
break;
case '-':
code ~= "mem[memptr]--;\n";
break;
case '[':
code ~= "while (mem[memptr]) {\n";
break;
case ']':
code ~= "}\n";
break;
case '.':
code ~= "dout.write(cast(char) mem[memptr]);\n";
break;
case ',':
code ~= "din.read(mem[memptr]);\n";
break;
default:
}
}
return code;
}
int main()
{
mixin(ctbf(import("helloworld.bf")));
return 0;
}
------------------------------------------------------------
------------------------------------------------------------
helloworld.bf:
------------------------------------------------------------
>+++++++++[<++++++++>-]<.>+++++++[<++++>-]<+.+++++++..+++.>>>++++++++[<++++>-]
<.>>>++++++++++[<+++++++++>-]<---.<<<<.+++.------.--------.>>+.
------------------------------------------------------------
- Gregor Richards
More information about the Digitalmars-d
mailing list