Jeff Hui

Compiling (pt 4) - Generating Code

What use is an AST without using it? As a test, I took my favorite network protocol and pasted the basic rules from the spec into a file and normalized its specification as a custom grammar:


Then attempted to generate the code parse it. Go isn’t particularly good at large switch statements and string generation (to use the switch statement). The easiest is to transform the AST into a form that a template finds useful, and then use text/template:


It's just a poor implementation of LISP. It would be better if there was a generalized way of traversing the tree. There’s been a handful of attempts of universal abstract syntax trees (UASTs), but they usually are in conflict with performance. It might be worth the trade off to build some generic algorithms (type checking is what first comes to mind). But that requires more thinking.

Also, happy holidays! 😄