[英]Basic arithmetic grammar -- handling parentheses
I have written the following to handle basic binary operations in arithmetic:我编写了以下代码来处理算术中的基本二进制运算:
grammar Calc;
expression
: OPERAND (BIN_OP expression)*
;
// 12 or .12 or 2. or 2.38
OPERAND
: [0-9]+ ('.' [0-9]*)?
| '.' [0-9]+
;
BIN_OP
: [-+/*]
;
Now I can do things like:现在我可以执行以下操作:
0.9+2.4*3.6
However, how is order-of-operations and parentheses normally handled with antlr?但是,antlr 通常如何处理操作顺序和括号? For example:例如:
(0.9+2.4)*3.6
instead, how could I do that?如果我想写(0.9+2.4)*3.6
怎么办,我该怎么做呢?((0.9+2.4)*3.6)
?或者,如果我想写((0.9+2.4)*3.6)
怎么办?(((((0.9+2.4)*3.6))
?最后,要捕获不匹配括号的无效情况, (((((0.9+2.4)*3.6))
?How is that normally handled in antlr?在antlr中通常如何处理?
One of the really nice things that ANTLR4 brought was the ability to easily represent precedence by the ordering of alternatives in a rule. ANTLR4 带来的真正好处之一是能够通过规则中的替代排序轻松表示优先级。
Try something like:尝试类似:
grammar Calc;
expression
: '(' expression ')' # parenExpr
: expression (MUL_OP | DIV_OP) expression # mulDivExpr
: expression (ADD_OP | SUB_OP) expressions # addSubExpr
: OPERAND # operandExpr
;
// 12 or .12 or 2. or 2.38
OPERAND
: [0-9]+ ('.' [0-9]*)?
| '.' [0-9]+
;
SUB_OP: '-';
ADD_OP: '+';
DIV_OP: '/';
MUL_OP: '*';
;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.