I am trying to implement a translator using ANTLR+StringTemplate. I have a starting language that is java like and multiple destination language.
I used the example: http://www.antlr.org/wiki/display/ST/Language+Translation+Using+ANTLR+and+StringTemplate
One of my destination language needs all variables to be declared globally. I wrote a grammar that recognizes variables, but i cannot find e way in my template for making a local variable to be declared globally.
Of course if I would have just one translation I would be able to do it, but I have multiple translation and some of them have local and global variables. I'd like to make it in the specific template file.
For example it would be great if I could define some sort of variables inside the template for keeping a list of all variable declarations and use it at the end when i define the global scope... but i don't know if this is possibile.
The parser will have to track the variables before passing them to a template. This doesn't mean that you need one parser for a global-based target and another for the other targets, it just means that you need to define some empty templates in the targets.
Here is a very simple example of how this can be done. I don't propose that your case is this ideal, but I hope it gives you enough to work with.
Assume that your source grammar, the Java-like one, accepts code like this:
Class
Foobar
contains member fieldsa
andb
, and member methodmyMethod
contains localsc
andd
. For argument's sake, assume that you wanta
,b
,c
, andd
to be treated as global variables for a global target, and like normal variables otherwise.Here is a grammar that accepts the input defined above, prepped for template output:
Note that parser member
globals
tracks the names of variables that a globals-only target is concerned about, but that templates pertaining to fields/variables are still called. This ensures that the grammar is target-neutral.Here is a template that produces Java code. Note that
compilationUnit
ignores inputglobals
because Java doesn't use them.Here is a template for a globals target. Note that many of the class templates are empty, but that
compilationUnit
processes inputglobals
.Here is the launcher class I'll use to test the grammar and templates.
Here is the input hard-coded in the test class:
And here is the output produced by the code, using both templates:
The key is to track globals in the parser regardless of the target language and pass them along with non-global information to the language's template regardless. The target language's template file either processes the globals or it ignores them. A template receive enough information to define both types of languages (whether it uses it all or not), so there's no need to create a new parser.