问题描述
所以我试图在 java 中为我的 ANTLR4 解析器创建一个启动器,当我尝试运行我的代码时出现“不兼容的类型”错误:
import org.antlr.runtime.*;
import java.io.IOException;
import static org.antlr.v4.runtime.CharStreams.fromFileName;
public class TLLauncher {
public static void main(String[] args) {
try{
String inp = "input.txt";
org.antlr.v4.runtime.CharStream in = fromFileName(inp);
gramLexer lexer = new gramLexer(in);
CommonTokenStream tokens = new CommonTokenStream(lexer); // ###HERE
gramParser parser = new gramParser(tokens); // ###HERE
parser.r();
} catch (IOException e) {e.printstacktrace();}
}
}
我收到以下错误。
incompatible types: gramLexer cannot be converted to org.antlr.runtime.TokenSource
incompatible types: org.antlr.runtime.CommonTokenStream cannot be converted to org.antlr.v4.runtime.TokenStream
有人可以向我解释我做错了什么吗?
另外,既然我们在这里,你能给我一个学习 ANTRL 的好资源吗?我需要以某种方式制作输入代码的 AST 并将其转换为另一种语言,但我在甚至无法理解 ANTLR 的工作原理以及如何完成它时遇到了麻烦。
解决方法
导入 org.antlr.runtime.*;
您导入了错误的运行时。 org.antlr.runtime
是 ANTLR3 运行时。 ANTLR4 运行时位于 org.antlr.v4.runtime
(您已经从中使用了 CharStream
和 CharStreams
,但未使用 CommonTokenStream
)。