How to determine if a raw_id token is a macro name?

Hi Team,

Preprocessor::isMacroDefined seems to be what I want, but how can I
access the active preprocesor from inside a clang-tidy check?

Currently I have a check that walks over a declaration string with the
Lexer. A bug was filed that this check had a negative interaction
with macros (no surprise). I've got a hacked up solution that passes
my test cases, but it would be really nice to know if a raw_id token I
just encountered while lexing the declaration is the name of a macro.

For context, see:
Lexing state machine
<llvm-project/RedundantVoidArgCheck.cpp at main · llvm/llvm-project · GitHub;
bug
<Issues · llvm/llvm-project · GitHub;

Thanks,

-- Richard

I believe the best you can do is to convert the string to an IdentifierInfo and access hadMacroDefinition:

bool FooMaybeMacroName = FooII.hadMacroDefinition();

This won’t be perfect — it won’t tell you whether Foo was defined at the particular SourceLocation you are interested in, only whether at some point in the TU a macro with that name was defined.

It would be nice to be able to test FooII.hasMacroDefinition() instead, but the problem mentioned in the other thread rears its head here too: the AST matching on which clang tidy depends is all done during HandleTranslationUnit, after all parsing has completed, so hasMacroDefinition() will only return true if a macro with that name was not #undef’d.

Ignoring the state tracking problem, what happens with use of `foo`
after `#define foo foo`? More reaslistic usages in this SO thread:

    Defining something to itself in C preprocessor - Stack Overflow

--Ben

[Please reply *only* to the list and do not include my email directly
in the To: or Cc: of your reply; otherwise I will not see your reply.

Thanks.]

In article <718D2E03-2B6D-4962-9DE8-22B6C2054FF7@gmail.com>,
    David Rector via cfe-dev <cfe-dev@lists.llvm.org> writes:

AST matching on which clang tidy depends is all done during
HandleTranslationUnit, *after* all parsing has completed, so
hasMacroDefinition() will only return true if a macro with that name was
not #undef'd.

Yeah, another option is to have the check hook the PP callbacks and
take note of the locations of macros as they're defined/undefined.

You are right, the presence of `#define false false` etc. would blow this solution up, so that it should not be relied as usually-okay-but-imperfect.

[Please reply *only* to the list and do not include my email directly
in the To: or Cc: of your reply; otherwise I will not see your reply.

Thanks.]

In article <D64116A8-DB65-4A0C-8146-53C3E0A2E53D@gmail.com>,
    David Rector via cfe-dev <cfe-dev@lists.llvm.org> writes:

You are right, the presence of `#define false false` etc. would blow this
solution up, so that it should not be relied as usually-okay-but-imperfect.

IMO, I am not worried about failing in the face of deliberately
malformed code.