n2liquid's sandbox

First working version of the Chii compiler — “Chew”

Posted on: September 16, 2011

Have I ever said I love LLVM before? If I didn’t, now is the time. LLVM is pure sex.

Yesterday I made my first working compiler ever. It outputs LLVM assembly that either runs off the (JIT-enabled) LLVM interpreter or compiles to native assembly, which in turn can be assembled and linked by GCC, producing a native executable.

As of now, the compiler can understand just function declarations and definitions. Since LLVM (or is it GCC?) automatically configures linkage to libc, you can declare libc functions and use them in Chii. It doesn’t understand variables, though (just expressions). That means the only things that can appear on the function body are function calls to other functions and the return statement. Also, the compiler doesn’t know “void” yet, so you can’t declare functions that return void.

The following is a “Hello, world” program written in Chii that shows usage of libc:

fn sin(double) double;
fn cos(double) double;
fn printf(const(char *), ...) int;

fn main()
	printf("Hello, %s world!\n", "fantastic Chii");
	printf("The sine of the cosine of %f radians is %f.\n",
                2.0f, sin(cos(2.0f)));

	return 0;

You can download the source-code and dependency executables here.

The compiler is fully written in JavaScript (OMG!), and uses a Parsing Expression Grammar-based (chii_gramar.pegjs) parser generated by the awesome PEG.js library (chii_parser.js). The output then undergoes semantic analysis, which structures the source-code into Chii language’s Intermediate Representation object (chii_ast_transformer.js). This object is then sent to the compiler (chii_compiler.js), which spits LLVM assembly, and the rest you already know.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Cute bouncing pixels


Twitter (technical)

Error: Please make sure the Twitter account is public.

Twitter (personal)

Error: Twitter did not respond. Please wait a few minutes and refresh this page.

Get messaged when I post something new!
Just enter your e-mail and hit Follow:

Join 171 other followers

%d bloggers like this: