Compile-time madness: Compile-time compiler!

kris foo at bar.com
Tue Feb 20 23:20:18 PST 2007


Gregor Richards wrote:
> 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;
> }
> ------------------------------------------------------------


hehe ... nice one



More information about the Digitalmars-d mailing list