Reputation: 11
I'm trying ANTLR 4.8. I'm having problems coding a correct main file that calls to the lexer and parser classes.
After correctly parsing my ANTLR g4 file (getting all files and classes provided by antlr) I've coded the following main java file:
import java.io.*;
import org.antlr.v4.runtime.TokenStream;
import org.antlr.runtime.*;
import org.antlr.runtime.TokenSource;
import org.antlr.v4.runtime.CharStream;
import org.antlr.v4.runtime.CharStreams;
public class example3Ppal {
public static void main(String[] args){
try{
CharStream input = CharStreams.fromFileName(args[0]);
//Create a Lexer with the previously created CharStream
example3Lexer mylexer = new example3Lexer(input);
//Conecting lexer and parser
CommonTokenStream tokens = new CommonTokenStream((TokenSource) mylexer);
example3Parser myparser = new example3Parser((TokenStream) tokens);
myparser.operation();
} catch (java.lang.RuntimeException re) {
System.out.println(re.getMessage());
} catch (IOException e) {
e.printStackTrace();
}
}
}
I started from a former main file, so I had to change from ANTLRFileStream and such to CharStreams. Everything seems to work until I try to connect lexer and parser. Following examples provided in ANTLR website a lexer object is enough to create a "CommonTokenStream" object that, in addition, should be enough to create a parser object.
Well I firstly tried without any cast but both, eclipse and NetBeans, ask me to cast "mylexer" and "tokens" objects. I don't undestand why, because lexer superclass implements "TokenSource" interface, as well as "CommonTokenStream" does with "TokenStream" interface. In addition both environments allow me to use a "CommonTokenStream" constructor without any attributes while this constructor doesn't exist in the ANTLR documentation
I've read many comments here about similar questions, but I haven't found any that could be applied to my situation.
The result is that it compiles but when I run the program I receive the following error message: "mylexer cannot be cast to org.antlr.runtime.TokenSource"
There are no prior installations of ANTLR in my computer, the "antlr-4.8-complete" jar file is correctly included as an external jar lib in the projects and it is also included in the CLASSPATH environment variable. I don't know why what should work isn't working for me, could somebody help me? I'm begining to think about reinstalling java, eclipse, netBeans and ANTLR.
Thanks in advance.
Upvotes: 1
Views: 1191
Reputation: 370397
You're mixing imports from ANTLR 4 and ANTLR 3. Any import that doesn't have v4
in it, is importing classes from ANTLR 3 (which is possible because the ANTLR 4 jar included ANTLR3 since ANTLR 4 uses ANTLR 4).
If you switch all your imports to org.antlr.v4
and remove the casts, the code should work.
Upvotes: 2