9/30/2012

A Simple Compiler - finding the resource first

Do you want to build a simple compiler?

I always wanted to build a simple compiler when I was in the university, though my major was not CS.  I have tried some simple projects since then, such as using C style programming to implement LISP AI projects.  So basically I had to implement most of the LISP basic functions in C, and modify the original LISP codes to more C-like function calls.  It's not that difficult to do so, just it took a while to figure out the correct memory management schemes.


The other project I have tried to do is using C# to implement Prolog-like logic programming.  There is a Japanese education site that gives most of the details about the implementation.  Its starting chapter is Prolog in Python, if you are not familiar with Prolog, you'd better start from there.


So what if you want to build a compiler or interpreter for a language like VB or C, or other object oriented programming languages.  Most of the textbooks are quite complicated, it talks a lot about the details of the theory of a compiler.  But if you just want to start from a simple one and DIY, basically you don't want to know too much about the details.


I found there is an easy start with a Jack compiler that is mentioned in the book, The Elements of Computer Systems, its mainly in chapter 9, 10, & 11.  An education site for the study plan is here.  Some people have implemented it using java or C#.


If you are interested in Open Source, you may take a look at this book, flex & bison.  So what is flex and what is bison?  These are two great tools to help you build your compiler.  Basically you only have to define the grammar of your language, and they can do the lexical analysis and do the parse for you.  So your work can be focused on the code generation part.


So a basic compiler can be done by 3 workers: tokenizer, parser, and code generator.

No comments :