ANTLR4 visitor pattern on simple arithmetic example
Asked Answered
D

2

28

I am a complete ANTLR4 newbie, so please forgive my ignorance. I ran into this presentation where a very simple arithmetic expression grammar is defined. It looks like:

grammar Expressions;

start : expr ;

expr  : left=expr op=('*'|'/') right=expr #opExpr
      | left=expr op=('+'|'-') right=expr #opExpr
      | atom=INT #atomExpr
      ;

INT   : ('0'..'9')+ ;

WS    : [ \t\r\n]+ -> skip ;

Which is great because it will generate a very simple binary tree that can be traversed using the visitor pattern as explained in the slides, e.g., here's the function that visits the expr:

public Integer visitOpExpr(OpExprContext ctx) {
  int left = visit(ctx.left);
  int right = visit(ctx.right);
  String op = ctx.op.getText();
  switch (op.charAt(0)) {
    case '*': return left * right;
    case '/': return left / right;
    case '+': return left + right;
    case '-': return left - right;
    default: throw new IllegalArgumentException("Unkown opeator " + op);
  }
}

The next thing I would like to add is support for parentheses. So I modified the expr as follows:

expr  : '(' expr ')'                      #opExpr
      | left=expr op=('*'|'/') right=expr #opExpr
      | left=expr op=('+'|'-') right=expr #opExpr
      | atom=INT #atomExpr
      ;

Unfortunately, the code above fails because when encountering parentheses the three attributes op,left and right are null (fails with NPE).

I think I could work around that by defining a new attribute, e.g., parenthesized='(' expr ')', and then deal with that in the visitor code. However, it seems overkill to me to have a whole extra node type to represent an expression in parentheses. A simpler but uglier solution is to add the following line of code at the beginning of the visitOpExpr method:

if (ctx.op == null) return visit(ctx.getChild(1)); // 0 and 2 are the parentheses!

I don't like the above at all because it's very fragile and highly dependent on the grammar structure.

I am wondering if there is a way to tell ANTLR to just "eat" the parentheses and treat the expression like a child. Is there? Is there a better way to do this?

Note: My end goal is to extend the example to include boolean expressions that can themselves contain arithmetic expressions, e.g., (2+4*3)/10 >= 11, that is, a relation (<,>,==,~=,etc.) between arithmetic expressions can define an atomic boolean expression. This is straight forward and I already have the grammar sketched out but I have the same problem with parenthesis, i.e., I need to be able to write stuff like (I will also add support for variables):

((2+4*x)/10 >= 11) | ( x>1 & x<3 )

EDIT: Fixed the precedence of the parenthesized expression, parenthesis always have higher precedence.

Dogooder answered 15/4, 2014 at 18:55 Comment(0)
K
27

Sure, just label it differently. After all, the alternative '(' expr ')' isn't a #opExpr:

expr  : left=expr op=('*'|'/') right=expr #opExpr
      | left=expr op=('+'|'-') right=expr #opExpr
      | '(' expr ')'                      #parenExpr
      | atom=INT                          #atomExpr
      ;

And in your visitor, you'd do something like this:

public class EvalVisitor extends ExpressionsBaseVisitor<Integer> {

    @Override
    public Integer visitOpExpr(@NotNull ExpressionsParser.OpExprContext ctx) {
        int left = visit(ctx.left);
        int right = visit(ctx.right);
        String op = ctx.op.getText();
        switch (op.charAt(0)) {
            case '*': return left * right;
            case '/': return left / right;
            case '+': return left + right;
            case '-': return left - right;
            default: throw new IllegalArgumentException("Unknown operator " + op);
        }
    }

    @Override
    public Integer visitStart(@NotNull ExpressionsParser.StartContext ctx) {
        return this.visit(ctx.expr());
    }

    @Override
    public Integer visitAtomExpr(@NotNull ExpressionsParser.AtomExprContext ctx) {
        return Integer.valueOf(ctx.getText());
    }

    @Override
    public Integer visitParenExpr(@NotNull ExpressionsParser.ParenExprContext ctx) {
        return this.visit(ctx.expr());
    }

    public static void main(String[] args) {
        String expression = "2 * (3 + 4)";
        ExpressionsLexer lexer = new ExpressionsLexer(CharStreams.fromString(expression));
        ExpressionsParser parser = new ExpressionsParser(new CommonTokenStream(lexer));
        ParseTree tree = parser.start();
        Integer answer = new EvalVisitor().visit(tree);
        System.out.printf("%s = %s\n", expression, answer);
    }
}

If you run the class above, you'd see the following output:

2 * (3 + 4) = 14
Koenraad answered 15/4, 2014 at 19:14 Comment(5)
I see. So I guess there is no way to just have ANTLR get rid of the intermediate node? In principle there's also a matter of space efficiency here isn't there?Dogooder
Not entirely sure if I know what you mean, but there's no way around handling the parenthesized alternative: ANTLR is just there for parsing, all other logic/evaluation must be handled explicitly by yourself [in a visitor/listener class].Koenraad
I mean if you write this: ((((((((((2+3)))))))))), instead of 2+3, the syntax is obviously valid, but the space taken by the tree is much larger because of all the parentheses nodes. I am just surprised there isn't a way to define a short-circuit so that the former expression gets converted to the latter.Dogooder
Ah, I see. Yeah, AFAIK, there is no such feature to rewrite the parse tree. Also see: #18769405Koenraad
Gotcha. That's not so bad with the change you suggested. Thanks!Dogooder
L
3

