3

I am currently trying to write my own compiler, targeting the JVM.

I have completed the parsing step using Java classes generated by ANTLR, and have an AST of the source code to work from (An ANTLR "CommonTree", specifically). I am using ASM to simplify the generating of the bytecode.

Could anyone give a broad overview of how to convert this AST to bytecode?

My current strategy is to explore down the tree, generating different code depending on the current node (using "Tree.getType()").

The problem is that I can only recognise tokens from my lexer this way, rather than more complex patterns from the parser.

Is there something I am missing, or am I simply approaching this wrong?

3

This is simply too large a topic to cover in a Q/A forum. You need to buy / borrow and read a textbook on compiler writing that has good coverage of code generation.

The problem is that I can only recognise tokens from my lexer this way, rather than more complex patterns from the parser.

I don't understand this. Do you mean that you don't have a symbol table? If not, you'll need one. A good textbook will explain this concept and how to implement it.


If someone would care to suggest an up-to-date textbook, feel free. (I have a copy of the Dragon Book ... but it is pretty dated.)

  • Hmmm. I have done some further reading, and it seems one can use a "Tree Grammar" to generate bytecode. I presume this makes things more "automatic"? – Nick Mar 8 '12 at 2:27
2

I am doing something along the same lines. I recommend Pragmatic's ANTLR The Definitive Guide and also Pragmatic's Language Implementation Patterns both available at their website (with which I have zero connection) .. I would say that both these books taken together are better than the Dragon

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.