2015-03-09 20:18:39 +08:00
|
|
|
//===--- ContainerSizeEmptyCheck.cpp - clang-tidy -------------------------===//
|
2015-01-15 23:46:58 +08:00
|
|
|
//
|
2019-01-19 16:50:56 +08:00
|
|
|
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
|
|
|
|
// See https://llvm.org/LICENSE.txt for license information.
|
|
|
|
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
|
2015-01-15 23:46:58 +08:00
|
|
|
//
|
|
|
|
//===----------------------------------------------------------------------===//
|
2015-03-09 20:18:39 +08:00
|
|
|
#include "ContainerSizeEmptyCheck.h"
|
2017-04-24 22:57:09 +08:00
|
|
|
#include "../utils/ASTUtils.h"
|
2016-09-13 16:58:11 +08:00
|
|
|
#include "../utils/Matchers.h"
|
2015-01-15 23:46:58 +08:00
|
|
|
#include "clang/AST/ASTContext.h"
|
|
|
|
#include "clang/ASTMatchers/ASTMatchers.h"
|
|
|
|
#include "clang/Lex/Lexer.h"
|
2015-02-13 17:07:58 +08:00
|
|
|
#include "llvm/ADT/StringRef.h"
|
2015-01-15 23:46:58 +08:00
|
|
|
|
|
|
|
using namespace clang::ast_matchers;
|
|
|
|
|
|
|
|
namespace clang {
|
2020-10-28 07:24:20 +08:00
|
|
|
namespace ast_matchers {
|
|
|
|
AST_POLYMORPHIC_MATCHER_P2(hasAnyArgumentWithParam,
|
|
|
|
AST_POLYMORPHIC_SUPPORTED_TYPES(CallExpr,
|
|
|
|
CXXConstructExpr),
|
|
|
|
internal::Matcher<Expr>, ArgMatcher,
|
|
|
|
internal::Matcher<ParmVarDecl>, ParamMatcher) {
|
|
|
|
BoundNodesTreeBuilder Result;
|
|
|
|
// The first argument of an overloaded member operator is the implicit object
|
|
|
|
// argument of the method which should not be matched against a parameter, so
|
|
|
|
// we skip over it here.
|
|
|
|
BoundNodesTreeBuilder Matches;
|
|
|
|
unsigned ArgIndex = cxxOperatorCallExpr(callee(cxxMethodDecl()))
|
|
|
|
.matches(Node, Finder, &Matches)
|
|
|
|
? 1
|
|
|
|
: 0;
|
|
|
|
int ParamIndex = 0;
|
|
|
|
for (; ArgIndex < Node.getNumArgs(); ++ArgIndex) {
|
|
|
|
BoundNodesTreeBuilder ArgMatches(*Builder);
|
|
|
|
if (ArgMatcher.matches(*(Node.getArg(ArgIndex)->IgnoreParenCasts()), Finder,
|
|
|
|
&ArgMatches)) {
|
|
|
|
BoundNodesTreeBuilder ParamMatches(ArgMatches);
|
|
|
|
if (expr(anyOf(cxxConstructExpr(hasDeclaration(cxxConstructorDecl(
|
|
|
|
hasParameter(ParamIndex, ParamMatcher)))),
|
|
|
|
callExpr(callee(functionDecl(
|
|
|
|
hasParameter(ParamIndex, ParamMatcher))))))
|
|
|
|
.matches(Node, Finder, &ParamMatches)) {
|
|
|
|
Result.addMatch(ParamMatches);
|
|
|
|
*Builder = std::move(Result);
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
++ParamIndex;
|
|
|
|
}
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
|
|
|
AST_MATCHER(Expr, usedInBooleanContext) {
|
|
|
|
const char *ExprName = "__booleanContextExpr";
|
|
|
|
auto Result =
|
|
|
|
expr(expr().bind(ExprName),
|
2021-01-03 05:18:29 +08:00
|
|
|
anyOf(hasParent(
|
|
|
|
mapAnyOf(varDecl, fieldDecl).with(hasType(booleanType()))),
|
2020-10-28 07:24:20 +08:00
|
|
|
hasParent(cxxConstructorDecl(
|
|
|
|
hasAnyConstructorInitializer(cxxCtorInitializer(
|
|
|
|
withInitializer(expr(equalsBoundNode(ExprName))),
|
|
|
|
forField(hasType(booleanType())))))),
|
|
|
|
hasParent(stmt(anyOf(
|
|
|
|
explicitCastExpr(hasDestinationType(booleanType())),
|
2021-01-03 05:18:29 +08:00
|
|
|
mapAnyOf(ifStmt, doStmt, whileStmt, forStmt,
|
|
|
|
conditionalOperator)
|
|
|
|
.with(hasCondition(expr(equalsBoundNode(ExprName)))),
|
2020-10-28 07:24:20 +08:00
|
|
|
parenListExpr(hasParent(varDecl(hasType(booleanType())))),
|
|
|
|
parenExpr(hasParent(
|
|
|
|
explicitCastExpr(hasDestinationType(booleanType())))),
|
|
|
|
returnStmt(forFunction(returns(booleanType()))),
|
|
|
|
cxxUnresolvedConstructExpr(hasType(booleanType())),
|
2021-01-03 05:18:29 +08:00
|
|
|
invocation(hasAnyArgumentWithParam(
|
2020-10-28 07:24:20 +08:00
|
|
|
expr(equalsBoundNode(ExprName)),
|
|
|
|
parmVarDecl(hasType(booleanType())))),
|
|
|
|
binaryOperator(hasAnyOperatorName("&&", "||")),
|
|
|
|
unaryOperator(hasOperatorName("!")).bind("NegOnSize"))))))
|
|
|
|
.matches(Node, Finder, Builder);
|
|
|
|
Builder->removeBindings([ExprName](const BoundNodesMap &Nodes) {
|
|
|
|
return Nodes.getNode(ExprName).getNodeKind().isNone();
|
|
|
|
});
|
|
|
|
return Result;
|
|
|
|
}
|
2020-12-23 01:45:22 +08:00
|
|
|
AST_MATCHER(CXXConstructExpr, isDefaultConstruction) {
|
|
|
|
return Node.getConstructor()->isDefaultConstructor();
|
|
|
|
}
|
2020-10-28 07:24:20 +08:00
|
|
|
} // namespace ast_matchers
|
2015-01-15 23:46:58 +08:00
|
|
|
namespace tidy {
|
|
|
|
namespace readability {
|
|
|
|
|
2021-11-02 15:14:25 +08:00
|
|
|
using utils::isBinaryOrTernary;
|
2017-04-24 22:57:09 +08:00
|
|
|
|
2015-01-15 23:46:58 +08:00
|
|
|
ContainerSizeEmptyCheck::ContainerSizeEmptyCheck(StringRef Name,
|
|
|
|
ClangTidyContext *Context)
|
|
|
|
: ClangTidyCheck(Name, Context) {}
|
|
|
|
|
|
|
|
void ContainerSizeEmptyCheck::registerMatchers(MatchFinder *Finder) {
|
2020-10-28 07:24:20 +08:00
|
|
|
const auto ValidContainerRecord = cxxRecordDecl(isSameOrDerivedFrom(
|
|
|
|
namedDecl(
|
|
|
|
has(cxxMethodDecl(isConst(), parameterCountIs(0), isPublic(),
|
|
|
|
hasName("size"),
|
|
|
|
returns(qualType(isInteger(), unless(booleanType()),
|
|
|
|
unless(elaboratedType()))))
|
|
|
|
.bind("size")),
|
|
|
|
has(cxxMethodDecl(isConst(), parameterCountIs(0), isPublic(),
|
|
|
|
hasName("empty"), returns(booleanType()))
|
|
|
|
.bind("empty")))
|
|
|
|
.bind("container")));
|
|
|
|
|
|
|
|
const auto ValidContainerNonTemplateType =
|
|
|
|
qualType(hasUnqualifiedDesugaredType(
|
|
|
|
recordType(hasDeclaration(ValidContainerRecord))));
|
|
|
|
const auto ValidContainerTemplateType =
|
|
|
|
qualType(hasUnqualifiedDesugaredType(templateSpecializationType(
|
|
|
|
hasDeclaration(classTemplateDecl(has(ValidContainerRecord))))));
|
|
|
|
|
|
|
|
const auto ValidContainer = qualType(
|
|
|
|
anyOf(ValidContainerNonTemplateType, ValidContainerTemplateType));
|
2016-04-22 00:57:56 +08:00
|
|
|
|
2020-12-23 01:45:22 +08:00
|
|
|
const auto WrongUse =
|
|
|
|
anyOf(hasParent(binaryOperator(
|
|
|
|
isComparisonOperator(),
|
|
|
|
hasEitherOperand(anyOf(integerLiteral(equals(1)),
|
|
|
|
integerLiteral(equals(0)))))
|
|
|
|
.bind("SizeBinaryOp")),
|
|
|
|
usedInBooleanContext());
|
2015-01-15 23:46:58 +08:00
|
|
|
|
|
|
|
Finder->addMatcher(
|
2020-12-23 01:45:22 +08:00
|
|
|
cxxMemberCallExpr(on(expr(anyOf(hasType(ValidContainer),
|
2016-09-13 18:19:13 +08:00
|
|
|
hasType(pointsTo(ValidContainer)),
|
2020-10-28 07:24:20 +08:00
|
|
|
hasType(references(ValidContainer))))
|
|
|
|
.bind("MemberCallObject")),
|
2016-12-22 07:44:23 +08:00
|
|
|
callee(cxxMethodDecl(hasName("size"))), WrongUse,
|
|
|
|
unless(hasAncestor(cxxMethodDecl(
|
|
|
|
ofClass(equalsBoundNode("container"))))))
|
2015-09-17 21:31:25 +08:00
|
|
|
.bind("SizeCallExpr"),
|
2015-01-15 23:46:58 +08:00
|
|
|
this);
|
2017-04-24 22:57:09 +08:00
|
|
|
|
2020-10-28 07:24:20 +08:00
|
|
|
Finder->addMatcher(
|
|
|
|
callExpr(has(cxxDependentScopeMemberExpr(
|
|
|
|
hasObjectExpression(
|
|
|
|
expr(anyOf(hasType(ValidContainer),
|
|
|
|
hasType(pointsTo(ValidContainer)),
|
|
|
|
hasType(references(ValidContainer))))
|
|
|
|
.bind("MemberCallObject")),
|
|
|
|
hasMemberName("size"))),
|
|
|
|
WrongUse,
|
|
|
|
unless(hasAncestor(
|
|
|
|
cxxMethodDecl(ofClass(equalsBoundNode("container"))))))
|
|
|
|
.bind("SizeCallExpr"),
|
|
|
|
this);
|
|
|
|
|
2017-04-24 22:57:09 +08:00
|
|
|
// Comparison to empty string or empty constructor.
|
|
|
|
const auto WrongComparend = anyOf(
|
2020-12-23 01:45:22 +08:00
|
|
|
stringLiteral(hasSize(0)), cxxConstructExpr(isDefaultConstruction()),
|
2020-10-28 07:24:20 +08:00
|
|
|
cxxUnresolvedConstructExpr(argumentCountIs(0)));
|
2017-04-24 22:57:09 +08:00
|
|
|
// Match the object being compared.
|
|
|
|
const auto STLArg =
|
|
|
|
anyOf(unaryOperator(
|
|
|
|
hasOperatorName("*"),
|
|
|
|
hasUnaryOperand(
|
|
|
|
expr(hasType(pointsTo(ValidContainer))).bind("Pointee"))),
|
|
|
|
expr(hasType(ValidContainer)).bind("STLObject"));
|
|
|
|
Finder->addMatcher(
|
2020-12-23 01:45:22 +08:00
|
|
|
binaryOperation(hasAnyOperatorName("==", "!="),
|
|
|
|
hasOperands(WrongComparend,
|
|
|
|
STLArg),
|
|
|
|
unless(hasAncestor(cxxMethodDecl(
|
|
|
|
ofClass(equalsBoundNode("container"))))))
|
2020-10-28 07:24:20 +08:00
|
|
|
.bind("BinCmp"),
|
|
|
|
this);
|
2015-01-15 23:46:58 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
void ContainerSizeEmptyCheck::check(const MatchFinder::MatchResult &Result) {
|
2020-10-28 07:24:20 +08:00
|
|
|
const auto *MemberCall = Result.Nodes.getNodeAs<Expr>("SizeCallExpr");
|
|
|
|
const auto *MemberCallObject =
|
|
|
|
Result.Nodes.getNodeAs<Expr>("MemberCallObject");
|
2017-04-24 22:57:09 +08:00
|
|
|
const auto *BinCmp = Result.Nodes.getNodeAs<CXXOperatorCallExpr>("BinCmp");
|
2020-10-28 07:24:20 +08:00
|
|
|
const auto *BinCmpTempl = Result.Nodes.getNodeAs<BinaryOperator>("BinCmp");
|
2021-01-03 05:18:29 +08:00
|
|
|
const auto *BinCmpRewritten =
|
|
|
|
Result.Nodes.getNodeAs<CXXRewrittenBinaryOperator>("BinCmp");
|
2015-01-15 23:46:58 +08:00
|
|
|
const auto *BinaryOp = Result.Nodes.getNodeAs<BinaryOperator>("SizeBinaryOp");
|
2017-04-24 22:57:09 +08:00
|
|
|
const auto *Pointee = Result.Nodes.getNodeAs<Expr>("Pointee");
|
|
|
|
const auto *E =
|
2020-10-28 07:24:20 +08:00
|
|
|
MemberCallObject
|
|
|
|
? MemberCallObject
|
2017-04-24 22:57:09 +08:00
|
|
|
: (Pointee ? Pointee : Result.Nodes.getNodeAs<Expr>("STLObject"));
|
2015-01-15 23:46:58 +08:00
|
|
|
FixItHint Hint;
|
2020-01-29 03:23:46 +08:00
|
|
|
std::string ReplacementText = std::string(
|
2016-09-24 10:13:45 +08:00
|
|
|
Lexer::getSourceText(CharSourceRange::getTokenRange(E->getSourceRange()),
|
2020-01-29 03:23:46 +08:00
|
|
|
*Result.SourceManager, getLangOpts()));
|
2021-11-02 15:14:25 +08:00
|
|
|
if (isBinaryOrTernary(E) || isa<UnaryOperator>(E)) {
|
2017-04-24 22:57:09 +08:00
|
|
|
ReplacementText = "(" + ReplacementText + ")";
|
|
|
|
}
|
2015-01-15 23:46:58 +08:00
|
|
|
if (E->getType()->isPointerType())
|
|
|
|
ReplacementText += "->empty()";
|
|
|
|
else
|
|
|
|
ReplacementText += ".empty()";
|
|
|
|
|
2017-04-24 22:57:09 +08:00
|
|
|
if (BinCmp) {
|
|
|
|
if (BinCmp->getOperator() == OO_ExclaimEqual) {
|
|
|
|
ReplacementText = "!" + ReplacementText;
|
|
|
|
}
|
|
|
|
Hint =
|
|
|
|
FixItHint::CreateReplacement(BinCmp->getSourceRange(), ReplacementText);
|
2020-10-28 07:24:20 +08:00
|
|
|
} else if (BinCmpTempl) {
|
|
|
|
if (BinCmpTempl->getOpcode() == BinaryOperatorKind::BO_NE) {
|
|
|
|
ReplacementText = "!" + ReplacementText;
|
|
|
|
}
|
|
|
|
Hint = FixItHint::CreateReplacement(BinCmpTempl->getSourceRange(),
|
|
|
|
ReplacementText);
|
2021-01-03 05:18:29 +08:00
|
|
|
} else if (BinCmpRewritten) {
|
|
|
|
if (BinCmpRewritten->getOpcode() == BinaryOperatorKind::BO_NE) {
|
|
|
|
ReplacementText = "!" + ReplacementText;
|
|
|
|
}
|
|
|
|
Hint = FixItHint::CreateReplacement(BinCmpRewritten->getSourceRange(),
|
|
|
|
ReplacementText);
|
2020-10-28 07:24:20 +08:00
|
|
|
} else if (BinaryOp) { // Determine the correct transformation.
|
2015-01-15 23:46:58 +08:00
|
|
|
bool Negation = false;
|
2015-12-12 19:31:25 +08:00
|
|
|
const bool ContainerIsLHS =
|
|
|
|
!llvm::isa<IntegerLiteral>(BinaryOp->getLHS()->IgnoreImpCasts());
|
2015-01-15 23:46:58 +08:00
|
|
|
const auto OpCode = BinaryOp->getOpcode();
|
|
|
|
uint64_t Value = 0;
|
|
|
|
if (ContainerIsLHS) {
|
2015-12-12 19:31:25 +08:00
|
|
|
if (const auto *Literal = llvm::dyn_cast<IntegerLiteral>(
|
|
|
|
BinaryOp->getRHS()->IgnoreImpCasts()))
|
2015-01-15 23:46:58 +08:00
|
|
|
Value = Literal->getValue().getLimitedValue();
|
|
|
|
else
|
|
|
|
return;
|
|
|
|
} else {
|
2015-12-12 19:31:25 +08:00
|
|
|
Value =
|
|
|
|
llvm::dyn_cast<IntegerLiteral>(BinaryOp->getLHS()->IgnoreImpCasts())
|
|
|
|
->getValue()
|
|
|
|
.getLimitedValue();
|
2015-01-15 23:46:58 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
// Constant that is not handled.
|
|
|
|
if (Value > 1)
|
|
|
|
return;
|
|
|
|
|
2016-04-19 21:29:05 +08:00
|
|
|
if (Value == 1 && (OpCode == BinaryOperatorKind::BO_EQ ||
|
|
|
|
OpCode == BinaryOperatorKind::BO_NE))
|
|
|
|
return;
|
|
|
|
|
2015-01-15 23:46:58 +08:00
|
|
|
// Always true, no warnings for that.
|
|
|
|
if ((OpCode == BinaryOperatorKind::BO_GE && Value == 0 && ContainerIsLHS) ||
|
|
|
|
(OpCode == BinaryOperatorKind::BO_LE && Value == 0 && !ContainerIsLHS))
|
|
|
|
return;
|
|
|
|
|
2015-12-29 01:20:33 +08:00
|
|
|
// Do not warn for size > 1, 1 < size, size <= 1, 1 >= size.
|
|
|
|
if (Value == 1) {
|
|
|
|
if ((OpCode == BinaryOperatorKind::BO_GT && ContainerIsLHS) ||
|
|
|
|
(OpCode == BinaryOperatorKind::BO_LT && !ContainerIsLHS))
|
|
|
|
return;
|
|
|
|
if ((OpCode == BinaryOperatorKind::BO_LE && ContainerIsLHS) ||
|
|
|
|
(OpCode == BinaryOperatorKind::BO_GE && !ContainerIsLHS))
|
|
|
|
return;
|
|
|
|
}
|
2015-12-21 17:43:52 +08:00
|
|
|
|
2015-01-15 23:46:58 +08:00
|
|
|
if (OpCode == BinaryOperatorKind::BO_NE && Value == 0)
|
|
|
|
Negation = true;
|
|
|
|
if ((OpCode == BinaryOperatorKind::BO_GT ||
|
|
|
|
OpCode == BinaryOperatorKind::BO_GE) &&
|
|
|
|
ContainerIsLHS)
|
|
|
|
Negation = true;
|
|
|
|
if ((OpCode == BinaryOperatorKind::BO_LT ||
|
|
|
|
OpCode == BinaryOperatorKind::BO_LE) &&
|
|
|
|
!ContainerIsLHS)
|
|
|
|
Negation = true;
|
|
|
|
|
|
|
|
if (Negation)
|
|
|
|
ReplacementText = "!" + ReplacementText;
|
|
|
|
Hint = FixItHint::CreateReplacement(BinaryOp->getSourceRange(),
|
|
|
|
ReplacementText);
|
|
|
|
|
|
|
|
} else {
|
|
|
|
// If there is a conversion above the size call to bool, it is safe to just
|
|
|
|
// replace size with empty.
|
|
|
|
if (const auto *UnaryOp =
|
|
|
|
Result.Nodes.getNodeAs<UnaryOperator>("NegOnSize"))
|
|
|
|
Hint = FixItHint::CreateReplacement(UnaryOp->getSourceRange(),
|
|
|
|
ReplacementText);
|
|
|
|
else
|
|
|
|
Hint = FixItHint::CreateReplacement(MemberCall->getSourceRange(),
|
|
|
|
"!" + ReplacementText);
|
|
|
|
}
|
2016-09-13 16:58:11 +08:00
|
|
|
|
2020-10-28 07:24:20 +08:00
|
|
|
auto WarnLoc = MemberCall ? MemberCall->getBeginLoc() : SourceLocation{};
|
|
|
|
|
|
|
|
if (WarnLoc.isValid()) {
|
|
|
|
diag(WarnLoc, "the 'empty' method should be used to check "
|
|
|
|
"for emptiness instead of 'size'")
|
2017-04-24 22:57:09 +08:00
|
|
|
<< Hint;
|
|
|
|
} else {
|
2021-01-03 05:18:29 +08:00
|
|
|
WarnLoc = BinCmpTempl
|
|
|
|
? BinCmpTempl->getBeginLoc()
|
|
|
|
: (BinCmp ? BinCmp->getBeginLoc()
|
|
|
|
: (BinCmpRewritten ? BinCmpRewritten->getBeginLoc()
|
|
|
|
: SourceLocation{}));
|
2020-10-28 07:24:20 +08:00
|
|
|
diag(WarnLoc, "the 'empty' method should be used to check "
|
|
|
|
"for emptiness instead of comparing to an empty object")
|
2017-04-24 22:57:09 +08:00
|
|
|
<< Hint;
|
|
|
|
}
|
2016-09-13 16:58:11 +08:00
|
|
|
|
|
|
|
const auto *Container = Result.Nodes.getNodeAs<NamedDecl>("container");
|
2018-11-27 18:53:44 +08:00
|
|
|
if (const auto *CTS = dyn_cast<ClassTemplateSpecializationDecl>(Container)) {
|
|
|
|
// The definition of the empty() method is the same for all implicit
|
|
|
|
// instantiations. In order to avoid duplicate or inconsistent warnings
|
|
|
|
// (depending on how deduplication is done), we use the same class name
|
|
|
|
// for all implicit instantiations of a template.
|
|
|
|
if (CTS->getSpecializationKind() == TSK_ImplicitInstantiation)
|
|
|
|
Container = CTS->getSpecializedTemplate();
|
|
|
|
}
|
2016-09-13 16:58:11 +08:00
|
|
|
const auto *Empty = Result.Nodes.getNodeAs<FunctionDecl>("empty");
|
|
|
|
|
|
|
|
diag(Empty->getLocation(), "method %0::empty() defined here",
|
|
|
|
DiagnosticIDs::Note)
|
|
|
|
<< Container;
|
2015-01-15 23:46:58 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
} // namespace readability
|
|
|
|
} // namespace tidy
|
|
|
|
} // namespace clang
|