I have ported above to Python Visitor and even Python Listener

Python listener

from antlr4 import *
from arithmeticLexer import arithmeticLexer
from arithmeticListener import arithmeticListener
from arithmeticParser import arithmeticParser
import sys

##  grammar arithmetic;
##  
##  start : expr ;
##  
##  expr  : left=expr op=('*'|'/') right=expr #opExpr
##        | left=expr op=('+'|'-') right=expr #opExpr
##        | '(' expr ')'                      #parenExpr
##        | atom=INT                          #atomExpr
##        ;
##  
##  INT   : ('0'..'9')+ ;
##  
##  WS    : [ \t\r\n]+ -> skip ;

import codecs
import sys

def dump(obj):
  for attr in dir(obj):
    print("obj.%s = %r" % (attr, getattr(obj, attr)))

def is_number(s):
    try:
        float(s)
        return True
    except ValueError:
        return False


class arithmeticPrintListener(arithmeticListener):

    def __init__(self):
        self.stack = []

    # Exit a parse tree produced by arithmeticParser#opExpr.
    def exitOpExpr(self, ctx:arithmeticParser.OpExprContext):

        print('exitOpExpr INP',ctx.op.text,ctx.left.getText(),ctx.right.getText())

        op = ctx.op.text

        opchar1=op[0]
        right= self.stack.pop()
        left= self.stack.pop()

        if opchar1 == '*':
           val = left * right 
        elif opchar1 == '/':
           val = left / right 
        elif opchar1 == '+':
           val = left + right 
        elif opchar1 == '-':
           val = left - right
        else:
           raise ValueError("Unknown operator " + op) 

        print("exitOpExpr OUT",opchar1,left,right,val)

        self.stack.append(val)


    # Exit a parse tree produced by arithmeticParser#atomExpr.
    def exitAtomExpr(self, ctx:arithmeticParser.AtomExprContext):
         val=int(ctx.getText())
         print('exitAtomExpr',val)
         self.stack.append(val)

def main():
    #lexer = arithmeticLexer(StdinStream())
    expression = "(( 4 - 10 ) * ( 3 + 4 )) / (( 2 - 5 ) * ( 3 + 4 ))"
    lexer = arithmeticLexer(InputStream(expression))
    stream = CommonTokenStream(lexer)
    parser = arithmeticParser(stream)
    tree = parser.start()
    printer = arithmeticPrintListener()
    walker = ParseTreeWalker()
    walker.walk(printer, tree)

if __name__ == '__main__':
    main()

Python Visitor

from antlr4 import *
from arithmeticLexer import arithmeticLexer
from arithmeticVisitor import arithmeticVisitor
from arithmeticParser import arithmeticParser
import sys
from pprint import pprint


##  grammar arithmetic;
##  
##  start : expr ;
##  
##  expr  : left=expr op=('*'|'/') right=expr #opExpr
##        | left=expr op=('+'|'-') right=expr #opExpr
##        | '(' expr ')'                      #parenExpr
##        | atom=INT                          #atomExpr
##        ;
##  
##  INT   : ('0'..'9')+ ;
##  
##  WS    : [ \t\r\n]+ -> skip ;

import codecs
import sys

class EvalVisitor(arithmeticVisitor):
    def visitOpExpr(self, ctx):

        #print("visitOpExpr",ctx.getText())

        left = self.visit(ctx.left)
        right = self.visit(ctx.right)
        op = ctx.op.text;

        # for attr in dir(ctx.op): ########### BEST 
        #   print("ctx.op.%s = %r" % (attr, getattr(ctx.op, attr)))
        #print("visitOpExpr",dir(ctx.op),left,right)

        opchar1=op[0]
        if opchar1 == '*':
           val = left * right 
        elif opchar1 == '/':
           val = left / right 
        elif opchar1 == '+':
           val = left + right 
        elif opchar1 == '-':
           val = left - right
        else:
           raise ValueError("Unknown operator " + op) 
        print("visitOpExpr",opchar1,left,right,val)
        return val 

    def visitStart(self, ctx):
        print("visitStart",ctx.getText())
        return self.visit(ctx.expr())

    def visitAtomExpr(self, ctx):
        print("visitAtomExpr",int(ctx.getText()))
        return int(ctx.getText())

    def visitParenExpr(self, ctx):
        print("visitParenExpr",ctx.getText())
        return self.visit(ctx.expr())

def main():
    #lexer = arithmeticLexer(StdinStream())
    expression = "(( 4 - 10 ) * ( 3 + 4 )) / (( 2 - 5 ) * ( 3 + 4 ))"
    lexer = arithmeticLexer(InputStream(expression))
    stream = CommonTokenStream(lexer)
    parser = arithmeticParser(stream)
    tree = parser.start()
    answer = EvalVisitor().visit(tree) 
    print(answer)

if __name__ == '__main__':
    main()
Lawhorn answered 28/8, 2018 at 10:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.