Tuesday, February 5, 2008

silliest compiler in the world

Today, I wanted to try to write a compiler in D and this is what came out:

import std.stdio;

char[] filename = "test.com";
ubyte[] source;

void main()
{
 source ~= [0xB4, 0x02];//mov ah,02 ;set parameter stdout
 source ~= [0xB2, 0x61];//mov dl,'a';set parameter 'a'
 source ~= [0xCD, 0x21];//int 21    ;print 'a' to stdout
 source ~= [0xCD, 0x20];//int 20    ;exit program

 FILE* handle = fopen(cast(char*) filename, cast(char*) "wb");
 fwrite(cast(void*) source, ubyte.sizeof, source.length, handle);
 fclose(handle);
}

This program compile a puny 8 byte DOS executable that displays an "a" on the console screen. It's not very exciting and has no frontend, but for anyone interested in writing compilers, it's easy to see the next steps (namely writing a file reader and a parser to generate the source byte array from a more programmer-friendly asm source file).

No comments:

Post a Comment