I created the antlr4 grammar file Jay.g4
and generated the JayLexer.java
and JayParser.java
. I compiled these to create JayLexer.class
and JayParser.class
.
My question is: how do I use those generated sources with Java? I am using the NetBeans IDE and I don't know how to integrate the lexer and parser into my project and make them work correctly.
If you're going to venture further, I recommend The Definitive Antlr 4 Reference. From the Antlr documentation, you can download/see some sample code, including this:
final LexerGrammar lg = (LexerGrammar) Grammar.load(lexerGrammarFileName);
final Grammar pg = Grammar.load(parserGrammarFileName, lg);
ANTLRFileStream input = new ANTLRFileStream(fileNameToParse);
LexerInterpreter lexEngine = lg.createLexerInterpreter(input);
CommonTokenStream tokens = new CommonTokenStream(lexEngine);
ParserInterpreter parser = pg.createParserInterpreter(tokens);
ParseTree t = parser.parse(pg.getRule(startRule).index);
System.out.println("parse tree: " + t.toStringTree(parser));
If you have the classes JayLexer
and JayParser
, however, you'd rather write something like:
ANTLRFileStream input = new ANTLRFileStream(fileName); // a character stream
JayLexer lex = new JayLexer(input); // transforms characters into tokens
CommonTokenStream tokens = new CommonTokenStream(lex); // a token stream
JayParser parser = new JayParser(tokens); // transforms tokens into parse trees
ParseTree t = parser.your_first_rule_name(); // creates the parse tree from the called rule
Then use the parse tree as you wish, for example a class implementing the JayBaseListener
or JayBaseVisitor
. Check one of the given links for more information.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With