1

I have a section of a ALTLR grammar which goes like this:

mainfilter: mandatoryfilter (optionalfilter1)? (optionalfilter2)? (optionalfilter3)? ;
mandatoryfilter: 'NAME' '=' ID;
optionalfilter1: 'VALUE1' EQ ID; 
optionalfilter2: 'VALUE2' EQ ID; 
optionalfilter3: 'VALUE3' EQ ID; 
EQ: '=' ;

ID: [A-Za-z0-9]+
//Also I will skip spaces and whitespace

My requirement is that the "optionalfilter" rules can occur in any order. One approach I think of is rewrite the rule like below and then validate using a Listener:

mainfilter: mandatoryfilter (optionalfilter1|optionalfilter2|optionalfilter3)*;

Another way to achieve this is to put all combinations in one parser rule each . but that may not be a wiser solution if the number of optionalfilter increases.

Sample input:

NAME = BOB VALUE1=X VALUE2=Y VALUE3 = Z
NAME = BILL VALUE3=X VALUE1=Y VALUE2 = Z

my grammar will successfully parse the first input but not the second one.

So is there an elegant way to handle this in my grammar itself ?

Simeon Leyzerzon
  • 18,658
  • 9
  • 54
  • 82
ssdimmanuel
  • 448
  • 10
  • 29

1 Answers1

1

So is there an elegant way to handle this in my grammar itself ?

No.

Usually, zero or more are matched and then after parsing, it is validated that a filter only occurs once.

Take for example the Java Language Specification that defines that a class definition can have zero or more class modifiers (the {ClassModifier} part)

NormalClassDeclaration:
  {ClassModifier} class Identifier [TypeParameters] [Superclass] [Superinterfaces] ClassBody

ClassModifier:
  (one of) 
  Annotation public protected private abstract static final strictfp

which would match public public class Foo {}. This is rejected at the stage after parsing.

Bart Kiers
  • 166,582
  • 36
  • 299
  • 288
  • Thanks Bart. Now I have some clarity. Also I am also looking at autocomplete using https://github.com/mike-lischke/antlr4-c3 . now each time I will get all of the tokens as autocomplete suggestions. – ssdimmanuel Jun 03 '18 at 14:11