Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  • 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?

>Solution :

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading