Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining rule that accepts arguments in any order

Tags:

antlr

antlr4

I have a rule that reads as

interfaceCommands
    :   descriptionCmd
        ipAddressCmd
        otherCmd
    ;

Though the expected order of Cmds is as stated in the grammar, I also should be able to accept the input when the order of these Cmds are interchanged. For example, At any time, ipAddressCmd can precede descriptionCmd or come after otherCmd in the actual input. How should my grammar be modified to accommodate and be able to parse these disordered inputs?

like image 605
callmeDP Avatar asked Jul 17 '13 11:07

callmeDP


1 Answers

There are a couple ways to approach this. One of the simplest options is to use the following parser rule.

interfaceCommands
  : (descriptionCmd | ipAddressCmd | otherCmd)*
  ;

You could then perform additional validation in a listener or visitor after parsing is complete (e.g. ensure that only one descriptionCmd was parsed, or make sure that exactly one of each of these items was parsed, etc.). This strategy has many advantages, especially in improving your ability to detect and report more types of syntax errors with clear messages.

Another option is to simply enumerate the possible ways a user could enter these items. Since this is hard to write/read/validate/maintain, I only use this option when there is no other way for me to use a more generic parser rule and perform the validation later.

interfaceCommands
  : descriptionCmd ipAddressCmd otherCmd
  | descriptionCmd otherCmd ipAddressCmd
  | ipAddressCmd descriptionCmd otherCmd
  | ipAddressCmd otherCmd descriptionCmd
  | otherCmd descriptionCmd ipAddressCmd
  | otherCmd ipAddressCmd descriptionCmd
  ;
like image 155
Sam Harwell Avatar answered Oct 09 '22 06:10

Sam Harwell