[cfe-dev] How to determine if a raw_id token is a macro name?

David Rector via cfe-dev cfe-dev at lists.llvm.org
Sun Jan 9 08:49:50 PST 2022


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.

> On Jan 7, 2022, at 12:02 PM, Ben Boeckel <ben.boeckel at kitware.com> wrote:
> 
> On Fri, Jan 07, 2022 at 07:45:23 -0500, David Rector via cfe-dev wrote:
>> I believe the best you can do is to convert the string to an
>> IdentifierInfo and access hadMacroDefinition:
>> ```
>> IdentifierInfo &FooII = Context.Idents.get("Foo");
>> 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:
> 
>    https://stackoverflow.com/questions/46797804/defining-something-to-itself-in-c-preprocessor
> 
> --Ben



More information about the cfe-dev mailing list