10 #include "../utils/ASTUtils.h" 11 #include "../utils/Matchers.h" 12 #include "clang/AST/ASTContext.h" 13 #include "clang/ASTMatchers/ASTMatchers.h" 14 #include "clang/Lex/Lexer.h" 15 #include "llvm/ADT/StringRef.h" 21 namespace readability {
25 ContainerSizeEmptyCheck::ContainerSizeEmptyCheck(StringRef
Name,
35 const auto ValidContainer = qualType(hasUnqualifiedDesugaredType(
36 recordType(hasDeclaration(cxxRecordDecl(isSameOrDerivedFrom(
39 isConst(), parameterCountIs(0),
isPublic(),
41 returns(qualType(isInteger(), unless(booleanType()))))
43 has(cxxMethodDecl(isConst(), parameterCountIs(0),
isPublic(),
44 hasName(
"empty"), returns(booleanType()))
46 .bind(
"container")))))));
48 const auto WrongUse = anyOf(
49 hasParent(binaryOperator(
50 matchers::isComparisonOperator(),
51 hasEitherOperand(ignoringImpCasts(anyOf(
52 integerLiteral(equals(1)), integerLiteral(equals(0))))))
53 .bind(
"SizeBinaryOp")),
54 hasParent(implicitCastExpr(
55 hasImplicitDestinationType(booleanType()),
57 hasParent(unaryOperator(hasOperatorName(
"!")).bind(
"NegOnSize")),
59 hasParent(explicitCastExpr(hasDestinationType(booleanType()))));
62 cxxMemberCallExpr(on(expr(anyOf(hasType(ValidContainer),
63 hasType(pointsTo(ValidContainer)),
64 hasType(references(ValidContainer))))),
65 callee(cxxMethodDecl(hasName(
"size"))), WrongUse,
66 unless(hasAncestor(cxxMethodDecl(
67 ofClass(equalsBoundNode(
"container"))))))
68 .bind(
"SizeCallExpr"),
72 const auto DefaultConstructor = cxxConstructExpr(
73 hasDeclaration(cxxConstructorDecl(isDefaultConstructor())));
75 const auto WrongComparend = anyOf(
76 ignoringImpCasts(stringLiteral(hasSize(0))),
77 ignoringImpCasts(cxxBindTemporaryExpr(has(DefaultConstructor))),
78 ignoringImplicit(DefaultConstructor),
80 hasDeclaration(cxxConstructorDecl(isCopyConstructor())),
81 has(expr(ignoringImpCasts(DefaultConstructor)))),
83 hasDeclaration(cxxConstructorDecl(isMoveConstructor())),
84 has(expr(ignoringImpCasts(DefaultConstructor)))));
90 expr(hasType(pointsTo(ValidContainer))).bind(
"Pointee"))),
91 expr(hasType(ValidContainer)).bind(
"STLObject"));
94 anyOf(hasOverloadedOperatorName(
"=="),
95 hasOverloadedOperatorName(
"!=")),
96 anyOf(allOf(hasArgument(0, WrongComparend), hasArgument(1, STLArg)),
97 allOf(hasArgument(0, STLArg), hasArgument(1, WrongComparend))),
99 cxxMethodDecl(ofClass(equalsBoundNode(
"container"))))))
105 const auto *MemberCall =
106 Result.Nodes.getNodeAs<CXXMemberCallExpr>(
"SizeCallExpr");
107 const auto *BinCmp = Result.Nodes.getNodeAs<CXXOperatorCallExpr>(
"BinCmp");
108 const auto *BinaryOp = Result.Nodes.getNodeAs<BinaryOperator>(
"SizeBinaryOp");
109 const auto *Pointee = Result.Nodes.getNodeAs<Expr>(
"Pointee");
112 ? MemberCall->getImplicitObjectArgument()
113 : (Pointee ? Pointee : Result.Nodes.getNodeAs<Expr>(
"STLObject"));
115 std::string ReplacementText =
116 Lexer::getSourceText(CharSourceRange::getTokenRange(E->getSourceRange()),
120 ReplacementText =
"(" + ReplacementText +
")";
122 if (E->getType()->isPointerType())
123 ReplacementText +=
"->empty()";
125 ReplacementText +=
".empty()";
128 if (BinCmp->getOperator() == OO_ExclaimEqual) {
129 ReplacementText =
"!" + ReplacementText;
132 FixItHint::CreateReplacement(BinCmp->getSourceRange(), ReplacementText);
133 }
else if (BinaryOp) {
134 bool Negation =
false;
135 const bool ContainerIsLHS =
136 !llvm::isa<IntegerLiteral>(BinaryOp->getLHS()->IgnoreImpCasts());
137 const auto OpCode = BinaryOp->getOpcode();
139 if (ContainerIsLHS) {
140 if (
const auto *Literal = llvm::dyn_cast<IntegerLiteral>(
141 BinaryOp->getRHS()->IgnoreImpCasts()))
142 Value = Literal->getValue().getLimitedValue();
147 llvm::dyn_cast<IntegerLiteral>(BinaryOp->getLHS()->IgnoreImpCasts())
156 if (Value == 1 && (OpCode == BinaryOperatorKind::BO_EQ ||
157 OpCode == BinaryOperatorKind::BO_NE))
161 if ((OpCode == BinaryOperatorKind::BO_GE && Value == 0 && ContainerIsLHS) ||
162 (OpCode == BinaryOperatorKind::BO_LE && Value == 0 && !ContainerIsLHS))
167 if ((OpCode == BinaryOperatorKind::BO_GT && ContainerIsLHS) ||
168 (OpCode == BinaryOperatorKind::BO_LT && !ContainerIsLHS))
170 if ((OpCode == BinaryOperatorKind::BO_LE && ContainerIsLHS) ||
171 (OpCode == BinaryOperatorKind::BO_GE && !ContainerIsLHS))
175 if (OpCode == BinaryOperatorKind::BO_NE && Value == 0)
177 if ((OpCode == BinaryOperatorKind::BO_GT ||
178 OpCode == BinaryOperatorKind::BO_GE) &&
181 if ((OpCode == BinaryOperatorKind::BO_LT ||
182 OpCode == BinaryOperatorKind::BO_LE) &&
187 ReplacementText =
"!" + ReplacementText;
188 Hint = FixItHint::CreateReplacement(BinaryOp->getSourceRange(),
194 if (
const auto *UnaryOp =
195 Result.Nodes.getNodeAs<UnaryOperator>(
"NegOnSize"))
196 Hint = FixItHint::CreateReplacement(UnaryOp->getSourceRange(),
199 Hint = FixItHint::CreateReplacement(MemberCall->getSourceRange(),
200 "!" + ReplacementText);
204 diag(MemberCall->getBeginLoc(),
205 "the 'empty' method should be used to check " 206 "for emptiness instead of 'size'")
209 diag(BinCmp->getBeginLoc(),
210 "the 'empty' method should be used to check " 211 "for emptiness instead of comparing to an empty object")
215 const auto *Container = Result.Nodes.getNodeAs<NamedDecl>(
"container");
216 if (
const auto *CTS = dyn_cast<ClassTemplateSpecializationDecl>(Container)) {
221 if (CTS->getSpecializationKind() == TSK_ImplicitInstantiation)
222 Container = CTS->getSpecializedTemplate();
224 const auto *
Empty = Result.Nodes.getNodeAs<FunctionDecl>(
"empty");
226 diag(
Empty->getLocation(),
"method %0::empty() defined here",
bool IsBinaryOrTernary(const Expr *E)
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
ClangTidyChecks that register ASTMatchers should do the actual work in here.
LangOptions getLangOpts() const
Returns the language options from the context.
Base class for all clang-tidy checks.
void registerMatchers(ast_matchers::MatchFinder *Finder) override
Override this to register AST matchers with Finder.
static constexpr llvm::StringLiteral Name
llvm::Optional< llvm::Expected< tooling::AtomicChanges > > Result
static bool isPublic(const clang::AccessSpecifier AS, const clang::Linkage Link)
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
Every ClangTidyCheck reports errors through a DiagnosticsEngine provided by this context.
DiagnosticBuilder diag(SourceLocation Loc, StringRef Description, DiagnosticIDs::Level Level=DiagnosticIDs::Warning)
Add a diagnostic with the check's name.