Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Antlr - Expression parser and evaluator

I am required to write a boolean expression parser/evaluator. The expressions would be of the form and would be enclosed in parenthesis :

exp1 : (A = B)
exp2 : ((A = B) AND (C = D))
exp3 : ((A = B) AND ((C = D) OR (E = F)))
exp4: (((A = B) AND (C = D)) OR (E = F))

and it goes on. The rule may contain 'n' number of expressions with proper grouping 2 in each group. My grammar file looks like this:

/*
Expression grammar
 */

grammar Exparser;

options

{
    language = Java;
}
cond    :   
tc EOF;

tc:
      exp
  | binary_exp
| leftparen* exp ( binaryop leftparen* exp rightparen+)*
| leftparen* exp ( binaryop leftparen* exp rightparen*)*

;

binary_exp:
 '(' exp BINARYOP exp ')'
;

binaryop:
            BINARYOP
        ;
leftparen:
             LEFTPARN
         ;

rightparen:
              RIGHTPARN
          ;

exp:
LEFTPARN VARIABLE COMPOP VARIABLE RIGHTPARN

;

variable:
            VARIABLE;


BINARYOP: AND | OR;
COMPOP: EQUAL | LT | GT | LTE | GTE | NE;
VARIABLE: (CHAR)+;
LEFTPARN: '(';
RIGHTPARN: ')';
EQUAL: '=' | 'EQ';
LT: '<' | 'LT';

GT:'>' | 'GT';
LTE: '<=';
GTE: '>=';
NE  :   '!=' | 'NE';
AND: 'AND' | '&' | 'and';

OR: 'OR' | 'or';

CHAR  :   'a'..'z'|'A'..'Z'|'_' |'0'..'9'|'-' | '.'
   ;

this grammar works fine, but I am not able to achieve the depth in the AST. for example exp3 is parsed as three exp and not as one exp and one binary_exp. Also how do I evaluate a boolean expression using my parser? How does my grammar enforce balancing of parenthesis? Though Nested Boolean Expression Parser using ANTLR give some idea for evaluating an expression, I am not able to apply in my case

like image 823
ssdimmanuel Avatar asked Mar 08 '26 10:03

ssdimmanuel


1 Answers

The parser generated from the following grammar parses all your example input:

grammar Exparser;

parse
 : expr EOF
 ;

expr
 : expr binop expr
 | VARIABLE
 | '(' expr ')'
 ;

binop
 : AND | OR | EQUAL | LT | GT | LTE | GTE | NE
 ;

EQUAL     : '=' | 'EQ';
LT        : '<' | 'LT';
GT        : '>' | 'GT';
LTE       : '<=';
GTE       : '>=';
NE        : '!=' | 'NE';
AND       : 'AND' | '&' | 'and';
OR        : 'OR' | 'or';
VARIABLE  : [a-zA-Z0-9_.-]+;
SPACE     : [ \t\r\n] -> skip;

Evaluating these expressions should be the same as the Q&A you linked to in your question.

like image 174
Bart Kiers Avatar answered Mar 10 '26 01:03

Bart Kiers



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!