我的规则是:
interfaceCommands
: descriptionCmd
ipAddressCmd
otherCmd
;
Run Code Online (Sandbox Code Playgroud)
虽然预期的顺序Cmds如语法中所述,但我也应该能够在这些顺序Cmds互换时接受输入.例如,在任何时候,ipAddressCmd可以在实际输入之前descriptionCmd或之后otherCmd.我的语法应如何修改以适应并能够解析这些无序输入?
有几种方法可以解决这个问题.最简单的选项之一是使用以下解析器规则.
interfaceCommands
: (descriptionCmd | ipAddressCmd | otherCmd)*
;
Run Code Online (Sandbox Code Playgroud)
然后,您可以在解析完成后在侦听器或访问者中执行其他验证(例如,确保只descriptionCmd解析了一个,或确保解析了其中每个项中的一个,等等).此策略具有许多优点,尤其是在提高您使用明确消息检测和报告更多类型的语法错误的能力方面.
另一种选择是简单地枚举用户可以输入这些项目的可能方式.由于这很难编写/读取/验证/维护,所以当我没有其他方法可以使用更通用的解析器规则并稍后执行验证时,我只使用此选项.
interfaceCommands
: descriptionCmd ipAddressCmd otherCmd
| descriptionCmd otherCmd ipAddressCmd
| ipAddressCmd descriptionCmd otherCmd
| ipAddressCmd otherCmd descriptionCmd
| otherCmd descriptionCmd ipAddressCmd
| otherCmd ipAddressCmd descriptionCmd
;
Run Code Online (Sandbox Code Playgroud)