[antlr-interest] rules with parameters are not equivalent to rules without parameters

Ric Klaren ric.klaren at gmail.com
Tue Oct 10 07:06:55 PDT 2006


On 10/10/06, Kristian Marinkovic <kristian.marinkovic at porsche.co.at> wrote:
> i'm trying to understand why antlr is generating different code for rules
> with parameters and rules without parameters.

I assume you pruned your example a bit? E.g. removed the lexer and
parser definitions?

> I assumed that the 2 examples below are equivalent?!
>
> example without parameter:
>
> a : "AAA";
> b : "BBB";
> c : "CCC";

I assume you have a lexer that supplies the tokens "AAA" etc.? If
these are meant to be lexer rules then the name should be in upper
case. (and in that case you should reference the tokens in the parser
rules below)

> startRule : (body)*;

It's best to add an EOF check after the start rule:

startRule : (body)* EOF;

> body : (a | b) COL c SEMIC {//do sth};

> example with parameter:
>
> startRule : (body)*;
>
> body
> {
>       String a = null;
>       String b = null;
> }
> :
> ( {a = a_sub();} | {b = b_sub();} ) COL c SEMIC {//do sth};;

I think you meant:

( a = a_sub | b = b_sub ) COL c SEMIC {//do sth};;

The way you wrote it down you're calling the parser rules from the
action code which is probably not what you want.

> a_sub returns [String a] : a { a = "AAA"; //alt. get it from token};
> b_sub returns [String b] : b { b =" BBB"; //alt. get it from token};

Shouldn't these read:

a_sub returns [String a] : t:AAA { a = t.getText(); //alt. get it from token};
b_sub returns [String b] : t:BBB { b = t.getText(); //alt. get it from token};

Or alternatively:

body
{
      String the_string = null;
}
:
( t1:AAA { the_string = t1.getText();}
| t2:BBB { the_string = t2.getText();}
) COL c SEMIC {//do sth};;

Cheers,

Ric


More information about the antlr-interest mailing list