简体   繁体   中英

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? For example:

  • What if I wanted to write (0.9+2.4)*3.6 instead, how could I do that?
  • Or, what if I wanted to write ((0.9+2.4)*3.6) ?
  • And finally, to catch an invalid case of un-matched parens, (((((0.9+2.4)*3.6)) ?

How is that normally handled in 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.

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: '*';
    ;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM