Preprocessor Macros Parser


In fact, I am confused in very basic things about clang: I have found no way to get the macro definition, make some magic with it and then make some magic on calling macroses.

For instance, for code:
#define sum(a, b) (a) + (b)
int main() { sum(1, 2); }
I want to do something on macro sum initialization and on macro sum call processing (in fact, at this moment I will evaluate the macros by myself and then push “3” instead of “(1) + (2)”).

So, generally speaking, I need to replace the clang preprocessor in the easiest way if possible (I still hope that it is possible to make it as an extension without changing anything in clang code).

I hone, someone can give me an advice how to implement it!



I must admit I am not an expert on how clang implements preprocessing, but my experience with another C-like compiler tells me that preprocessing is usually very tightly coupled into the lexer. Clang’s lexer claims to be highly optimized, so I think you will find the same tight coupling there. Hence, I doubt that you can achieve what you need without changing any of clang’s source code.

That said, a minimally invasive approach might be to derive your own preprocessor class from clang’s “Preprocessor” class and overload the methods you would like to modify (e.g. “HandleDefineDirective”). For this to work, you will have to make the overloaded methods virtual in the base class, i.e. In the “Preprocessor” class. Does this sound like a sensible approach?