【问题标题】:What Does the ANTLR ParseTree accept() method do? [duplicate]ANTLR ParseTree accept() 方法有什么作用? [复制]
【发布时间】:2015-01-19 23:43:03
【问题描述】:

我正在研究如何使用 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) 的作用。树的每个节点在 ANTLR 中都有这个方法。

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

The ParseTreeVisitor needs a double dispatch method.

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

编辑:

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

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

【问题讨论】:

    标签: java antlr visitor-pattern


    【解决方案1】:

    这是一个访问者模式的内部实现。您可以放心地忽略它。你应该继承 YOURGRAMMARBaseVisitor 或 YOURGRAMMARBaseListener。

    【讨论】:

    • 为什么在我在问题中展示的方法中使用它?感谢您的帮助:)
    • 在这种情况下,accept 方法是访问者访问他们的孩子 e1 和 e2 的方式。这是题外话,因为它与 ANTLR 无关。
    猜你喜欢
    • 2013-06-02
    • 1970-01-01
    • 2018-09-04
    • 1970-01-01
    • 2016-11-08
    • 2011-07-10
    • 2013-09-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多