[antlr-interest] Problems with syntactic predicates(?)

Jim Idle jimi at temporal-wave.com
Sat Jan 26 17:06:21 PST 2008


Look at the example grammars for how to set up for parsing expressions 
with precedence, you don't need those predicates but you do need to 
chain your rules correctly. Start by coding the primitives (the thigns 
that cannot break down further). You want something like

equations
	: equation* EOF
	;

equation
  : primary ('=' primary)?
  ;

primary
  : IDENT ('(' expression (',' expression)* ')')?
  | INT
  ;

INT	:	( '0'..'9' )+ ;
IDENT	:	( 'a'..'z' )+ ;
WS	:	(' ' | '\t' )+ { $channel = HIDDEN; } ;
NL	:	'\r'? '\n'	{ $channel = HIDDEN; } ;

You are trying to construct context/semantics in the parser, but it's 
job is to parse correct syntactical constructs only. After the parser 
you can apply context and semantics. For your grammar then you want to 
combine everything with common roots into one rule/alt and branch when 
tokens tell you that you must.

Jim

> -----Original Message-----
> From: Christian Gudrian [mailto:gn at fluidon.dyndns.info]
> Sent: Saturday, January 26, 2008 12:24 PM
> To: antlr-interest at antlr.org
> Subject: [antlr-interest] Problems with syntactic predicates(?)
> 
> Hello!
> 
> I want to write a grammar that matches equations like:
> 
> a=1
> 2=b
> f_a(3)=4
> 5=f_b(6,7)
> f_c(8,9)
> 
> This is my approach so far:
> 
> // -------------------------- 8< --------------------------
> 
> grammar test;
> 
> INT	:	( '0'..'9' )+ ;
> IDENT	:	( 'a'..'z' )+ ;
> 
> equation
> 	:	( expression '=' ) => expression '=' expression
> 	|	function_call
> 	;
> 
> expression
> 	:	( IDENT '(' ) => function_call
> 	|	INT
> 	|	IDENT
> 	;
> 
> function_call
> 	:	IDENT '(' args? ')' ;
> 
> args	:	expression ( ',' expression )* ;
> 
> // ------------------------- >8 --------------------------
> 
> The ANTLRWorks debugger shows me, that the equation rule matches input
> of the form "a=1".  Everything involving function calls doesn't match,
> however; I get a NoViableAltException(0!=[null]) error in these
> cases.  I suspect it's my use of syntactic predicates which causes
> this behaviour, isn't it?  What's wrong?
> 
> Christian
> 




More information about the antlr-interest mailing list