yegor256
yegor256

Reputation: 105210

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?

Upvotes: 1

Views: 79

Answers (1)

Mike Lischke
Mike Lischke

Reputation: 53582

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).

Upvotes: 1

Related Questions