简体   繁体   中英

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.

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.

  • antlr is an alias to java org.antlr.v4.Tool
  • grun is an alias to java org.antlr.v4.gui.TestRig .

When I run antlr TestParser.g4 && javac *.java the parser code gets generated and compiled.

When I run grun TestParser testRule -gui I get the error:

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:

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 ?

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.

Note: When using separated lexer and parser it's expected that the lexer ends on Lexer and the parser ends on Parser . The common part of the files is the name of grammar. Ie TestLexer and TestParser -> Test is the name of the grammar.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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