[antlr-interest] Using multiple grammars with a single parser

Kirby Bohling kirby.bohling at gmail.com
Tue Oct 20 07:31:29 PDT 2009


On Tue, Oct 20, 2009 at 8:36 AM, Parambir Singh <speiestaaim at gmail.com> wrote:
> Hi
> I am working on a project where I want to parse input in different locales
> (e.g. english, french & german dates). I don't want to create multiple
> parsers, since the semantics of the grammar don't change between locales. So
> probably I'll need multiple lexers and a single parser. Moreover, I want to
> specify a locale to the parser and the input should be matched against only
> that particular locale (e.g. german dates should be invalid in english
> locale).
> What would be the best approach to construct such a parser using ANTLR. I
> don't have much experience with ANTLR but I read about grammar inheritance
> and think it could be useful here.
> Thanks
> Param

This sounds like exactly the case for "gated predicates" given inside
of the "ANTLR: The Definitive Guide".  Essentially if you had the
lexer/parser rules that are gated by an "global" variable (either a
boolean, or an enumeration).

foo : ( {isEnglishAllowed()}?=> englishFoo
       |  {isGermanAllowed()}?=> germanFoo
       | defaultFoo
       );

If you read the beginning on Chapter 12, they discuss enabling and
disabling various language extensions (like parsing ANSI C vs.
including the gcc extensions based upon flags).  The reason to use
"globals" is that those predicates will be hoisted from the parser
into the DFA.  So if you try and using do something like:

foo[LangEnum lang]: ( {lang==ENGLISH}? => englishFoo| ... );

It won't work, because "lang" is not a global.  I really wish there
were a way to pass an actual constant (I've got a number of
lexer/parser rules that I can express in terms of a half dozen
constants, but I can't find a better when then generating the rules).

It appears you can use scopes to affect that sort of thing, but I
don't yet understand how to use those effectively.

Thanks,
    Kirby


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