clang-tools 22.0.0git
UseStdMinMaxCheck.cpp
Go to the documentation of this file.
1//===----------------------------------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include "UseStdMinMaxCheck.h"
10#include "../utils/ASTUtils.h"
11#include "clang/AST/ASTContext.h"
12#include "clang/ASTMatchers/ASTMatchFinder.h"
13#include "clang/Lex/Preprocessor.h"
14
15using namespace clang::ast_matchers;
16
18
19namespace {
20
21// Ignore if statements that are inside macros.
22AST_MATCHER(IfStmt, isIfInMacro) {
23 return Node.getIfLoc().isMacroID() || Node.getEndLoc().isMacroID();
24}
25
26} // namespace
27
28static const llvm::StringRef AlgorithmHeader("<algorithm>");
29
30static bool minCondition(const BinaryOperator::Opcode Op, const Expr *CondLhs,
31 const Expr *CondRhs, const Expr *AssignLhs,
32 const Expr *AssignRhs, const ASTContext &Context) {
33 if ((Op == BO_LT || Op == BO_LE) &&
34 (tidy::utils::areStatementsIdentical(CondLhs, AssignRhs, Context) &&
35 tidy::utils::areStatementsIdentical(CondRhs, AssignLhs, Context)))
36 return true;
37
38 if ((Op == BO_GT || Op == BO_GE) &&
39 (tidy::utils::areStatementsIdentical(CondLhs, AssignLhs, Context) &&
40 tidy::utils::areStatementsIdentical(CondRhs, AssignRhs, Context)))
41 return true;
42
43 return false;
44}
45
46static bool maxCondition(const BinaryOperator::Opcode Op, const Expr *CondLhs,
47 const Expr *CondRhs, const Expr *AssignLhs,
48 const Expr *AssignRhs, const ASTContext &Context) {
49 if ((Op == BO_LT || Op == BO_LE) &&
50 (tidy::utils::areStatementsIdentical(CondLhs, AssignLhs, Context) &&
51 tidy::utils::areStatementsIdentical(CondRhs, AssignRhs, Context)))
52 return true;
53
54 if ((Op == BO_GT || Op == BO_GE) &&
55 (tidy::utils::areStatementsIdentical(CondLhs, AssignRhs, Context) &&
56 tidy::utils::areStatementsIdentical(CondRhs, AssignLhs, Context)))
57 return true;
58
59 return false;
60}
61
62static QualType getNonTemplateAlias(QualType QT) {
63 while (true) {
64 // cast to a TypedefType
65 if (const auto *TT = dyn_cast<TypedefType>(QT)) {
66 // check if the typedef is a template and if it is dependent
67 if (!TT->getDecl()->getDescribedTemplate() &&
68 !TT->getDecl()->getDeclContext()->isDependentContext())
69 return QT;
70 QT = TT->desugar();
71 } else {
72 break;
73 }
74 }
75 return QT;
76}
77
78static QualType getReplacementCastType(const Expr *CondLhs, const Expr *CondRhs,
79 QualType ComparedType) {
80 const QualType LhsType = CondLhs->getType();
81 const QualType RhsType = CondRhs->getType();
82 const QualType LhsCanonicalType =
83 LhsType.getCanonicalType().getNonReferenceType().getUnqualifiedType();
84 const QualType RhsCanonicalType =
85 RhsType.getCanonicalType().getNonReferenceType().getUnqualifiedType();
86 QualType GlobalImplicitCastType;
87 if (LhsCanonicalType != RhsCanonicalType) {
88 if (llvm::isa<IntegerLiteral>(CondRhs))
89 GlobalImplicitCastType = getNonTemplateAlias(LhsType);
90 else if (llvm::isa<IntegerLiteral>(CondLhs))
91 GlobalImplicitCastType = getNonTemplateAlias(RhsType);
92 else
93 GlobalImplicitCastType = getNonTemplateAlias(ComparedType);
94 }
95 return GlobalImplicitCastType;
96}
97
98static std::string
99createReplacement(const Expr *CondLhs, const Expr *CondRhs,
100 const Expr *AssignLhs, const SourceManager &Source,
101 const LangOptions &LO, StringRef FunctionName,
102 const BinaryOperator *BO, StringRef Comment = "") {
103 const llvm::StringRef CondLhsStr = Lexer::getSourceText(
104 Source.getExpansionRange(CondLhs->getSourceRange()), Source, LO);
105 const llvm::StringRef CondRhsStr = Lexer::getSourceText(
106 Source.getExpansionRange(CondRhs->getSourceRange()), Source, LO);
107 const llvm::StringRef AssignLhsStr = Lexer::getSourceText(
108 Source.getExpansionRange(AssignLhs->getSourceRange()), Source, LO);
109
110 const QualType GlobalImplicitCastType =
111 getReplacementCastType(CondLhs, CondRhs, BO->getLHS()->getType());
112
113 return (AssignLhsStr + " = " + FunctionName +
114 (!GlobalImplicitCastType.isNull()
115 ? "<" + GlobalImplicitCastType.getAsString() + ">("
116 : "(") +
117 CondLhsStr + ", " + CondRhsStr + ");" + (Comment.empty() ? "" : " ") +
118 Comment)
119 .str();
120}
121
123 : ClangTidyCheck(Name, Context),
124 IncludeInserter(Options.getLocalOrGlobal("IncludeStyle",
125 utils::IncludeSorter::IS_LLVM),
126 areDiagsSelfContained()) {}
127
129 Options.store(Opts, "IncludeStyle", IncludeInserter.getStyle());
130}
131
132void UseStdMinMaxCheck::registerMatchers(MatchFinder *Finder) {
133 auto AssignOperator =
134 binaryOperator(hasOperatorName("="),
135 hasLHS(expr(unless(isTypeDependent())).bind("AssignLhs")),
136 hasRHS(expr(unless(isTypeDependent())).bind("AssignRhs")));
137 auto BinaryOperator =
138 binaryOperator(hasAnyOperatorName("<", ">", "<=", ">="),
139 hasLHS(expr(unless(isTypeDependent())).bind("CondLhs")),
140 hasRHS(expr(unless(isTypeDependent())).bind("CondRhs")))
141 .bind("binaryOp");
142 Finder->addMatcher(
143 ifStmt(stmt().bind("if"), unless(isIfInMacro()),
144 unless(hasElse(stmt())), // Ensure `if` has no `else`
145 hasCondition(BinaryOperator),
146 hasThen(
147 anyOf(stmt(AssignOperator),
148 compoundStmt(statementCountIs(1), has(AssignOperator)))),
149 hasParent(stmt(unless(ifStmt(hasElse(
150 equalsBoundNode("if"))))))), // Ensure `if` has no `else if`
151 this);
152}
153
154void UseStdMinMaxCheck::registerPPCallbacks(const SourceManager &SM,
155 Preprocessor *PP,
156 Preprocessor *ModuleExpanderPP) {
157 IncludeInserter.registerPreprocessor(PP);
158}
159
160void UseStdMinMaxCheck::check(const MatchFinder::MatchResult &Result) {
161 const auto *If = Result.Nodes.getNodeAs<IfStmt>("if");
162 const clang::LangOptions &LO = Result.Context->getLangOpts();
163 const auto *CondLhs = Result.Nodes.getNodeAs<Expr>("CondLhs");
164 const auto *CondRhs = Result.Nodes.getNodeAs<Expr>("CondRhs");
165 const auto *AssignLhs = Result.Nodes.getNodeAs<Expr>("AssignLhs");
166 const auto *AssignRhs = Result.Nodes.getNodeAs<Expr>("AssignRhs");
167 const auto *BinaryOp = Result.Nodes.getNodeAs<BinaryOperator>("binaryOp");
168 const clang::BinaryOperatorKind BinaryOpcode = BinaryOp->getOpcode();
169 const SourceLocation IfLocation = If->getIfLoc();
170 const SourceLocation ThenLocation = If->getEndLoc();
171
172 auto ReplaceAndDiagnose = [&](const llvm::StringRef FunctionName) {
173 const SourceManager &Source = *Result.SourceManager;
174 llvm::SmallString<64> Comment;
175
176 const auto AppendNormalized = [&](llvm::StringRef Text) {
177 Text = Text.ltrim();
178 if (!Text.empty()) {
179 if (!Comment.empty())
180 Comment += " ";
181 Comment += Text;
182 }
183 };
184
185 const auto GetSourceText = [&](SourceLocation StartLoc,
186 SourceLocation EndLoc) {
187 return Lexer::getSourceText(
188 CharSourceRange::getCharRange(
189 Lexer::getLocForEndOfToken(StartLoc, 0, Source, LO), EndLoc),
190 Source, LO);
191 };
192
193 // Captures:
194 // if (cond) // Comment A
195 // if (cond) /* Comment A */ { ... }
196 // if (cond) /* Comment A */ x = y;
197 AppendNormalized(
198 GetSourceText(If->getRParenLoc(), If->getThen()->getBeginLoc()));
199
200 if (const auto *CS = dyn_cast<CompoundStmt>(If->getThen())) {
201 const Stmt *Inner = CS->body_front();
202
203 // Captures:
204 // if (cond) { // Comment B
205 // ...
206 // }
207 // if (cond) { /* Comment B */ x = y; }
208 AppendNormalized(GetSourceText(CS->getBeginLoc(), Inner->getBeginLoc()));
209
210 // Captures:
211 // if (cond) { x = y; // Comment C }
212 // if (cond) { x = y; /* Comment C */ }
213 llvm::StringRef PostInner =
214 GetSourceText(Inner->getEndLoc(), CS->getEndLoc());
215
216 // Strip the trailing semicolon to avoid fixes like:
217 // x = std::min(x, y);; // comment
218 const size_t Semi = PostInner.find(';');
219 if (Semi != llvm::StringRef::npos &&
220 PostInner.take_front(Semi).trim().empty()) {
221 PostInner = PostInner.drop_front(Semi + 1);
222 }
223 AppendNormalized(PostInner);
224 }
225
226 diag(IfLocation, "use `%0` instead of `%1`")
227 << FunctionName << BinaryOp->getOpcodeStr()
228 << FixItHint::CreateReplacement(
229 SourceRange(IfLocation, Lexer::getLocForEndOfToken(
230 ThenLocation, 0, Source, LO)),
231 createReplacement(CondLhs, CondRhs, AssignLhs, Source, LO,
232 FunctionName, BinaryOp, Comment))
233 << IncludeInserter.createIncludeInsertion(
234 Source.getFileID(If->getBeginLoc()), AlgorithmHeader);
235 };
236
237 if (minCondition(BinaryOpcode, CondLhs, CondRhs, AssignLhs, AssignRhs,
238 (*Result.Context))) {
239 ReplaceAndDiagnose("std::min");
240 } else if (maxCondition(BinaryOpcode, CondLhs, CondRhs, AssignLhs, AssignRhs,
241 (*Result.Context))) {
242 ReplaceAndDiagnose("std::max");
243 }
244}
245
246} // namespace clang::tidy::readability
Every ClangTidyCheck reports errors through a DiagnosticsEngine provided by this context.
UseStdMinMaxCheck(StringRef Name, ClangTidyContext *Context)
void registerPPCallbacks(const SourceManager &SM, Preprocessor *PP, Preprocessor *ModuleExpanderPP) override
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
void registerMatchers(ast_matchers::MatchFinder *Finder) override
void storeOptions(ClangTidyOptions::OptionMap &Opts) override
AST_MATCHER(BinaryOperator, isRelationalOperator)
static QualType getNonTemplateAlias(QualType QT)
static bool minCondition(const BinaryOperator::Opcode Op, const Expr *CondLhs, const Expr *CondRhs, const Expr *AssignLhs, const Expr *AssignRhs, const ASTContext &Context)
static std::string createReplacement(const Expr *CondLhs, const Expr *CondRhs, const Expr *AssignLhs, const SourceManager &Source, const LangOptions &LO, StringRef FunctionName, const BinaryOperator *BO, StringRef Comment="")
static bool maxCondition(const BinaryOperator::Opcode Op, const Expr *CondLhs, const Expr *CondRhs, const Expr *AssignLhs, const Expr *AssignRhs, const ASTContext &Context)
static QualType getReplacementCastType(const Expr *CondLhs, const Expr *CondRhs, QualType ComparedType)
static const llvm::StringRef AlgorithmHeader("<algorithm>")
bool areStatementsIdentical(const Stmt *FirstStmt, const Stmt *SecondStmt, const ASTContext &Context, bool Canonical)
Definition ASTUtils.cpp:89
llvm::StringMap< ClangTidyValue > OptionMap