1

I'm creating an antlr4 grammar for a language that has several possibilities for variable declaration prefixes, e.g. a variable declaration could be any of the following:

IDENTIFIER
PREFIX1 IDENTIFIER
PREFIX2 IDENTIFIER
PREFIX1 PREFIX2 IDENTIFIER
PREFIX2 PREFIX1 IDENTIFIER

and the prefixes are optional and can be in any order, but at most one of each.

If I have a rule:

var_declaration: (PREFIX1 | PREFIX2)? IDENTIFIER;

then that will handle none or a single prefix of either type. How do I handle none, one or both in either order but prevent two prefixes the same?

1 Answers1

1

There's no special syntax for that. You will have a define all alternatives:

var_declaration
 : PREFIX1 PREFIX2 IDENTIFIER
 | PREFIX2? PREFIX1? IDENTIFIER
 ;

If there are more than 2 prefixes, listing them will become verbose. In that case, it's best to match any of them zero or more times:

var_declaration
 : prefix* IDENTIFIER
 ;

prefix
 : PREFIX1
 | PREFIX2
 | PREFIX3
 ;

and then checking after the parse (using a tree-listener) if the prefixes that got matched are unique.

Related Q&A: In ANTLR, is there a shortcut notation for expressing alternation of all the permutations of some set of rules?

Bart Kiers
  • 166,582
  • 36
  • 299
  • 288