为什么在 ANTLRv4 中尝试将词法分析器作为 CommonTokenStream 的输入时出现错误
Why do I get an error when trying to give a lexer as input of CommonTokenStream in ANTLRv4
所以我试图在 java 中为我的 ANTLR4 解析器创建一个启动器,当我尝试 运行 我的代码时出现 'incompatible types' 错误:
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 的工作原理以及我如何完成它时遇到了麻烦。
import org.antlr.runtime.*;
您导入了错误的运行时。 org.antlr.runtime
是 ANTLR3 运行时。 ANTLR4 运行时存在于 org.antlr.v4.runtime
中(您已经从中使用 CharStream
和 CharStreams
,但不是 CommonTokenStream
)。
所以我试图在 java 中为我的 ANTLR4 解析器创建一个启动器,当我尝试 运行 我的代码时出现 'incompatible types' 错误:
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 的工作原理以及我如何完成它时遇到了麻烦。
import org.antlr.runtime.*;
您导入了错误的运行时。 org.antlr.runtime
是 ANTLR3 运行时。 ANTLR4 运行时存在于 org.antlr.v4.runtime
中(您已经从中使用 CharStream
和 CharStreams
,但不是 CommonTokenStream
)。