SourceLocation -> MacroDefinition(Record?)

Hi all,

For IWYU, we can usually make better suggestions if we know whether a
use happens inside a macro or not.

I should be able to use SourceLocation::isMacroID to ask whether I'm
in *a* macro, but is there a way to go from there to *which* macro?
I'm guessing that's represented by the new MacroDefinition class.

I've toyed with the idea of recording all macro definitions in a
PPCallbacks implementation and building a reverse lookup table from
location to macro definition, but I figured Clang might already have
that. Does it?

- Kim

Yes, but it depends on what you want. You can ask the SourceManager for
information about a macro SourceLocation to find where the macro was
defined and where it was expanded. In common cases you can get the name of
the macro this way, but if the name of the macro was itself produced by
macro expansion, it's tricky to extract that information from the

If you want more information, one option would be to use
clang::PreprocessingRecord. This is a prebuilt implementation of what you
mention above: a PPCallbacks implementation that tracks the macro expansion

I honestly can't remember exactly what I want anymore :-), it's been a
few months since I worked on the problematic case, but the
PreprocessingRecord looks interesting.

I think I should be able to use that as a backend for detecting macro
uses more easily and correctly than a custom PPCallbacks, and it looks
like it holds the information necessary to map decl/type uses to the
right file (for some value of right).

Appreciate it, thanks!

- Kim

After some recent hacking, I now know what I'm looking for:

I have a Decl and a location where it's used.

If that location is in a macro, we want to attribute the use to the
file containing the macro, unless
  a) there is a prior forward-declaration of the Decl in the macro file
  b) the use-location points to a macro-argument

So for example:

OK, so I've come up with this snippet that appears to do what I want: