Saturday, December 12, 2015

Adding Actions To Your ANTLR Grammar

We established last time that getting antlr to generate code is a huge pain. Even worse, is the fact that it's hard to find good examples of the antlr workflow, i.e. generating code with actions, adding arguments, and etc. Thankfully, in my quest to build a CSS parser in C++, I've managed to track down two invaluable Stack Overflow posts that proved invaluable.
The first is a simple ANTLR3 example. I found this to be a very helpful workflow example for antlr3. While it's aimed towards a Java target, it should be very simple to translate the code actions to any other language. While working on this example I also highly recommend learning what ANTLRWorks has to offer, especially the syntax diagrams and built-in interpreter. These tools should help you better understand your grammar, including what it can handle and what it can't. It's also not a bad idea to follow along in a debugger when running the parsing routine to get a hold of how the grammar actions behave. If you find any tweaks that need to be made, just remember to apply them to the grammar, or they will be wiped away if you ever generate your parser again.

By the end of that example you should have built it all; a Exp parser and lexer from ANTLR3, and added target code to the grammar that works. At this point you should be ready to work with a larger and more sophisticated grammar. However, you may find using the limited rules in the Exp example that you can't accomplish everything you'd like with only returns. Thankfully this other post shows how to pass in arguments.

There are a couple of other things to consider as you fiddle with your grammar. Code actions must go under a rule. Also, don't expect ANTLRworks to know what the hell your code is supposed to. Its job is to understand your grammar. This is both a blessing and a curse. It's a blessing in that you don't really have to show ANTLR the classes and structs you're working with, but at the same time, you can sabotage yourself and write some funked up code-- but your IDE will let you know.


No comments:

Post a Comment