I've been using ANTLR4
to parse a piece of Java
or C++
code. I'm planning to apply transformations on the Tree
in order to dump the source code out of the Tree
again.
For the latter I barely found any useful information with code examples so I wrote a simple recursive method as follows:
private String toSourceCode(Tree tree, StringBuilder stringBuilder)
{
int childCount = tree.getChildCount();
for (int childIndex = 0; childIndex < childCount; childIndex++)
{
Tree child = tree.getChild(childIndex);
if (child instanceof TerminalNode)
{
TerminalNode parserRuleContext = (TerminalNode) child;
String text = parserRuleContext.toString() + " ";
stringBuilder.append(text);
}
toSourceCode(child, stringBuilder);
}
String recoveredSourceCode = stringBuilder.toString().trim();
return recoveredSourceCode.replace("<EOF>", "");
}
Note that I do not care to lose comments or the formatting. Producing compilable code is all what matters. Is my solution fool-proof? I heard that StringTemplate
can be used to generate the source code as well but I did not find any code examples. How would that work and would it be preferable over my solution above?