[antlr-interest] Wrong rule in parser gets matched

Dan Spaven danspaven at hotmail.com
Sat Feb 25 16:55:30 PST 2006


Hi there,
I keep on getting an error at runtime because my parser is matching the  
wrong rule. Every time an expression is parsed that assigns a value to a 
variable reference, the "sensorCont" rule is matched instead. I understand 
that this is because both statements can start with an IDENT but i can't for 
the life of me solve the problem. Could this be solved by a semantic 
predicate that somehow recognises the variable type? Or does my code need 
restructuring?

Help would be very much appreciated unfortunately i'm not only a newbie to 
ANTLR but parsing in general and i'm finding the learning curve very hard 
going.

Here below is a simplified version of my code showing the statements that 
are the problem.

statement
	:	sensorDec
	|	sensorCont
	|	expression
	;

sensorDec //declaration of sensor reference variable
	:	"sensor"^ IDENT "on"! INT
	;

sensorCont //Defines sensor attributes
	:	IDENT "is"^ type ("as" mode)*
	|	IDENT "as"^ mode
	;
type
	:	"unknown"
	|	"switch"
	|	"temperature"
	|	"light"
	|	"rotation"
	;

mode
	:	"raw"
	|	"boolean"
	|	"transition"
	|	"periodic"
	|	"percent"
	|	"celsius"
	|	"fahrenheit"
	|	"angle"
	;

expression
	:	addExpr
		(
			ASSIGN^
			expression
		)?
	;

addExpr
	:	multExpr
		(
			pm:PLUS_MINUS^ {System.out.println("matched PLUS-MINUS");}
			me:multExpr
			exception
				catch [ RecognitionException ex ]
				{
					System.out.println("Caught error in addExpr");
					reportError(ex.toString());
				}
		)*
	;

multExpr
	:	unaryExpression
		(
			MULT_DIV^ {System.out.println("matched MULT_DIV");}
			unaryExpression
		)*
	;

unaryExpression
	:	MINUS^ atom {System.out.println("matched UNARY MINUS");}
	|	PLUS^ atom {System.out.println("matched UNARY PLUS");}

	;


atom	:	a:IDENT {System.out.println(a.getText());}
	|	b:INT {System.out.println(b.getText());}
	|	LPAREN! expression RPAREN! {System.out.println("CALLING EXPRESSION in 
atom");}
	;

Thanks for any replies,

Dan




More information about the antlr-interest mailing list