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?
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
;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With