[antlr-interest] StringTemplate 2.3 regions and ANTLR v3 code gen
Terence Parr
parrt at cs.usfca.edu
Fri Nov 11 10:27:02 PST 2005
Ok, another just amazing ST moment. Imagine the following template
that was previously used to generate validation code for a predicate:
/** Every predicate is used as a validating predicate (even when it is
* also hoisted into a prediction expression).
*/
validateSemanticPredicate(pred) ::= <<
if ( !(<if(debug)>evalPredicate(<pred>,"<pred>")<else><pred><endif>) ) {
throw new FailedPredicateException(input, "<ruleName>", "<pred>");
}
>>
So when I see
a : {p}? A ;
I want to generate
if ( !(p) ) {
throw new ...
}
and
if ( !(evalPredicate(p,"p")) ) {
throw new ...
}
when debugging.
The template is not only hard to read, but you have the debug stuff
mingled with regular code; bad separation of concerns. What you
really want is the normal template to have code that might need
replacing marked as a region via <@eval>...<@end>:
group Java;
...
/** Every predicate is used as a validating predicate (even when it is
* also hoisted into a prediction expression).
*/
validateSemanticPredicate(pred) ::= <<
if ( !(<@eval><pred><@end>) ) {
throw new FailedPredicateException(input, "<ruleName>", "<pred>");
}
>>
Then, in a subgroup, you can override/specify the code needed to do
the actual eval:
group Dbg;
...
/** Force predicate validation to trigger an event */
@validateSemanticPredicate.eval() ::= <<evalPredicate(<pred>,"<pred>")>>
This avoids the need to override the *entire*
validateSemanticPredicate template, thus, duplicating the generation
code (introducing the usual maintenance nightmare). You override a
"snippet" or _region_. :)
Hooray!
Coming soon to a theatre near you. :)
Ter
PS Thanks again to Ric Klaren for helping invent this!
More information about the antlr-interest
mailing list