Home > database >  Basic arithmetic grammar -- handling parentheses
Basic arithmetic grammar -- handling parentheses

Time:08-10

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?

CodePudding user response:

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