[antlr-interest] Semantic predicates

Kaleb Pederson kaleb.pederson at gmail.com
Fri Oct 16 12:35:51 PDT 2009


On Fri, Oct 16, 2009 at 10:39 AM, Robert Wentworth <bob at wentworth.bz> wrote:
> There appears to be something fundamental that I am not "getting"
> about the way semantic predicates work. In the grammar below, the
> input "cat" is recognized using the rule "cat" but in not recognized
> by either the rule "expr" or the rule "pexpr". Could someone explain
> to me why this is so and what the fix is?

[... snip ...]
> cat     : {input.LT(1).getText().equals("cat")}?=> WORD ;
>
> dog     : {input.LT(1).getText().equals("dog")}?=> WORD ;

You're using a gated semantic predicate.  A gated semantic predicate
is used to distinguish between multiple alternatives, but as you have
only one alternative, this isn't what you want. See
https://wincent.com/wiki/ANTLR_predicates for more information on
predicates.

> expr    :       cat
>                | cat WHEN dog
>                | dog

You could do:

expr: cat (WHEN dog)? | dog;

You should also be able to use a syntactic predicate:

expr: (cat WHEN)=> cat WHEN dog
    | cat
    | dog;

HTH,

--
Kaleb Pederson
Twitter - http://twitter.com/kalebpederson
Blog - http://kalebpederson.com


More information about the antlr-interest mailing list