2

I have an AST that has been parsed by Clang. How do I generate the equivalent C++ code for the AST? I would like the result as an std::string and formatted in a readable way.

Another way of putting this question is: can I use clang-format like a library?

For example, the AST of this source code:

 int  main()  {

         int   y  = 4;
       int  x =  y+ 7;  return  0;}

... might become this std::string:

int main()
{
    int y = 4;
    int x = y + 7;
    return 0;
}

The ideal API would be something like:

std::string deparse(clang::TranslationUnitDecl* root) 
sdgfsdh
  • 33,689
  • 26
  • 132
  • 245
  • #includes are always processed before LLVM gets code, so you will actually get the preprocessed file, which includes the contents of iostream (and whatever headers it itself includes) – Paul Stelian Jul 05 '16 at 18:16
  • @PaulStelian That's OK; I would like to see the preprocessed code. – sdgfsdh Jul 06 '16 at 10:05
  • @PaulStelian But isn't clang-format able to handle includes? I am working at a Clang level, before any LLVM is generated. – sdgfsdh Jul 06 '16 at 10:17
  • 1
    Not for Clang, but a similar tool, our DMS Software Reengineering Toolkit, provides exactly fully scriptable parsing and unparsing capability for many languages, including C++. (It can even retain almost all preprocessor directives). I'll note that regenerating source code from an AST is harder than it looks: see my SO answer on how to build a prtettyprinter: http://stackoverflow.com/questions/5832412/compiling-an-ast-back-to-source-code/5834775#5834775 – Ira Baxter Jul 06 '16 at 10:20
  • @sdgfsdh The thing is that Clang gets the already preprocessed files, where includes and preprocessor directives (except Pragma) have already been processed and are no longer present. – Paul Stelian Jul 06 '16 at 11:42

0 Answers0