Search code examples
javaantlrvisitor-pattern

What Does the ANTLR ParseTree accept() method do?


I´m studying how to build a typechecker using ANTLR´s Tree walker. I saw there´s an accept method. This method is sometimes used in compilers books when showing examples of a type checker implementation

public Type visit(Plus n) {
if (! (n.e1.accept(this) instanceof IntegerType) )
error.complain("Left side of LessThan must be of type integer");
if (! (n.e2.accept(this) instanceof IntegerType) )
error.complain("Right side of LessThan must be of type integer");
return new IntegerType();
}

That piece of code is from the book Modern Compiler Implementation In Java. But I don´t really understand what n.e1.accept(this) does.Every node of the tree has this method in ANTLR.

I´ve checked ANTLR v4 docs and the explanation is not really clear;

The ParseTreeVisitor needs a double dispatch method.

Can someone explain me what this does?

EDIT:

I researched a bit more and it is not an ANTLR specific question, I think this can be considered as a duplicate question so maybe it is a good idea to remove it:

What is the point of accept() method in Visitor pattern?


Solution

  • This is an internal implementation a visitor pattern. You can safely ignore it. You should subclass YOURGRAMMARBaseVisitor or YOURGRAMMARBaseListener.