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 ?