有没有更好的方法来检查 child 节点的类型并相应地返回?

Is there a better way to check the type of a child node and returning accordingly?

我正在使用 ANTLR 开发一种小型语言。我有一个解释器 class 准备好了,它能够识别和执行这种语言的任何语法树。不幸的是,ANTLR 生成解析树。因此,我使用访问者模式将解析树转换为语法树。

给定以下规则,

<Factor> = <Identifier> | <Literal>

我的访客 class 中的 visitFactor(FactorContext ctx),应该 return 文字或标识符....

 public Statement visitFactor(FactorContext ctx) {
        if (ctx.ID() != null)
            return new Identifier(ctx.ID().getText());
        else if (ctx.literal() != null)
            return visit(ctx.literal());
        return null; // should never happen, factor *must* be either id or literal.
    }

我的问题如下。有没有更好的方法来了解 Factor 的 child 类型?或者我是否必须使用 if-statements,检查每个 child 是否是 non-null?

您可以这样使用 alternative labels

factor
 : ID      #factorID
 | literal #factorLiteral
 ;

然后将生成以下方法,而不是单个 visitFactor(...):

public Statement visitFactorID(FactorIDContext ctx) {
   return new Identifier(ctx.ID().getText());
}

public Statement visitFactorLiteral(FactorLiteralContext ctx) {
   return visit(ctx.literal());
}