[antlr-interest] Semantic predicates

Robert Wentworth bob at wentworth.bz
Fri Oct 16 10:39:36 PDT 2009


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?

Thanks,
Bob Wentworth

//======================================================


grammar ATest;

options {
	backtrack = true;
	memoize = true;
	output = template;
}

@parser::header { package dummy; }
@lexer::header { package dummy; }


WS  :   ( ' '
         | '\t'
         | '\r'
         | '\n'
         ) {$channel=HIDDEN;}
     ;

WHEN 	:	'when' ;

WORD	: ('a'..'z')+ ;

expr	:	cat
		| cat WHEN dog
		| dog
		;
		
pexpr	:	{input.LT(1).getText().equals("cat")}?=> cat
		| {input.LT(1).getText().equals("cat")}?=> cat WHEN dog
		| {input.LT(1).getText().equals("dog")}?=> dog
		;

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

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



More information about the antlr-interest mailing list