1
我創建了antlr4語法文件「Jay.g4」,並生成了我編譯創建「JayLexer.class」和「JayParser.class」的「JayLexer.java」和「JayParser.java」。 現在的問題是:如何使用java生成的源代碼?我使用NetBeans IDE,我不知道如何將詞法分析器和分析器集成到我的項目中,並使它們正常工作。如何使用antlr生成的解析器和詞法分析器?
我創建了antlr4語法文件「Jay.g4」,並生成了我編譯創建「JayLexer.class」和「JayParser.class」的「JayLexer.java」和「JayParser.java」。 現在的問題是:如何使用java生成的源代碼?我使用NetBeans IDE,我不知道如何將詞法分析器和分析器集成到我的項目中,並使它們正常工作。如何使用antlr生成的解析器和詞法分析器?
如果您打算進一步冒險,我建議The Definitive Antlr 4 Reference。從Antlr documentation,您可以下載/看到一些示例代碼,包括這個:
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));
如果你有類JayLexer
和JayParser
,但是,你寧願寫類似:
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
然後請根據需要使用分析樹,例如實施JayBaseListener
或JayBaseVisitor
的類。檢查一個給定的鏈接瞭解更多信息。