Debian Codegraph @

llvm-project/clang-tools-extra/clang-tidy/readability/ContainerSizeEmptyCheck.cpp

raw
1 //===--- ContainerSizeEmptyCheck.cpp - clang-tidy -------------------------===//
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 #include "ContainerSizeEmptyCheck.h"
9 #include "../utils/ASTUtils.h"
10 #include "../utils/Matchers.h"
11 #include "clang/AST/ASTContext.h"
12 #include "clang/ASTMatchers/ASTMatchers.h"
13 #include "clang/Lex/Lexer.h"
14 #include "llvm/ADT/StringRef.h"
15
16 using namespace clang::ast_matchers;
17
18 namespace clang {
19 namespace ast_matchers {
20 AST_POLYMORPHIC_MATCHER_P2(hasAnyArgumentWithParam,
21 AST_POLYMORPHIC_SUPPORTED_TYPES(CallExpr,
22 CXXConstructExpr),
23 internal::Matcher<Expr>, ArgMatcher,
24 internal::Matcher<ParmVarDecl>, ParamMatcher) {
25 BoundNodesTreeBuilder Result;
26 // The first argument of an overloaded member operator is the implicit object
27 // argument of the method which should not be matched against a parameter, so
28 // we skip over it here.
29 BoundNodesTreeBuilder Matches;
30 unsigned ArgIndex = cxxOperatorCallExpr(callee(cxxMethodDecl()))
31 .matches(Node, Finder, &Matches)
32 ? 1
33 : 0;
34 int ParamIndex = 0;
35 for (; ArgIndex < Node.getNumArgs(); ++ArgIndex) {
36 BoundNodesTreeBuilder ArgMatches(*Builder);
37 if (ArgMatcher.matches(*(Node.getArg(ArgIndex)->IgnoreParenCasts()), Finder,
38 &ArgMatches)) {
39 BoundNodesTreeBuilder ParamMatches(ArgMatches);
40 if (expr(anyOf(cxxConstructExpr(hasDeclaration(cxxConstructorDecl(
41 hasParameter(ParamIndex, ParamMatcher)))),
42 callExpr(callee(functionDecl(
43 hasParameter(ParamIndex, ParamMatcher))))))
44 .matches(Node, Finder, &ParamMatches)) {
45 Result.addMatch(ParamMatches);
46 *Builder = std::move(Result);
47 return true;
48 }
49 }
50 ++ParamIndex;
51 }
52 return false;
53 }
54
55 AST_MATCHER(Expr, usedInBooleanContext) {
56 const char *ExprName = "__booleanContextExpr";
57 auto Result =
58 expr(expr().bind(ExprName),
59 anyOf(hasParent(
60 mapAnyOf(varDecl, fieldDecl).with(hasType(booleanType()))),
61 hasParent(cxxConstructorDecl(
62 hasAnyConstructorInitializer(cxxCtorInitializer(
63 withInitializer(expr(equalsBoundNode(ExprName))),
64 forField(hasType(booleanType())))))),
65 hasParent(stmt(anyOf(
66 explicitCastExpr(hasDestinationType(booleanType())),
67 mapAnyOf(ifStmt, doStmt, whileStmt, forStmt,
68 conditionalOperator)
69 .with(hasCondition(expr(equalsBoundNode(ExprName)))),
70 parenListExpr(hasParent(varDecl(hasType(booleanType())))),
71 parenExpr(hasParent(
72 explicitCastExpr(hasDestinationType(booleanType())))),
73 returnStmt(forFunction(returns(booleanType()))),
74 cxxUnresolvedConstructExpr(hasType(booleanType())),
75 invocation(hasAnyArgumentWithParam(
76 expr(equalsBoundNode(ExprName)),
77 parmVarDecl(hasType(booleanType())))),
78 binaryOperator(hasAnyOperatorName("&&", "||")),
79 unaryOperator(hasOperatorName("!")).bind("NegOnSize"))))))
80 .matches(Node, Finder, Builder);
81 Builder->removeBindings([ExprName](const BoundNodesMap &Nodes) {
82 return Nodes.getNode(ExprName).getNodeKind().isNone();
83 });
84 return Result;
85 }
86 AST_MATCHER(CXXConstructExpr, isDefaultConstruction) {
87 return Node.getConstructor()->isDefaultConstructor();
88 }
89 AST_MATCHER(QualType, isIntegralType) {
90 return Node->isIntegralType(Finder->getASTContext());
91 }
92 } // namespace ast_matchers
93 namespace tidy::readability {
94
95 using utils::isBinaryOrTernary;
96
97 ContainerSizeEmptyCheck::ContainerSizeEmptyCheck(StringRef Name,
98 ClangTidyContext *Context)
99 : ClangTidyCheck(Name, Context) {}
100
101 void ContainerSizeEmptyCheck::registerMatchers(MatchFinder *Finder) {
102 const auto ValidContainerRecord = cxxRecordDecl(isSameOrDerivedFrom(
103 namedDecl(
104 has(cxxMethodDecl(
105 isConst(), parameterCountIs(0), isPublic(), hasName("size"),
106 returns(qualType(isIntegralType(), unless(booleanType()))))
107 .bind("size")),
108 has(cxxMethodDecl(isConst(), parameterCountIs(0), isPublic(),
109 hasName("empty"), returns(booleanType()))
110 .bind("empty")))
111 .bind("container")));
112
113 const auto ValidContainerNonTemplateType =
114 qualType(hasUnqualifiedDesugaredType(
115 recordType(hasDeclaration(ValidContainerRecord))));
116 const auto ValidContainerTemplateType =
117 qualType(hasUnqualifiedDesugaredType(templateSpecializationType(
118 hasDeclaration(classTemplateDecl(has(ValidContainerRecord))))));
119
120 const auto ValidContainer = qualType(
121 anyOf(ValidContainerNonTemplateType, ValidContainerTemplateType));
122
123 const auto WrongUse =
124 anyOf(hasParent(binaryOperator(
125 isComparisonOperator(),
126 hasEitherOperand(anyOf(integerLiteral(equals(1)),
127 integerLiteral(equals(0)))))
128 .bind("SizeBinaryOp")),
129 usedInBooleanContext());
130
131 Finder->addMatcher(
132 cxxMemberCallExpr(on(expr(anyOf(hasType(ValidContainer),
133 hasType(pointsTo(ValidContainer)),
134 hasType(references(ValidContainer))))
135 .bind("MemberCallObject")),
136 callee(cxxMethodDecl(hasName("size"))), WrongUse,
137 unless(hasAncestor(cxxMethodDecl(
138 ofClass(equalsBoundNode("container"))))))
139 .bind("SizeCallExpr"),
140 this);
141
142 Finder->addMatcher(
143 callExpr(has(cxxDependentScopeMemberExpr(
144 hasObjectExpression(
145 expr(anyOf(hasType(ValidContainer),
146 hasType(pointsTo(ValidContainer)),
147 hasType(references(ValidContainer))))
148 .bind("MemberCallObject")),
149 hasMemberName("size"))),
150 WrongUse,
151 unless(hasAncestor(
152 cxxMethodDecl(ofClass(equalsBoundNode("container"))))))
153 .bind("SizeCallExpr"),
154 this);
155
156 // Comparison to empty string or empty constructor.
157 const auto WrongComparend = anyOf(
158 stringLiteral(hasSize(0)), cxxConstructExpr(isDefaultConstruction()),
159 cxxUnresolvedConstructExpr(argumentCountIs(0)));
160 // Match the object being compared.
161 const auto STLArg =
162 anyOf(unaryOperator(
163 hasOperatorName("*"),
164 hasUnaryOperand(
165 expr(hasType(pointsTo(ValidContainer))).bind("Pointee"))),
166 expr(hasType(ValidContainer)).bind("STLObject"));
167 Finder->addMatcher(
168 binaryOperation(hasAnyOperatorName("==", "!="),
169 hasOperands(WrongComparend,
170 STLArg),
171 unless(hasAncestor(cxxMethodDecl(
172 ofClass(equalsBoundNode("container"))))))
173 .bind("BinCmp"),
174 this);
175 }
176
177 void ContainerSizeEmptyCheck::check(const MatchFinder::MatchResult &Result) {
178 const auto *MemberCall = Result.Nodes.getNodeAs<Expr>("SizeCallExpr");
179 const auto *MemberCallObject =
180 Result.Nodes.getNodeAs<Expr>("MemberCallObject");
181 const auto *BinCmp = Result.Nodes.getNodeAs<CXXOperatorCallExpr>("BinCmp");
182 const auto *BinCmpTempl = Result.Nodes.getNodeAs<BinaryOperator>("BinCmp");
183 const auto *BinCmpRewritten =
184 Result.Nodes.getNodeAs<CXXRewrittenBinaryOperator>("BinCmp");
185 const auto *BinaryOp = Result.Nodes.getNodeAs<BinaryOperator>("SizeBinaryOp");
186 const auto *Pointee = Result.Nodes.getNodeAs<Expr>("Pointee");
187 const auto *E =
188 MemberCallObject
189 ? MemberCallObject
190 : (Pointee ? Pointee : Result.Nodes.getNodeAs<Expr>("STLObject"));
191 FixItHint Hint;
192 std::string ReplacementText = std::string(
193 Lexer::getSourceText(CharSourceRange::getTokenRange(E->getSourceRange()),
194 *Result.SourceManager, getLangOpts()));
195 const auto *OpCallExpr = dyn_cast<CXXOperatorCallExpr>(E);
196 if (isBinaryOrTernary(E) || isa<UnaryOperator>(E) ||
197 (OpCallExpr && (OpCallExpr->getOperator() == OO_Star))) {
198 ReplacementText = "(" + ReplacementText + ")";
199 }
200 if (OpCallExpr &&
201 OpCallExpr->getOperator() == OverloadedOperatorKind::OO_Arrow) {
202 // This can happen if the object is a smart pointer. Don't add anything
203 // because a '->' is already there (PR#51776), just call the method.
204 ReplacementText += "empty()";
205 } else if (E->getType()->isPointerType())
206 ReplacementText += "->empty()";
207 else
208 ReplacementText += ".empty()";
209
210 if (BinCmp) {
211 if (BinCmp->getOperator() == OO_ExclaimEqual) {
212 ReplacementText = "!" + ReplacementText;
213 }
214 Hint =
215 FixItHint::CreateReplacement(BinCmp->getSourceRange(), ReplacementText);
216 } else if (BinCmpTempl) {
217 if (BinCmpTempl->getOpcode() == BinaryOperatorKind::BO_NE) {
218 ReplacementText = "!" + ReplacementText;
219 }
220 Hint = FixItHint::CreateReplacement(BinCmpTempl->getSourceRange(),
221 ReplacementText);
222 } else if (BinCmpRewritten) {
223 if (BinCmpRewritten->getOpcode() == BinaryOperatorKind::BO_NE) {
224 ReplacementText = "!" + ReplacementText;
225 }
226 Hint = FixItHint::CreateReplacement(BinCmpRewritten->getSourceRange(),
227 ReplacementText);
228 } else if (BinaryOp) { // Determine the correct transformation.
229 const auto *LiteralLHS =
230 llvm::dyn_cast<IntegerLiteral>(BinaryOp->getLHS()->IgnoreImpCasts());
231 const auto *LiteralRHS =
232 llvm::dyn_cast<IntegerLiteral>(BinaryOp->getRHS()->IgnoreImpCasts());
233 const bool ContainerIsLHS = !LiteralLHS;
234
235 uint64_t Value = 0;
236 if (LiteralLHS)
237 Value = LiteralLHS->getValue().getLimitedValue();
238 else if (LiteralRHS)
239 Value = LiteralRHS->getValue().getLimitedValue();
240 else
241 return;
242
243 bool Negation = false;
244 const auto OpCode = BinaryOp->getOpcode();
245
246 // Constant that is not handled.
247 if (Value > 1)
248 return;
249
250 if (Value == 1 && (OpCode == BinaryOperatorKind::BO_EQ ||
251 OpCode == BinaryOperatorKind::BO_NE))
252 return;
253
254 // Always true, no warnings for that.
255 if ((OpCode == BinaryOperatorKind::BO_GE && Value == 0 && ContainerIsLHS) ||
256 (OpCode == BinaryOperatorKind::BO_LE && Value == 0 && !ContainerIsLHS))
257 return;
258
259 // Do not warn for size > 1, 1 < size, size <= 1, 1 >= size.
260 if (Value == 1) {
261 if ((OpCode == BinaryOperatorKind::BO_GT && ContainerIsLHS) ||
262 (OpCode == BinaryOperatorKind::BO_LT && !ContainerIsLHS))
263 return;
264 if ((OpCode == BinaryOperatorKind::BO_LE && ContainerIsLHS) ||
265 (OpCode == BinaryOperatorKind::BO_GE && !ContainerIsLHS))
266 return;
267 }
268
269 if (OpCode == BinaryOperatorKind::BO_NE && Value == 0)
270 Negation = true;
271 if ((OpCode == BinaryOperatorKind::BO_GT ||
272 OpCode == BinaryOperatorKind::BO_GE) &&
273 ContainerIsLHS)
274 Negation = true;
275 if ((OpCode == BinaryOperatorKind::BO_LT ||
276 OpCode == BinaryOperatorKind::BO_LE) &&
277 !ContainerIsLHS)
278 Negation = true;
279
280 if (Negation)
281 ReplacementText = "!" + ReplacementText;
282 Hint = FixItHint::CreateReplacement(BinaryOp->getSourceRange(),
283 ReplacementText);
284
285 } else {
286 // If there is a conversion above the size call to bool, it is safe to just
287 // replace size with empty.
288 if (const auto *UnaryOp =
289 Result.Nodes.getNodeAs<UnaryOperator>("NegOnSize"))
290 Hint = FixItHint::CreateReplacement(UnaryOp->getSourceRange(),
291 ReplacementText);
292 else
293 Hint = FixItHint::CreateReplacement(MemberCall->getSourceRange(),
294 "!" + ReplacementText);
295 }
296
297 auto WarnLoc = MemberCall ? MemberCall->getBeginLoc() : SourceLocation{};
298
299 if (WarnLoc.isValid()) {
300 diag(WarnLoc, "the 'empty' method should be used to check "
301 "for emptiness instead of 'size'")
302 << Hint;
303 } else {
304 WarnLoc = BinCmpTempl
305 ? BinCmpTempl->getBeginLoc()
306 : (BinCmp ? BinCmp->getBeginLoc()
307 : (BinCmpRewritten ? BinCmpRewritten->getBeginLoc()
308 : SourceLocation{}));
309 diag(WarnLoc, "the 'empty' method should be used to check "
310 "for emptiness instead of comparing to an empty object")
311 << Hint;
312 }
313
314 const auto *Container = Result.Nodes.getNodeAs<NamedDecl>("container");
315 if (const auto *CTS = dyn_cast<ClassTemplateSpecializationDecl>(Container)) {
316 // The definition of the empty() method is the same for all implicit
317 // instantiations. In order to avoid duplicate or inconsistent warnings
318 // (depending on how deduplication is done), we use the same class name
319 // for all implicit instantiations of a template.
320 if (CTS->getSpecializationKind() == TSK_ImplicitInstantiation)
321 Container = CTS->getSpecializedTemplate();
322 }
323 const auto *Empty = Result.Nodes.getNodeAs<FunctionDecl>("empty");
324
325 diag(Empty->getLocation(), "method %0::empty() defined here",
326 DiagnosticIDs::Note)
327 << Container;
328 }
329
330 } // namespace tidy::readability
331 } // namespace clang