[英]N-ary operators in ANTLR4 grammar
I have a grammar for parsing boolean formulas:我有一个解析 boolean 公式的语法:
expr: op=NOT right=expr #Not
| left=expr op=AND right=expr #And
| left=expr op=OR right=expr #Or
| left=expr op=XOR right=expr #Xor
| <assoc=right> left=expr op=IMPL right=expr #Implication
| <assoc=right> left=expr op=EQ right=expr #Equivalence
| boolean=BOOL #Boolean
| '(' content=expr+ ')' #Brackets
| atomic=ATOMIC #Atomic
;
BOOL : TRUE|FALSE;
NOT : ('!'|'not');
AND : ('&'|'and');
OR : ('|'|'or');
XOR : ('^'|'xor');
IMPL : '->';
EQ : '<->';
TRUE : ('True'|'true');
FALSE : ('False'|'false');
ATOMIC : [a-z]+([_]?[a-z]+)*;
WS : [ \t\n]+ -> skip; //Skip whitespaces
How can I change AND
, OR
, and XOR
to be n-ary instead of binary (so that the children of these operators are on the same level)?如何将AND
、 OR
和XOR
更改为 n 元而不是二进制(以便这些运算符的子级处于同一级别)? I tried replacing left=expr op=AND right=expr
with expr (op=AND expr)+
, which does not change anything.我尝试用expr (op=AND expr)+
替换left=expr op=AND right=expr
,这不会改变任何东西。
Something like this would do the trick:这样的事情可以解决问题:
expr
: <assoc=right> expr IMPL expr
| <assoc=right> expr EQ expr
| xor_expr
;
xor_expr
: or_expr (XOR or_expr)*
;
or_expr
: and_expr (OR and_expr)*
;
and_expr
: unary (AND unary)*
;
unary
: NOT atom
| atom
;
atom
: BOOL
| '(' expr+ ')'
| ATOMIC
;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.