10#include "clang/Basic/TokenKinds.h"
11#include "clang/Lex/Lexer.h"
12#include "clang/Lex/PPCallbacks.h"
13#include "clang/Lex/Preprocessor.h"
21class IfPreprocessorCallbacks final :
public PPCallbacks {
23 IfPreprocessorCallbacks(ClangTidyCheck &Check,
const Preprocessor &PP)
24 : Check(Check), PP(PP) {}
26 void If(SourceLocation Loc, SourceRange ConditionRange,
27 ConditionValueKind)
override {
28 impl(Loc, ConditionRange, {
"ifdef",
"ifndef"});
31 void Elif(SourceLocation Loc, SourceRange ConditionRange, ConditionValueKind,
32 SourceLocation)
override {
33 if (PP.getLangOpts().C23 || PP.getLangOpts().CPlusPlus23)
34 impl(Loc, ConditionRange, {
"elifdef",
"elifndef"});
38 void impl(SourceLocation DirectiveLoc, SourceRange ConditionRange,
39 const std::array<llvm::StringLiteral, 2> &Replacements) {
41 SmallString<128> Condition =
42 Lexer::getSourceText(CharSourceRange::getTokenRange(ConditionRange),
43 PP.getSourceManager(), PP.getLangOpts());
44 Condition.push_back(
'\0');
45 Lexer Lex(DirectiveLoc, PP.getLangOpts(), Condition.data(),
46 Condition.data(), Condition.data() + Condition.size() - 1);
48 bool Inverted =
false;
49 std::size_t ParensNestingDepth = 0;
51 if (Lex.LexFromRawLexer(Tok))
54 if (Tok.is(tok::TokenKind::exclaim) ||
55 (PP.getLangOpts().CPlusPlus &&
56 Tok.is(tok::TokenKind::raw_identifier) &&
57 Tok.getRawIdentifier() ==
"not"))
59 else if (Tok.is(tok::TokenKind::l_paren))
65 if (Tok.isNot(tok::TokenKind::raw_identifier) ||
66 Tok.getRawIdentifier() !=
"defined")
69 bool NoMoreTokens = Lex.LexFromRawLexer(Tok);
70 if (Tok.is(tok::TokenKind::l_paren)) {
74 NoMoreTokens = Lex.LexFromRawLexer(Tok);
77 if (Tok.isNot(tok::TokenKind::raw_identifier))
79 const StringRef
Macro = Tok.getRawIdentifier();
81 while (!NoMoreTokens) {
82 NoMoreTokens = Lex.LexFromRawLexer(Tok);
83 if (Tok.isNot(tok::TokenKind::r_paren))
88 if (ParensNestingDepth != 0)
93 "preprocessor condition can be written more concisely using '#%0'")
94 << FixItHint::CreateReplacement(DirectiveLoc, Replacements[Inverted])
95 << FixItHint::CreateReplacement(ConditionRange, Macro)
96 << Replacements[Inverted];
99 ClangTidyCheck &Check;
100 const Preprocessor &PP;
106 const SourceManager &, Preprocessor *PP, Preprocessor *) {
107 PP->addPPCallbacks(std::make_unique<IfPreprocessorCallbacks>(*
this, *PP));
void registerPPCallbacks(const SourceManager &SM, Preprocessor *PP, Preprocessor *ModuleExpanderPP) override