blob: 2734b25c282910c750afbcc4d5e22fcb3455281e [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 {
41namespace ast_matchers {
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 Kornienkodf0ab6a2015-03-04 18:01:10 +000047} // namespace ast_matchers
48} // namespace clang
Alexander Kornienko4babd682015-01-15 15:46:58 +000049
50namespace clang {
51namespace tidy {
52namespace readability {
53
54ContainerSizeEmptyCheck::ContainerSizeEmptyCheck(StringRef Name,
55 ClangTidyContext *Context)
56 : ClangTidyCheck(Name, Context) {}
57
58void ContainerSizeEmptyCheck::registerMatchers(MatchFinder *Finder) {
59 const auto WrongUse = anyOf(
60 hasParent(
61 binaryOperator(
62 anyOf(has(integerLiteral(equals(0))),
63 allOf(anyOf(hasOperatorName("<"), hasOperatorName(">="),
64 hasOperatorName(">"), hasOperatorName("<=")),
Alexander Kornienkoa6354ca2015-01-23 14:43:06 +000065 hasEitherOperand(integerLiteral(equals(1))))))
Alexander Kornienko4babd682015-01-15 15:46:58 +000066 .bind("SizeBinaryOp")),
67 hasParent(implicitCastExpr(
Alexander Kornienkofebfd3452015-01-22 12:27:09 +000068 hasImplicitDestinationType(isBoolType()),
Alexander Kornienko4babd682015-01-15 15:46:58 +000069 anyOf(
70 hasParent(unaryOperator(hasOperatorName("!")).bind("NegOnSize")),
71 anything()))),
Alexander Kornienkofebfd3452015-01-22 12:27:09 +000072 hasParent(explicitCastExpr(hasDestinationType(isBoolType()))));
Alexander Kornienko4babd682015-01-15 15:46:58 +000073
74 Finder->addMatcher(
75 memberCallExpr(
76 on(expr(anyOf(hasType(namedDecl(stlContainer())),
Alexander Kornienkofebfd3452015-01-22 12:27:09 +000077 hasType(pointsTo(namedDecl(stlContainer()))),
78 hasType(references(namedDecl(stlContainer())))))
79 .bind("STLObject")),
Alexander Kornienko4babd682015-01-15 15:46:58 +000080 callee(methodDecl(hasName("size"))), WrongUse).bind("SizeCallExpr"),
81 this);
82}
83
84void ContainerSizeEmptyCheck::check(const MatchFinder::MatchResult &Result) {
85 const auto *MemberCall =
86 Result.Nodes.getNodeAs<CXXMemberCallExpr>("SizeCallExpr");
87 const auto *BinaryOp = Result.Nodes.getNodeAs<BinaryOperator>("SizeBinaryOp");
88 const auto *E = Result.Nodes.getNodeAs<Expr>("STLObject");
89 FixItHint Hint;
Alexander Kornienko96e7b8b2015-01-22 12:40:47 +000090 std::string ReplacementText = Lexer::getSourceText(
91 CharSourceRange::getTokenRange(E->getSourceRange()),
92 *Result.SourceManager, Result.Context->getLangOpts());
Alexander Kornienko4babd682015-01-15 15:46:58 +000093 if (E->getType()->isPointerType())
94 ReplacementText += "->empty()";
95 else
96 ReplacementText += ".empty()";
97
98 if (BinaryOp) { // Determine the correct transformation.
99 bool Negation = false;
100 const bool ContainerIsLHS = !llvm::isa<IntegerLiteral>(BinaryOp->getLHS());
101 const auto OpCode = BinaryOp->getOpcode();
102 uint64_t Value = 0;
103 if (ContainerIsLHS) {
104 if (const auto *Literal =
105 llvm::dyn_cast<IntegerLiteral>(BinaryOp->getRHS()))
106 Value = Literal->getValue().getLimitedValue();
107 else
108 return;
109 } else {
110 Value = llvm::dyn_cast<IntegerLiteral>(BinaryOp->getLHS())
111 ->getValue()
112 .getLimitedValue();
113 }
114
115 // Constant that is not handled.
116 if (Value > 1)
117 return;
118
119 // Always true, no warnings for that.
120 if ((OpCode == BinaryOperatorKind::BO_GE && Value == 0 && ContainerIsLHS) ||
121 (OpCode == BinaryOperatorKind::BO_LE && Value == 0 && !ContainerIsLHS))
122 return;
123
124 if (OpCode == BinaryOperatorKind::BO_NE && Value == 0)
125 Negation = true;
126 if ((OpCode == BinaryOperatorKind::BO_GT ||
127 OpCode == BinaryOperatorKind::BO_GE) &&
128 ContainerIsLHS)
129 Negation = true;
130 if ((OpCode == BinaryOperatorKind::BO_LT ||
131 OpCode == BinaryOperatorKind::BO_LE) &&
132 !ContainerIsLHS)
133 Negation = true;
134
135 if (Negation)
136 ReplacementText = "!" + ReplacementText;
137 Hint = FixItHint::CreateReplacement(BinaryOp->getSourceRange(),
138 ReplacementText);
139
140 } else {
141 // If there is a conversion above the size call to bool, it is safe to just
142 // replace size with empty.
143 if (const auto *UnaryOp =
144 Result.Nodes.getNodeAs<UnaryOperator>("NegOnSize"))
145 Hint = FixItHint::CreateReplacement(UnaryOp->getSourceRange(),
146 ReplacementText);
147 else
148 Hint = FixItHint::CreateReplacement(MemberCall->getSourceRange(),
149 "!" + ReplacementText);
150 }
151 diag(MemberCall->getLocStart(),
152 "The 'empty' method should be used to check for emptiness instead "
153 "of 'size'.")
154 << Hint;
155}
156
157} // namespace readability
158} // namespace tidy
159} // namespace clang