11#include "clang/AST/ASTContext.h"
12#include "clang/Lex/PPCallbacks.h"
13#include "clang/Lex/Preprocessor.h"
14#include "llvm/ADT/STLExtras.h"
21struct AvoidUnconditionalPreprocessorIfPPCallbacks :
public PPCallbacks {
22 explicit AvoidUnconditionalPreprocessorIfPPCallbacks(ClangTidyCheck &Check,
24 : Check(Check), PP(PP) {}
26 void If(SourceLocation Loc, SourceRange ConditionRange,
27 ConditionValueKind ConditionValue)
override {
28 if (ConditionValue == CVK_NotEvaluated)
30 SourceManager &SM = PP.getSourceManager();
31 if (!isImmutable(SM, PP.getLangOpts(), ConditionRange))
34 if (ConditionValue == CVK_True)
35 Check.diag(Loc,
"preprocessor condition is always 'true', consider "
36 "removing condition but leaving its contents");
38 Check.diag(Loc,
"preprocessor condition is always 'false', consider "
39 "removing both the condition and its contents");
42 bool isImmutable(SourceManager &SM,
const LangOptions &LangOpts,
43 SourceRange ConditionRange) {
44 const SourceLocation Loc = ConditionRange.getBegin();
49 CharSourceRange::getTokenRange(ConditionRange), SM, LangOpts);
53 Tokens, [
this](
const Token &Tok) {
return isImmutableToken(Tok); });
56 bool isImmutableToken(
const Token &Tok) {
57 switch (Tok.getKind()) {
60 case tok::numeric_constant:
61 case tok::char_constant:
62 case tok::wide_char_constant:
63 case tok::utf8_char_constant:
64 case tok::utf16_char_constant:
65 case tok::utf32_char_constant:
66 case tok::string_literal:
67 case tok::wide_string_literal:
70 case tok::raw_identifier:
71 return (Tok.getRawIdentifier() ==
"true" ||
72 Tok.getRawIdentifier() ==
"false");
74 return Tok.getKind() >= tok::l_square &&
75 Tok.getKind() <= tok::greatergreatergreater;
79 ClangTidyCheck &Check;
86 const SourceManager &SM, Preprocessor *PP, Preprocessor *ModuleExpanderPP) {
88 std::make_unique<AvoidUnconditionalPreprocessorIfPPCallbacks>(*
this,
void registerPPCallbacks(const SourceManager &SM, Preprocessor *PP, Preprocessor *ModuleExpanderPP) override
std::vector< Token > getRawTokens(CharSourceRange Range, const SourceManager &SM, const LangOptions &LangOpts)
Returns the raw tokens in Range.