[antlr-interest] v3: semantic predicates in parser

Richard Musiol mail at richard-musiol.de
Fri Aug 18 05:25:05 PDT 2006


Hi,

semantic predicates in the parser don't seem to work in beta 3 as they 
did in ANTLR 2. Will they be supported in the final?

For example the following grammar:

grammar Test;

document : (element)* EOF ;
element : theA | B | C	;

theA
	:
		A
		(
			{ someCondition }?=>
			theElement=element
			{
				// do something with theElement
			}
		|
			// quit the rule
		)
	;

A : 'a' ;
B : 'b' ;
C : 'c' ;

ANTLR can't handle it:
"[fatal] rule theA has non-LL(*) decision due to recursive rule 
invocations in alts 1,2. Resolve by left-factoring or using syntactic 
predicates with fixed k lookahead or using backtrack=true option."

At my opinion, ANTLR should use the first alternative if someCondition 
is true and the second one if not.

My second approach was to swap the alternatives:

theA
	:
		A
		(
			{ !someCondition }?=>
			// quit the rule
		|
			theElement=element
			{
				// do something with the element
			}
		)
	;

ANTLR compiles this without any errors, but the resulting code is really 
stange:

[...]
else if ( (LA3_0==A) ) {
	else {
		NoViableAltException nvae = [...];
		throw nvae;
	}
}
[...]

It seems that there is a bug in the code generation. But also the 
decisions are wrong:

[...]
int alt3=2;
int LA3_0 = input.LA(1);
	if ( (LA3_0==EOF) && ( !someCondition )) {
		alt3=1;
	}
[...]

Why should it only quit the rule if an EOF is following? There may be an 
A, B or C too.

I hope this will get fixed until the final, because semantic predicates 
are a really powerful feature.

Regards,
Richard



More information about the antlr-interest mailing list