C compiler written in Python

Tim Freeman tfreeman at cs.uchicago.edu
Thu Jun 3 06:32:07 CEST 2004

Doing an independent study with Dave Beazley this quarter, Atul Varma
has written a C compiler on his own in Python.  It generates annotated
x86 assembly code from arbitrary C files.

Quoting Atul's website:

    * The different stages of compilation are encapsulated in visitor
classes, which (in my opinion) makes the code quite readable, and also
made writing the compiler a lot easier. The yacc rules merely generate
the abstract syntax tree and visitors do the rest.

    * The code generator is also a visitor, which makes the process very
modular; for instance, although this compiler doesn't generate
intermediate code (which is what most compilers that compile for
different architectures use), one could simply write, say, a SPARC code
generation visitor and run the AST through it to generate assembly for
that architecture. This separation also means that the rest of the
compiler is independent of machine architecture.

    * Writing the compiler in Python allowed me to focus entirely on the
task at hand (compilation), without being distracted by issues of memory
management and low-level data structure creation. Using such a
high-level language also made reading and refactoring the code a lot

Have a look:

And this is the annotated assembly output:

More information about the Python-list mailing list