Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

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?

share|improve this question
    
To emit java bytecode: stackoverflow.com/questions/4016305/… –  dead Jun 11 '12 at 19:25
add comment

2 Answers

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.)

share|improve this answer
    
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
add comment

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

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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