Robert B
Robert B

Reputation: 3255

Removing mutual left-recursion from left-recursive rules

With ANTLR 4.6, snapshot of 11/23/2016.

I have two rules which are each left-recursive. I expanded several of the alternatives to expose the left recursion. ANTLR4 handles this, because the left recursion is explicit. However, the two rules are also mutually left-recursive.

How do I resolve the mutual left recursion AND do so so that the rules aren't a total mess? Right now I have nice comments showing what was expanded, and I moved that to primary2 and constant_primary2 which aren't involved in the mutual left recursion.

constant_primary : 
  constant_primary2
  | primary '.' method_call_body
  | constant_primary '\'' '(' constant_expr ')'
  ;

primary : 
  primary2
  | primary '.' method_call_body
  | constant_primary '\'' '(' expr ')'
  ;

Upvotes: 0

Views: 98

Answers (1)

Sam Harwell
Sam Harwell

Reputation: 99859

One option is to switch to using my fork of ANTLR 4, which is available through Maven using the Group ID com.tunnelvisionlabs. This fork handles mutual left recursion while producing parse trees that match the form you actually wrote in the grammar.

Note that this feature is somewhat experimental. If you run into problems feel free to post an issue on the issue tracker for my fork.

Upvotes: 1

Related Questions