ANTLR ParseTree accept() 方法有什么作用?

What Does the ANTLR ParseTree accept() method do?

我正在研究如何使用 ANTLR 的 Tree walker 构建类型检查器。我看到有一个接受方法。在显示类型检查器实现示例时,有时会在编译器书籍中使用此方法

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();
}

那段代码来自 Java 中的现代编译器实现一书。但是我真的不明白什么 n.e1.accept(this) does.Every 树的节点在 ANTLR 中有这个方法。

我检查了 ANTLR v4 文档,但解释不是很清楚;

The ParseTreeVisitor needs a double dispatch method.

谁能解释一下这是做什么的?

编辑:

我进行了更多研究,这不是一个特定于 ANTLR 的问题,我认为这可以被视为重复问题,所以删除它也许是个好主意:

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

这是访问者模式的内部实现。您可以安全地忽略它。您应该继承 YOURGRAMMARBaseVisitor 或 YOURGRAMMARBaseListener。