11#include "clang/Basic/TokenKinds.h"
12#include "clang/Lex/PPCallbacks.h"
13#include "clang/Lex/Preprocessor.h"
23class IfPreprocessorCallbacks final :
public PPCallbacks {
25 IfPreprocessorCallbacks(ClangTidyCheck &Check,
const Preprocessor &PP)
26 : Check(Check), PP(PP) {}
28 void If(SourceLocation Loc, SourceRange ConditionRange,
29 ConditionValueKind)
override {
30 impl(Loc, ConditionRange, {
"ifdef",
"ifndef"});
33 void Elif(SourceLocation Loc, SourceRange ConditionRange, ConditionValueKind,
34 SourceLocation)
override {
35 if (PP.getLangOpts().C23 || PP.getLangOpts().CPlusPlus23)
36 impl(Loc, ConditionRange, {
"elifdef",
"elifndef"});
40 void impl(SourceLocation DirectiveLoc, SourceRange ConditionRange,
41 const std::array<StringRef, 2> &Replacements) {
43 CharSourceRange::getTokenRange(ConditionRange), PP.getSourceManager(),
45 bool Inverted =
false;
46 std::size_t ParensNestingDepth = 0;
47 std::size_t Index = 0;
48 while (Index < Tokens.size()) {
49 const Token &Tok = Tokens[Index];
50 if (Tok.is(tok::TokenKind::exclaim) ||
51 (PP.getLangOpts().CPlusPlus &&
52 Tok.is(tok::TokenKind::raw_identifier) &&
56 }
else if (Tok.is(tok::TokenKind::l_paren)) {
64 if (Index >= Tokens.size() ||
65 Tokens[Index].isNot(tok::TokenKind::raw_identifier) ||
70 if (Index < Tokens.size() && Tokens[Index].is(tok::TokenKind::l_paren)) {
75 if (Index >= Tokens.size() ||
76 Tokens[Index].isNot(tok::TokenKind::raw_identifier))
80 while (Index < Tokens.size()) {
81 if (Tokens[Index++].isNot(tok::TokenKind::r_paren) ||
82 ParensNestingDepth == 0)
87 if (ParensNestingDepth != 0)
92 "preprocessor condition can be written more concisely using '#%0'")
93 << FixItHint::CreateReplacement(
94 CharSourceRange::getCharRange(DirectiveLoc,
95 ConditionRange.getBegin()),
96 (Replacements[Inverted].str() +
" "))
97 << FixItHint::CreateReplacement(ConditionRange, Macro)
98 << Replacements[Inverted];
101 ClangTidyCheck &Check;
102 const Preprocessor &PP;
108 const SourceManager &, Preprocessor *PP, Preprocessor *) {
109 PP->addPPCallbacks(std::make_unique<IfPreprocessorCallbacks>(*
this, *PP));
void registerPPCallbacks(const SourceManager &SM, Preprocessor *PP, Preprocessor *ModuleExpanderPP) override
StringRef getTokenName(const Token &Tok)
Returns the spelling of an identifier token.
std::vector< Token > getRawTokens(CharSourceRange Range, const SourceManager &SM, const LangOptions &LangOpts)
Returns the raw tokens in Range.
StringRef getTokenName(const Token &Tok)
Returns the spelling of an identifier token.