如果您查看 ObjectiveC antlr v3 语法(http://www.antlr3.org/grammar/1212699960054/ObjectiveC2ansi.g)和许多其他流行的语法,它们会采用与此类似的结构来解决条件
conditional_expression : logical_or_expression
('?' logical_or_expression ':' logical_or_expression)? ;
constant_expression : conditional_expression ;
logical_or_expression : logical_and_expression
('||' logical_and_expression)* ;
logical_and_expression : inclusive_or_expression
('&&' inclusive_or_expression)* ;
inclusive_or_expression : exclusive_or_expression
('|' exclusive_or_expression)* ;
exclusive_or_expression : and_expression ('^' and_expression)* ;
and_expression : equality_expression ('&' equality_expression)* ;
equality_expression : relational_expression
(('!=' | '==') relational_expression)* ;
relational_expression : shift_expression
(('<' | '>' | '<=' | '>=') shift_expression)* ;
shift_expression : additive_expression (('<<' | '>>') additive_expression)* ;
additive_expression : multiplicative_expression
(('+' | '-') multiplicative_expression)* ;
multiplicative_expression : cast_expression
(('*' | '/' | '%') cast_expression)* ;
cast_expression : '(' type_name ')' cast_expression | unary_expression ;
unary_expression
: postfix_expression
| '++' unary_expression
| '--' unary_expression
| unary_operator cast_expression
| 'sizeof' ('(' type_name ')' | unary_expression) ;
unary_operator : '&' | '*' | '-' | '~' | '!' ;
如果您阅读它,您会注意到他们执行了非常长的 1 对 1 条件链 from conditional_expression
to logical_or_expression
to logical_and_expression
to inclusive_or_expression
to exclusive_or_expression
。
现在,当谈到 ANTLR 时,我很天真,但这让我觉得这是一种奇怪的解析条件的方式。将logical_or_expression 的定义扭曲到所有其他条件表达式类型似乎非常复杂。毕竟,逻辑的定义OR
与左移位有什么关系?
是否有更好的方法,或者是否有特定的原因需要这种方法?