Antlr4 解析器中缺少变量

Missing variable in Antlr4 parser

我正在尝试为使用 Antlr4 的语言构建一个符号 table。我的语法文件中有以下规则。

/* Global String Declaration */
//string_decl       : STRING id ASSIGN str SEMICOLON ;
string_decl returns [StrEntry s] : STRING id ASSIGN ex=str SEMICOLON 
           { $s = new StrEntry(); s.addID($id.text); s.addValue($ex.text);} ;

我还创建了一个 StrEntry class(虚拟实现)

public class StrEntry{


    String value;
    String id;
    String type;


    void addID(String x){
        id = x;
    }

    void addValue(String c){
        value = c;
    }

}

当我编译 (javac *.java) 时,出现以下错误:

MicroParser.java:382: error: cannot find symbol
                         ((String_declContext)_localctx).s =  new   StrEntry(); s.addID((((String_declContext)_localctx).id!=null?  _input.getText(((String_declContext)_localctx).id.start,    ((String_declContext)_localctx).id.stop):null));    s.addValue((((String_declContext)_localctx).ex!=null?_input.getText(((String_declContext)_localctx).ex.start,   ((String_declContext)_localctx).ex.stop):null));
                                                                                                                                                                                                                                        ^
  symbol:   variable s
  location: class MicroParser

它说缺少 StrEntry 类型的变量 s,但我已经在我的语法文件中定义了它。我认为在 MicroParser.java 文件中编辑它不是一个好主意,因为它是由 Antlr4 生成的。

我该怎么办?

$s = new StrEntry(); s.addID($id.text); s.addValue($ex.text)

此处您同时使用了 $s(在生成的 Java 代码中将被转换为 _localctx.s)和 s(将仅保留 s).后者是编译器找不到的符号,因为该块中没有定义该名称的变量。

换句话说,你只需要始终如一地使用 $s 而不是 s 就可以了。