[antlr-interest] Can I target C and Java from one grammar file?
Jim Idle
jimi at temporal-wave.com
Thu Jan 22 10:00:49 PST 2009
Andy Grove wrote:
> Hi,
>
> I need to generate C and Java from an ANTLR grammar containing
> actions. Is there a preprocessor approach I can use rather than
> maintaining two versions of the grammar?
>
I use perforce and maintain a base grammar that has no actions, then
change only the grammar base. When ready to test I integrate the changes
via a prestored branch spec. Other SCCS can do the same sort of thing,
though perforce is streets ahead of anything else at the merge process.
However, occasionally it is a pain to debug remotely when I want to just
use the ANTLR works debugger before integrating a change, so I have
written a pre-processor as an experiment (it is in ANTLR3 of course),
and am trying to decide between the C# lexer base approach and the VB/C
approach (albeit not having the stupidity of the VB pre-processor.)
I was then going to propose it to Ter as an addon for the next release
(as it is non invasive if you don't use any pre-processing instructions.
Then you can have:
options
{
#if TARGET="C"
language = C;
#else
language = Java;
#endif
}
Or perhaps
language = TARGET_LANG;
and, referencing a prior thread:
#ifdef ANTLR_VER_MAJOR > 3 || ANTLR_VER_MINOR < 2
#abort "This grammar requires ANTLR 3.1.2 and above"
#endif
If I am willing to do the C macro thing. In general though, if you add
macros, people start embedding code in them and the whole thing is
macros, so I prefer the minimalist approach of C#.
As far as code generation goes, and maybe this would solve
preprocessing, I think it would be good to be able to supply a string
template for action code generation (rather than for the parser to use
at runtime). So you would have:
language = template;
r1 : %r1predicate(x)%?=> a=INT bINT c=INT
For now though, m4 is your best bet (it is in the Java compiler even),
or perhaps something simple with gawk.
Jim
> I'm thinking that the grammar would look something like this:
>
> selectStatement[int initRule]
> //IFDEF JAVA
> @init {if(initRule) sse.pushCall(sse.SELECTSTAT);}
> //ELIFDEF CPP
> @init {if(initRule) sse->pushCall(sse.SELECTSTAT);}
> //END
> :
> q = queryExpression[true]
> ;
>
> Are there tools out there already or do I need to roll my own?
>
> Thanks,
>
> Andy Grove
> Chief Architect
> CodeFutures Corporation
>
>
>
>
>
>
>
>
>
> List: http://www.antlr.org/mailman/listinfo/antlr-interest
> Unsubscribe: http://www.antlr.org/mailman/options/antlr-interest/your-email-address
>
More information about the antlr-interest
mailing list