Clang Checker for Import Statements

I want to write a checker that will analyze the #import statements within
Objective-C files and issue a warning when a certain file is included in the
import directive. For example if I have:

#import "x.h"

and x.h is the file name I am looking for then the checker would issue a
warning that x.h is being used when it comes across this import statement.

What would be the best way to go about doing this? Using the
InclusionDirective class?


As I understand it, #import is completely taken care of in the preprocessing won't see it in the AST. That means that writing a static analysis checker won't work.

If you really wanted to do this in code, you'd probably be modifying code in the Lex library (which I'm not so familiar with). But an easier way to solve your problem might be to just use the #warning extension: if you put a #warning in x.h, you'll get a warning whenever x.h is included. If you don't have control over x.h, or you want the warning every time x.h is referenced, you could make a wrapper that looks like this:

#warning "Use of x.h"
#import "x.h"

...and then *#include* your wrapper. Admittedly, that requires a little more intrusion into your project, but it /doesn't/ require a custom compiler build. :slight_smile:


This information can possibly be groveled through in the SourceManager (so it could be a static analysis check, at least partially), but I don't think we get SourceLocations when we include (say) an empty header or we #include the same header again that we know has include guards.

If you don't want to touch the code itself, you can still go with
Jordy's solution below and just update the include paths. You can
perhaps even avoid touching makefiles if you use environment