It's not trivial and it looks like LexerInterpreter and ParserInterpreter could help here (I haven't had the opportunity to test this myself). There are a number of tests in the Java tools test that show how to use it, e.g.:
**
* This is a regression test for antlr/antlr4#461.
*
https://github.com/antlr/antlr4/issues/461
*/
@Test public void testLeftRecursiveStartRule() throws Exception {
LexerGrammar lg = new LexerGrammar(
"lexer grammar L;\n" +
"A : 'a' ;\n" +
"B : 'b' ;\n" +
"C : 'c' ;\n" +
"PLUS : '+' ;\n" +
"MULT : '*' ;\n");
Grammar g = new Grammar(
"parser grammar T;\n" +
"s : e ;\n" +
"e : e MULT e\n" +
" | e PLUS e\n" +
" | A\n" +
" ;\n",
lg);
testInterp(lg, g, "e", "a", "(e a)");
testInterp(lg, g, "e", "a+a", "(e (e a) + (e a))");
testInterp(lg, g, "e", "a*a", "(e (e a) * (e a))");
testInterp(lg, g, "e", "a+a+a", "(e (e (e a) + (e a)) + (e a))");
testInterp(lg, g, "e", "a*a+a", "(e (e (e a) * (e a)) + (e a))");
testInterp(lg, g, "e", "a+a*a", "(e (e a) + (e (e a) * (e a)))");
}
ParseTree testInterp(LexerGrammar lg, Grammar g,
String startRule, String input,
String expectedParseTree)
{
LexerInterpreter lexEngine = lg.createLexerInterpreter(new ANTLRInputStream(input));
CommonTokenStream tokens = new CommonTokenStream(lexEngine);
ParserInterpreter parser = g.createParserInterpreter(tokens);
ParseTree t = parser.parse(g.rules.get(startRule).index);
System.out.println("parse tree: "+t.toStringTree(parser));
assertEquals(expectedParseTree, t.toStringTree(parser));
return t;
}
That looks simple, but the tricky part is that LexerGrammar and Grammar classes are not part of the runtime. They are needed to generated the ATN required by the interpreters.
Mike
--
www.soft-gems.net