Why does ANTLR sometimes go into an infinite loop when constructing AST trees?

Matthew Ford

Turn off default AST construction for that rule

eg rule was

assignmentExpression
: lhs:lhsExpression ASSIGN! ex:expression {#assignmentExpression = #(#[ASSIGN_EXPR,"ASSIGN"],#lhs,#ex);} ;

This caused ANTLR to go into an infinite loop when running the parser built by ANTLR

change to (not the ! in the first line to suppress default AST)
assignmentExpression!
   : lhs:lhsExpression ASSIGN! ex:expression
    {#assignmentExpression = #(#[ASSIGN_EXPR,"ASSIGN"],#lhs,#ex);}
   ;
This works now.

Sinan suggested these alternatives

assignmentExpression!
  : lhs:lhsExpression ASSIGN! ex:expression
    {## = #(#[ASSIGN_EXPR,"ASSIGN"],#lhs,#ex);}
  ;

or

assignmentExpression
  : lhsExpression ASSIGN! expression
    {## = #(#[ASSIGN_EXPR,"ASSIGN"],##);}
  ;

or

assignmentExpression
  : lhsExpression a:ASSIGN^ expression
    {#a.setType(ASSIGN_EXPR);}
  ;

I (Sinan) personally like the last one since I can write things like

operand :
	(constant) => constant
	| (variable) => variable
	| p:Plus^ operand {#p.setType(UNARY_PLUS);}
	| m:Minus^ operand {#m.setType(UNARY_MINUS);}
	| Lp! expression Rp!
	| valFnKW Lp! expression Rp!
	{ ## = #([ValFN],##); }
;
0 Comments  (click to add your comment)
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

About | Sitemap | Contact