Search code examples
javaantlrantlr4

How to make ANTLR rule consume all possible elements, not only the first one?


This is my grammar:

grammar test;
text: foo EOF;
foo: 'X' | foo tail;
tail: (' ' foo)+;

This is the input:

X X X X

The tree looks like this:

enter image description here

Instead, I expect only one tail to exist in the output tree, which must include three foo elements. How can I do that?


Solution

  • By removing the left recursion from foo: 'X' | foo tail; you can better see why you get more than one tail:

    foo: 'X' tail*;
    

    This also works for multiple 'X' because tail contains another recursion (back to foo).