首页 > 解决方案 > 找不到 Parser.varContext

问题描述

试图遵循权威 antlr 4 参考中的示例并停留在第 147 页,我无法找到我的 java 语法对 parser.VarContext 的引用。** - 我需要获取 ID,但我找不到 VarContext,只有一个 VarLocalContext没有身份证。我错过了定义中的某些内容吗?我验证了该类正在生成,所以它有些奇怪。

我已经将那些让我遇到麻烦的行加粗了,但是 VariableDeclaratorContext 确实存在,但与我需要的不匹配。

我的来源如下。

enter code here

import org.antlr.v4.runtime.tree.ParseTreeProperty;



    public class RefPhase<CatchesContext> extends JavaBaseListener {
    ParseTreeProperty<Scope> scopes;
    GlobalScope globals;
    Scope currentScope; // resolve symbols starting in this scope

    public RefPhase(GlobalScope globals, ParseTreeProperty<Scope> scopes) {
    this.scopes = scopes;
    this.globals = globals;
    }
    @SuppressWarnings("unchecked")
    public void enterFile(CatchesContext ctx) {
        currentScope = (Scope) globals;
    }

    public void enterCompilationUnit(JavaParser.CompilationUnitContext ctx) {
        currentScope = scopes.get(ctx);
    }
    public void exitCompilationUnit(JavaParser.CompilationUnitContext ctx) {
        currentScope = currentScope.getEnclosingScope();
    }

    public void enterBlock(JavaParser.BlockContext ctx) {
        currentScope = scopes.get(ctx);
    }
    public void exitBlock(JavaParser.BlockContext ctx) {
        currentScope = currentScope.getEnclosingScope();
    }

**public void exitVar(JavaParser.VariableDeclaratorContext ctx) {
    String name = ctx.ID().getSymbol().getText();**
    Symbol var = currentScope.resolve(name);
    if ( var==null ) {
        CheckSymbols.error(ctx.ID().getSymbol(), "no such variable: "+name);
    }
    if ( var instanceof FunctionSymbol ) {
        CheckSymbols.error(ctx.ID().getSymbol(), name+" is not a variable");
    }
}

public void exitCallContext(JavaParser.CatchesContext ctx) {
    // can only handle f(...) not expr(...)
    String funcName = ctx.ID().getText();
    Symbol meth = ((Object) currentScope).resolve(funcName);
    if ( meth==null ) {
        CheckSymbols.error(ctx.ID().getSymbol(), "no such function: "+funcName);
    }
    if ( meth instanceof VariableSymbol ) {
        CheckSymbols.error(ctx.ID().getSymbol(), funcName+" is not a function");
    }
 }
 }

标签: antlr4javaparser

解决方案


推荐阅读