3

I am building a grammar in ANTLR4, and I am getting this warning

TL4.g4:224:12: greedy block ()* contains wildcard; the non-greedy syntax ()*? may be preferred

Here is the line of code it is referring to

block
    : ( statement | functionDecl )* (Return expression ';')?
    ;

What does the warning mean, How can I correct it ?

Gautam
  • 7,868
  • 12
  • 64
  • 105
  • it's an old question, but still, I would like to share the ANTLR documentation, which provides further clarification on the topic: https://github.com/antlr/antlr4/blob/master/doc/wildcard.md – SimonAda May 19 '17 at 15:11

1 Answers1

7

The warning is telling you that the block ()* is greedy, meaning that it will try to match maximum occurrences of statement or functionDec1 which, depending on the situation, might not be what you expect.

Changing it to ()*? makes it non-greedy, as suggested by the warning. This means it will match minimum occurrences of statement or functionDec1.

Expression examples with strings:

Samples:

foofoobar
foobarbar
foofoobarbarbar

Expression:

(foo|bar)*bar

Will give result:

foofoobar
foobarbar
foofoobarbarbar

Expression:

(foo|bar)*?bar

Will give result:

foofoobar
foobar
foofoobar

For the last one, the result will stop at the first bar

Jerry
  • 70,495
  • 13
  • 100
  • 144
  • can you please add some examples – Gautam May 14 '13 at 17:30
  • 1
    @mataug How about those string match examples? – Jerry May 14 '13 at 17:52
  • 2
    I'm a little late to the party, but is there any way to suppress this warning? What if I want to capture all of the text between /* and */? Would it not be best to take the greedy approach? – Giga Chad Coding Jan 30 '19 at 20:55
  • 2
    @JohnSmith Not that I'm aware of, and that'd be risky, unless you know there's exactly 1 of these `/* ... */` in the text, because if not, then you will get everything from the first `/*` to the last `*/` with no regards to whether there is another `*/` in the middle of those. – Jerry Jan 31 '19 at 16:02
  • @Jerry, so that's what it's saying. Okay that makes a lot of sense! Thank you. – Giga Chad Coding Feb 01 '19 at 17:03