blob: 4a1f7e5ab1ae062912356f2b3ee9e6d7ee28bf02 [file] [log] [blame]
Alexander Kornienko1b677db2015-03-09 12:18:39 +00001//===--- ContainerSizeEmptyCheck.cpp - clang-tidy -------------------------===//
Alexander Kornienko4babd682015-01-15 15:46:58 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
Alexander Kornienko1b677db2015-03-09 12:18:39 +00009#include "ContainerSizeEmptyCheck.h"
Alexander Kornienko4babd682015-01-15 15:46:58 +000010#include "clang/AST/ASTContext.h"
11#include "clang/ASTMatchers/ASTMatchers.h"
Alexander Kornienko4babd682015-01-15 15:46:58 +000012#include "clang/Lex/Lexer.h"
Chandler Carruthf7662782015-02-13 09:07:58 +000013#include "llvm/ADT/StringRef.h"
Alexander Kornienko4babd682015-01-15 15:46:58 +000014
15using namespace clang::ast_matchers;
16
Benjamin Kramer73d27492015-04-17 13:52:08 +000017static bool isContainer(llvm::StringRef ClassName) {
18 static const char *ContainerNames[] = {
19 "std::array",
20 "std::deque",
21 "std::forward_list",
22 "std::list",
23 "std::map",
24 "std::multimap",
25 "std::multiset",
26 "std::priority_queue",
27 "std::queue",
28 "std::set",
29 "std::stack",
30 "std::unordered_map",
31 "std::unordered_multimap",
32 "std::unordered_multiset",
33 "std::unordered_set",
34 "std::vector"
35 };
36 return std::binary_search(std::begin(ContainerNames),
37 std::end(ContainerNames), ClassName);
Alexander Kornienko4babd682015-01-15 15:46:58 +000038}
Alexander Kornienko4babd682015-01-15 15:46:58 +000039
40namespace clang {
Alexander Kornienko50d7f4612015-06-17 13:11:37 +000041namespace {
Alexander Kornienkofebfd3452015-01-22 12:27:09 +000042AST_MATCHER(QualType, isBoolType) { return Node->isBooleanType(); }
Alexander Kornienko4babd682015-01-15 15:46:58 +000043
44AST_MATCHER(NamedDecl, stlContainer) {
45 return isContainer(Node.getQualifiedNameAsString());
46}
Alexander Kornienko50d7f4612015-06-17 13:11:37 +000047} // namespace
Alexander Kornienko4babd682015-01-15 15:46:58 +000048
Alexander Kornienko4babd682015-01-15 15:46:58 +000049namespace tidy {
50namespace readability {
51
52ContainerSizeEmptyCheck::ContainerSizeEmptyCheck(StringRef Name,
53 ClangTidyContext *Context)
54 : ClangTidyCheck(Name, Context) {}
55
56void ContainerSizeEmptyCheck::registerMatchers(MatchFinder *Finder) {
57 const auto WrongUse = anyOf(
58 hasParent(
59 binaryOperator(
60 anyOf(has(integerLiteral(equals(0))),
61 allOf(anyOf(hasOperatorName("<"), hasOperatorName(">="),
62 hasOperatorName(">"), hasOperatorName("<=")),
Alexander Kornienkoa6354ca2015-01-23 14:43:06 +000063 hasEitherOperand(integerLiteral(equals(1))))))
Alexander Kornienko4babd682015-01-15 15:46:58 +000064 .bind("SizeBinaryOp")),
65 hasParent(implicitCastExpr(
Alexander Kornienkofebfd3452015-01-22 12:27:09 +000066 hasImplicitDestinationType(isBoolType()),
Alexander Kornienko4babd682015-01-15 15:46:58 +000067 anyOf(
68 hasParent(unaryOperator(hasOperatorName("!")).bind("NegOnSize")),
69 anything()))),
Alexander Kornienkofebfd3452015-01-22 12:27:09 +000070 hasParent(explicitCastExpr(hasDestinationType(isBoolType()))));
Alexander Kornienko4babd682015-01-15 15:46:58 +000071
72 Finder->addMatcher(
73 memberCallExpr(
74 on(expr(anyOf(hasType(namedDecl(stlContainer())),
Alexander Kornienkofebfd3452015-01-22 12:27:09 +000075 hasType(pointsTo(namedDecl(stlContainer()))),
76 hasType(references(namedDecl(stlContainer())))))
77 .bind("STLObject")),
Alexander Kornienko4babd682015-01-15 15:46:58 +000078 callee(methodDecl(hasName("size"))), WrongUse).bind("SizeCallExpr"),
79 this);
80}
81
82void ContainerSizeEmptyCheck::check(const MatchFinder::MatchResult &Result) {
83 const auto *MemberCall =
84 Result.Nodes.getNodeAs<CXXMemberCallExpr>("SizeCallExpr");
85 const auto *BinaryOp = Result.Nodes.getNodeAs<BinaryOperator>("SizeBinaryOp");
86 const auto *E = Result.Nodes.getNodeAs<Expr>("STLObject");
87 FixItHint Hint;
Alexander Kornienko96e7b8b2015-01-22 12:40:47 +000088 std::string ReplacementText = Lexer::getSourceText(
89 CharSourceRange::getTokenRange(E->getSourceRange()),
90 *Result.SourceManager, Result.Context->getLangOpts());
Alexander Kornienko4babd682015-01-15 15:46:58 +000091 if (E->getType()->isPointerType())
92 ReplacementText += "->empty()";
93 else
94 ReplacementText += ".empty()";
95
96 if (BinaryOp) { // Determine the correct transformation.
97 bool Negation = false;
98 const bool ContainerIsLHS = !llvm::isa<IntegerLiteral>(BinaryOp->getLHS());
99 const auto OpCode = BinaryOp->getOpcode();
100 uint64_t Value = 0;
101 if (ContainerIsLHS) {
102 if (const auto *Literal =
103 llvm::dyn_cast<IntegerLiteral>(BinaryOp->getRHS()))
104 Value = Literal->getValue().getLimitedValue();
105 else
106 return;
107 } else {
108 Value = llvm::dyn_cast<IntegerLiteral>(BinaryOp->getLHS())
109 ->getValue()
110 .getLimitedValue();
111 }
112
113 // Constant that is not handled.
114 if (Value > 1)
115 return;
116
117 // Always true, no warnings for that.
118 if ((OpCode == BinaryOperatorKind::BO_GE && Value == 0 && ContainerIsLHS) ||
119 (OpCode == BinaryOperatorKind::BO_LE && Value == 0 && !ContainerIsLHS))
120 return;
121
122 if (OpCode == BinaryOperatorKind::BO_NE && Value == 0)
123 Negation = true;
124 if ((OpCode == BinaryOperatorKind::BO_GT ||
125 OpCode == BinaryOperatorKind::BO_GE) &&
126 ContainerIsLHS)
127 Negation = true;
128 if ((OpCode == BinaryOperatorKind::BO_LT ||
129 OpCode == BinaryOperatorKind::BO_LE) &&
130 !ContainerIsLHS)
131 Negation = true;
132
133 if (Negation)
134 ReplacementText = "!" + ReplacementText;
135 Hint = FixItHint::CreateReplacement(BinaryOp->getSourceRange(),
136 ReplacementText);
137
138 } else {
139 // If there is a conversion above the size call to bool, it is safe to just
140 // replace size with empty.
141 if (const auto *UnaryOp =
142 Result.Nodes.getNodeAs<UnaryOperator>("NegOnSize"))
143 Hint = FixItHint::CreateReplacement(UnaryOp->getSourceRange(),
144 ReplacementText);
145 else
146 Hint = FixItHint::CreateReplacement(MemberCall->getSourceRange(),
147 "!" + ReplacementText);
148 }
149 diag(MemberCall->getLocStart(),
150 "The 'empty' method should be used to check for emptiness instead "
151 "of 'size'.")
152 << Hint;
153}
154
155} // namespace readability
156} // namespace tidy
157} // namespace clang