Lisa
Lisa

Reputation: 227

How to fix mutually left-recursive in ANTLR4 rules

I'm trying to parse a language in ANTLRWorks2:

grammar testLR;
pb: 'kind' '=' ID ';' pb
  | fd pb
  |
  ;
fd: ( 'instance' '=' ID ';' )*   
  ;
ID: ('a'..'z'|'A'..'Z'|'_'|'$') ('a'..'z'|'A'..'Z'|'0'..'9'|'_'|'$')*
  ;

Then ANTLRWork tells me: "The following sets of rules are mutually left-recursive [pb]". I just can not figure out how to fix the problem. Any suggestions are welcome. Thanks!

Upvotes: 3

Views: 4660

Answers (1)

Simon Groenewolt
Simon Groenewolt

Reputation: 10665

Since your fd rule has a * that means it can be empty (* = 0 or more times) - having an empty fd would mean your pb rule (second line) would be a pb : pb, which is not allowed since the parser would keep looping forever. You can fix this by not allowing the fd rule to be empty (change * to +), but I have no idea if that is desired in your grammar.

Upvotes: 3

Related Questions