3

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.

aravindkanna
  • 663
  • 1
  • 7
  • 25
  • 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. Jul 31 '17 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" https://stackoverflow.com/a/5834775/120163 – Ira Baxter Aug 16 '17 at 01:19

2 Answers2

1

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.).

Mike Lischke
  • 48,925
  • 16
  • 119
  • 181
0

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.

somename
  • 19
  • 2
  • It might be worth emphasizing more strongly that any specific AST still represents a program's syntax in the language it was written in, and thus cannot be directly converted to another language – Hurricane Hamilton Aug 15 '17 at 18:43
  • 2
    If you design your ASTs properly, they carry enough information to regenerate equivalent source text for the language represented by the AST nodes. Converting an AST for one language to another is possible, but that's really code code migration, not regenerating the source text. For more details on why this hard see https://stackoverflow.com/questions/3455456/what-kinds-of-patterns-could-i-enforce-on-the-code-to-make-it-easier-to-translat/3460977#3460977 – Ira Baxter Aug 16 '17 at 01:24