0

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?

BullyWiiPlaza
  • 17,329
  • 10
  • 113
  • 185
  • 1
    It's a bit odd that you want to generate the same code (sans correct whitespace) which you just parsed. Why not take the original code then? Did you change the parse tree? Anyway, the approach should work ok, but keep in mind the parse tree can be deeply nested, so that your recursive approach might overflow the stack. Better use the tree visitor to construct your finaly code. – Mike Lischke Aug 26 '19 at 06:51
  • @MikeLischke: Yeah, I would modify the parse tree and then dump it back out. Thanks for the visitors for bigger trees, I agree. – BullyWiiPlaza Aug 26 '19 at 16:08

0 Answers0