6

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?

4

1 回答 1

10

有几种方法可以解决这个问题。最简单的选项之一是使用以下解析器规则。

interfaceCommands
  : (descriptionCmd | ipAddressCmd | otherCmd)*
  ;

然后,您可以在解析完成后在侦听器或访问者中执行额外的验证(例如,确保只descriptionCmd解析了一个,或者确保解析了这些项目中的每一个,等等)。这种策略有很多优点,特别是在提高您检测和报告更多类型的语法错误的能力方面,并带有清晰的消息。

另一种选择是简单地列举用户输入这些项目的可能方式。由于这很难编写/读取/验证/维护,因此我只在没有其他方法可以使用更通用的解析器规则并稍后执行验证时才使用此选项。

interfaceCommands
  : descriptionCmd ipAddressCmd otherCmd
  | descriptionCmd otherCmd ipAddressCmd
  | ipAddressCmd descriptionCmd otherCmd
  | ipAddressCmd otherCmd descriptionCmd
  | otherCmd descriptionCmd ipAddressCmd
  | otherCmd ipAddressCmd descriptionCmd
  ;
于 2013-07-17T12:24:38.710 回答