ANTLR:找不到符号

ANTLR: Could not find symbol

我有一个名为 "Test.g4" 的 ANTLR 项目,我使用 antlrworks2 创建的文件没有任何问题:Test.tokens、TestBaseListner.java、TestLexer.java、TestLexer.tokens , TestListener.java 和 TestParser.java.

现在我想在我的程序中使用语法 Test.java:

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

public class Test {
    public static void main(String[] args) throws Exception {
        // create a CharStream that reads from standard input
        ANTLRInputStream input = new ANTLRInputStream(System.in);

        // create a lexer that feeds off of input CharStream
        TestLexer lexer = new TestLexer(input);

        // create a buffer of tokens pulled from the lexer
        CommonTokenStream tokens = new CommonTokenStream(lexer);

        // create a parser that feeds off the tokens buffer
        TestParser parser = new TestParser(tokens);

        ParseTree tree = parser.init(); // begin parsing at init rule
        System.out.println(tree.toStringTree(parser)); // print LISP-style tree
    }
}

当我尝试用 "javac -classpath /path/java2/antlr-4.4-complete.jar Test.java" 编译它时,我得到了这个错误:

Test.java:19: error: cannot find symbol
        TestLexer lexer = new TestLexer(input);
        ^
  symbol:   class TestLexer
  location: class Test
Test.java:19: error: cannot find symbol
        TestLexer lexer = new TestLexer(input);
                                        ^
  symbol:   class TestLexer
  location: class Test
Test.java:25: error: cannot find symbol
        TestParser parser = new TestParser(tokens);
        ^
  symbol:   class TestParser
  location: class Test
Test.java:25: error: cannot find symbol
        TestParser parser = new TestParser(tokens);
                                          ^
  symbol:   class TestParser
  location: class Test
4 errors

谢谢!

您需要构建并导入 ANTLR 生成的词法分析器和解析器。为此,您需要:

  1. 使用您的主要方法将导入语句添加到文件
  2. 将 ANTLR 生成的 classes 放入您的导入语句中的包中
  3. 使用您的主要方法构建生成的 classes 和 class

TestLexer.javaTestParser.java 也应该在同一命令中与 Test.java 一起编译,否则编译器将不知道在哪里寻找它们的二进制文件。尝试按如下方式调用 javac

javac -classpath /path/java2/antlr-4.4-complete.jar *java

或手动传递所有文件:

javac -classpath /path/java2/antlr-4.4-complete.jar Test.java TestLexer.java TestParser.java