A checker that checks macro calls

Hi,

I’m currently trying to implement a checker that needs to know when a certain macro is invoked.

For example, if I had something like:
#define MY_MACRO(x) …

I would want to check if the statement is MY_MACRO and then inspect its argument.

I see that with checkPreStmt or checkPostStmt. I can check if it is a macro, via getLocStart and isMacroID. Is there a way to get the name of the macro and it’s argument (if it has one)?
I see that MacroInfo could be used to get the args possibly, but it doesn’t seem to give me the name.

Thanks!

Sincerely,
Todd Nowacki

You can get the name of the macro by looking into the source buffer; get
the expansion location and use something like Lexer::getRawToken to pull
out the name.

-Eli

Err, actually you probably want Lexer::getSpelling(), which returns
something a bit easier to work with.

-Eli

Hi,

I'm currently trying to implement a checker that needs to know when a certain macro is invoked.

For example, if I had something like:
#define MY_MACRO(x) ...

I would want to check if the statement is MY_MACRO and then inspect its argument.

I see that with checkPreStmt or checkPostStmt. I can check if it is a macro, via getLocStart and isMacroID. Is there a way to get the name of the macro and it's argument (if it has one)?
I see that MacroInfo could be used to get the args possibly, but it doesn't seem to give me the name.

Starting from the source location of the statement you could use Preprocessor::getImmediateMacroName() to get the macro name.
You could also see if the location came from the macro argument via SourceManager::isMacroArgExpansion().

Todd,

Since you say “when a certain macro is invoked”, could this be a case for deriving a class from PPCallbacks which overrides MacroExpands to watch for instances of the macro? You call the Preprocessor’s addPPCallbacks function to hook up an instance of your callbacks class.

-John

Right now, I’ve been using checkPostStmt and then using the source location of the expression to check isMacroId() and using the CheckerContext function getMacroNameOrSpelling. The reason being that I need the SymbolRef for the argument to the macro, and I can’t see a way to get that via a MacroArg or Token (which is what I get if I used the Preprocessor).

The PPCallback seems much cleaner; if there was a way to get a SymbolRef fromt that method, that would be awesome.

-Todd

Todd,

did you suceed with building a Checker for Macros and their arguments, and
if yes, can you share how you did it? I'm currently facing the same problem,
my code uses a lot of macro calls, and basing a checker on them is much
easier than trying to re-assemble them on a function call level, but I am a
bit lost in the clang API.

Many Thanks
Eph

Todd Nowacki wrote