简体   繁体   English

Antlr4解析器中缺少变量

[英]Missing variable in Antlr4 parser

I am trying to build a symbol table for a language using Antlr4. 我正在尝试使用Antlr4构建一种语言的符号表。 I have the following rule in my grammar file. 我的语法文件中有以下规则。

/* 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);} ;

I also created a StrEntry class (a dummy implementation) 我还创建了StrEntry类(虚拟实现)

public class StrEntry{


    String value;
    String id;
    String type;


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

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

}

When I compile ( javac *.java ) I get the following error: 当我编译( 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

It says variable s of type StrEntry is missing, but I have defined it in my grammar file. 它说缺少StrEntry类型的变量s,但是我已经在语法文件中定义了它。 I don't think editing it in MicroParser.java file is a good idea as it was generated by Antlr4. 我认为在MicroParser.java文件中对其进行编辑不是一个好主意,因为它是由Antlr4生成的。

What should I do? 我该怎么办?

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

Here you're using both $s (which will be translated to _localctx.s in the generated Java code) and s (which will remain just s ). 在这里,您同时使用了$s (将在生成的Java代码中转换为_localctx.s )和s (将仅保留s )。 The latter is the symbol that the compiler can't find because there is no variable with that name defined in that block. 后者是编译器找不到的符号,因为在该块中没有定义该名称的变量。

In other words, you just need to consistently use $s instead of s and it will work fine. 换句话说,您只需要始终使用$s而不是s ,它将可以正常工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM