Defining rule that accepts arguments in any order
Asked Answered
A

1

7

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?

Aleksandr answered 17/7, 2013 at 11:21 Comment(0)
A
14

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
  ;
Argueta answered 17/7, 2013 at 12:24 Comment(1)
Thanks 280Z28! This helped me come out of a sticky thought process that fogged my mind and take a simple view of the problem.Aleksandr

© 2022 - 2024 — McMap. All rights reserved.