Rewriter: expand macro to definition

Hi all,

I am currently working on a source-to-source transformation using libtooling/clang. I would like to selectively expand some macros to their definition during rewrite. Possible recursion and other macros in the expansion shall be expanded as well. e.g.

#define FOO( name, line ) name##line
#define BAR( name, line ) FOO( name, line )
#define BAZ( name ) BAR( name, __LINE__ )

such that

BAZ( test )

at line 42 can be expanded to the string "test42". How can I do that? I found an old, similar question on the clang list, which never received a proper answer[1]. It cannot be that hard, can it?

Thank you!



I was looking into this last week when investigating “expand macro” & “preprocess” actions for Clang’s new refactoring engine. I came to the conclusion that the best way to solve this full preprocessing issue is to re-preprocess the whole translation unit, use a custom PP frontend action, and call a modified version of clang::DoPrintPreprocessedInput which implements the -E mode. The modification in DoPrintPreprocessedInput boiled down to a source range constraint that controlled which tokens should be printed to ensure that only the relevant tokens (that actually make-up the BAZ(test) expansion) are printed instead of the whole preprocessed source. Btw, would you be interested in working on a patch for Clang that implements this modification if you decide to use this approach?

I hope this helps,

There is a code in clang::html::HighдightMacros() routine (clang/lib/Rewrite/HTMLRewrite.cpp ) which does similar thing. I borrowed the code and slightly modified it to Lex exact macro invocation (opposed to entire file in original code) for my in-house indexing c++ indexing tool.
The only issue I met thus far is lost formatting in multi-line macros (inability to split lines by trailing '\'). I am now trying to use clang::format to re-format expansion, but it strangely doesn't work for me in release compilation (though works fine in debug).