Lei Yu Lei Yu - 6 months ago 53
C++ Question

is there a way to get source code with macro expanded using Clang API

For example, I got following code.

#define ADD(x, y) (x) + (y)

int func(int i, int j)
return ADD(i, j);

The clang SourceManager can be used to get source code of the function func. and what I got is
{ return ADD(i, j)
. is there any way that I can get the source code as
{ return (i) + (j); }

Answer from keyboardsmoke: tested

Can simply use Decl::print() method, or keyboardsmoke's code in this answer, actually, Decl::print() calls methods of DeclPrinter.

Stmt has a different method called printPretty() that can print out the source code of a statement with macro expanded.


An easy way is to use the 'print' function inside of Decl, the pretty printer will expand all macros.

You can also print statements, so if you want that specific statement that is being returned you should be able to do something similar.

Decl::print also refers to "DeclPrinter" which allows you to print any decl type (output to raw_ostream)

std::string s;
llvm::raw_string_ostream sos(s);
PrintingPolicy pp(compiler->getLangOpts());
DeclPrinter DP(sos, pp, 0 /* indent */, true /* PrintInstantiation */);

Will place the text for "functionDecl" into "std::string s"