Tony Ennis
Tony Ennis

Reputation: 12299

At least one Antlr rule optional part

consider this grammar fragment:

a : 'x' (b)? (c)? (d)? 'x'

I want at least one of b, c, or d to be present. Any that are present must be in the order specified. So 'xx' should not be valid because at least one of [b, c, d] should be specified. "xcbx" would also be invalid since b and c are mis-ordered. How do I express this? Previously I'd have one rule for every combination, and that is really low-rent on my part.

Upvotes: 1

Views: 407

Answers (2)

Mike Lischke
Mike Lischke

Reputation: 53337

You can do a semantic check after the parse run as Mike Cargal suggests, or you try something which I used in the MySQL grammar occasionally:

a: 'x' (
     | (b) (c)? (d)?
     | (c) (d)?
     | (d)
 ) 'x'
;

Upvotes: 1

Mike Cargal
Mike Cargal

Reputation: 6785

Since order is important, and you want at least one of these, I’d suggest you leave the grammar as is and then perform the edit to ensure that one of them is present in a visitor/listener once the input is parsed.

One mistake a lot of people make is wanting to get “all the things” in their grammar. In general, getting the grammar to simply interpret the input correctly and unambiguously, and then doing the rest of the validation in your own code, will result in cleaner grammars, and better error messages.

Sure, ANTLR will “accept” x x, but you can detect that there is no b, c, or d.

Upvotes: 2

Related Questions