简体   繁体   English

在分离的语法和词法分析器上运行`TestRig`导致`java.lang.ClassCastException`或`无法将测试加载为词法分析器或解析器

[英]Running `TestRig` on separated grammer and lexer results in `java.lang.ClassCastException` or `Can't load Test as lexer or parser`

I have a separated parser and lexer grammar and want to run org.antlr.v4.gui.TestRig to debug/test my grammar. 我有一个单独的解析器和词法分析器语法,并希望运行org.antlr.v4.gui.TestRig来调试/测试我的语法。

My lexer grammar start with: 我的词法分析器语法从:

lexer grammar TestLexer;

IDS: [a-zA-Z];

WS: [ \t];
NL: [\r?\n];

...

and my parser grammar start with: 我的解析器语法以:

parser grammar TestParser;
options { tokenVocab=TestLexer; }

testRule: WS* IDS+ NL;

...

My classpath env variable points to complete antlr.jar and current directory. 我的classpath env变量指向完成antlr.jar和当前目录。

  • antlr is an alias to java org.antlr.v4.Tool antlrjava org.antlr.v4.Tool的别名
  • grun is an alias to java org.antlr.v4.gui.TestRig . grunjava org.antlr.v4.gui.TestRig的别名。

When I run antlr TestParser.g4 && javac *.java the parser code gets generated and compiled. 当我运行antlr TestParser.g4 && javac *.java ,会生成并编译解析器代码。

When I run grun TestParser testRule -gui I get the error: 当我运行grun TestParser testRule -gui我得到错误:

Exception in thread "main" java.lang.ClassCastException: class TestParser
        at java.lang.Class.asSubclass(Class.java:3404)
        at org.antlr.v4.gui.TestRig.process(TestRig.java:135)
        at org.antlr.v4.gui.TestRig.main(TestRig.java:119)

And when I run grun Test testRule -gui I get the error: 当我运行grun Test testRule -gui我得到错误:

Can't load Test as lexer or parser

I don't have any problems when using a combined grammar. 使用组合语法时我没有任何问题。

What's missing in order to run TestRig ? 运行TestRig缺少什么?

When using separated lexer and parser you have to generate the code for the lexer and parser. 使用分离的词法分析器和解析器时,您必须为词法分析器和解析器生成代码。 This is not done automatically by generating the code for the parser alone. 这不是通过单独生成解析器的代码自动完成的。

Execute: 执行:

antlr TestLexer.g4
antlr TestParser.g4
javac *.java

After generating the code for both (lexer and parser) you have to run: 为两者(词法分析器和解析器)生成代码后,您必须运行:

grun Test -gui testInput.txt

where testInput.txt contains some test input to parse. 其中testInput.txt包含一些要解析的测试输入。

Note: When using separated lexer and parser it's expected that the lexer ends on Lexer and the parser ends on Parser . 注意:当使用分离的词法分析器和解析器时,预期词法分析器在Lexer结束, ParserParser结束。 The common part of the files is the name of grammar. 文件的常见部分是语法名称。 Ie TestLexer and TestParser -> Test is the name of the grammar. TestLexerTestParser - > Test是语法的名称。

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

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