I understand that any source code can be converted to an AST. Now I want to convert that AST back to source code, but language independent. Is there any tool that helps me out?
By language independent I specifically mean for python and java.
- If you are not reverting the AST back to the source from which it came, what would be the target syntax if not a known language?Frank C.– Frank C.2017-07-31 10:57:39 +00:00Commented Jul 31, 2017 at 10:57
- You can only regenerate the text if your AST builder leaves enough information in the AST to do so. ANTLR mostly doesnt (e.g, what is the display radix of that number?) If you want to know what it takes to do this, see my answer to "Compiling an AST back to source code" stackoverflow.com/a/5834775/120163Ira Baxter– Ira Baxter2017-08-16 01:19:48 +00:00Commented Aug 16, 2017 at 1:19
2 Answers
What you have in mind is a source code translator and it involves a lot more than just generation of some code from the parse tree (ANTLR4 doesn't create an AST btw.). Usually such a translator converts the parse tree into an intermediate representation which abstracts the various language constructs and then uses that to generate code in the target language (with a lot of special handling for everything from the source language not available in the target language, optimization etc.).
Comments
you cannot convert an AST back to source code according to my opinion. Because the ast generated may be of any language and you cannot convert that ast back to any language you want.