clang-tools 24.0.0git
UseStartsEndsWithCheck.cpp
Go to the documentation of this file.
1//===----------------------------------------------------------------------===//
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
10
11#include "../utils/ASTUtils.h"
12#include "../utils/Matchers.h"
13#include "clang/ASTMatchers/ASTMatchers.h"
14#include "clang/Lex/Lexer.h"
15
16#include <string>
17
18using namespace clang::ast_matchers;
19
20namespace clang::tidy::modernize {
21
22static bool isNegativeComparison(const Expr *ComparisonExpr) {
23 if (const auto *Op = dyn_cast<BinaryOperator>(ComparisonExpr))
24 return Op->getOpcode() == BO_NE;
25
26 if (const auto *Op = dyn_cast<CXXOperatorCallExpr>(ComparisonExpr))
27 return Op->getOperator() == OO_ExclaimEqual;
28
29 if (const auto *Op = dyn_cast<CXXRewrittenBinaryOperator>(ComparisonExpr))
30 return Op->getOperator() == BO_NE;
31
32 return false;
33}
34
35namespace {
36
37struct NotLengthExprForStringNode {
38 NotLengthExprForStringNode(std::string ID, DynTypedNode Node,
39 ASTContext *Context)
40 : ID(std::move(ID)), Node(std::move(Node)), Context(Context) {}
41 bool operator()(const internal::BoundNodesMap &Nodes) const {
42 // Match a string literal and an integer size or strlen() call.
43 if (const auto *StringLiteralNode = Nodes.getNodeAs<StringLiteral>(ID)) {
44 if (const auto *IntegerLiteralSizeNode = Node.get<IntegerLiteral>()) {
45 return StringLiteralNode->getLength() !=
46 IntegerLiteralSizeNode->getValue().getZExtValue();
47 }
48
49 if (const auto *StrlenNode = Node.get<CallExpr>()) {
50 if (StrlenNode->getDirectCallee()->getName() != "strlen" ||
51 StrlenNode->getNumArgs() != 1) {
52 return true;
53 }
54
55 if (const auto *StrlenArgNode = dyn_cast<StringLiteral>(
56 StrlenNode->getArg(0)->IgnoreParenImpCasts())) {
57 return StrlenArgNode->getLength() != StringLiteralNode->getLength();
58 }
59 }
60 }
61
62 // Match a string variable and a call to length() or size().
63 if (const auto *ExprNode = Nodes.getNodeAs<Expr>(ID)) {
64 if (const auto *MemberCallNode = Node.get<CXXMemberCallExpr>()) {
65 const CXXMethodDecl *MethodDeclNode = MemberCallNode->getMethodDecl();
66 const StringRef Name = MethodDeclNode->getName();
67 if (!MethodDeclNode->isConst() || MethodDeclNode->getNumParams() != 0 ||
68 (Name != "size" && Name != "length")) {
69 return true;
70 }
71
72 if (const Expr *OnNode = MemberCallNode->getImplicitObjectArgument()) {
73 return !utils::areStatementsIdentical(OnNode->IgnoreParenImpCasts(),
74 ExprNode->IgnoreParenImpCasts(),
75 *Context);
76 }
77 }
78 }
79
80 return true;
81 }
82
83private:
84 std::string ID;
85 DynTypedNode Node;
86 ASTContext *Context;
87};
88
89AST_MATCHER_P(Expr, lengthExprForStringNode, std::string, ID) {
90 return Builder->removeBindings(NotLengthExprForStringNode(
91 ID, DynTypedNode::create(Node), &Finder->getASTContext()));
92}
93
94} // namespace
95
97 ClangTidyContext *Context)
98 : ClangTidyCheck(Name, Context) {}
99
101 const auto ZeroLiteral = integerLiteral(equals(0));
102
103 const auto ClassTypeWithMethod = [](const StringRef MethodBoundName,
104 const auto... Methods) {
105 return cxxRecordDecl(anyOf(
106 hasMethod(cxxMethodDecl(isConst(), parameterCountIs(1),
107 returns(booleanType()), hasAnyName(Methods))
108 .bind(MethodBoundName))...));
109 };
110
111 const auto OnClassWithStartsWithFunction =
112 ClassTypeWithMethod("starts_with_fun", "starts_with", "startsWith",
113 "startswith", "StartsWith");
114
115 const auto OnClassWithEndsWithFunction = ClassTypeWithMethod(
116 "ends_with_fun", "ends_with", "endsWith", "endswith", "EndsWith");
117
118 // Case 1: X.find(Y, [0], [LEN(Y)]) [!=]= 0 -> starts_with.
119 const auto FindExpr = cxxMemberCallExpr(
120 callee(
121 cxxMethodDecl(hasName("find"), ofClass(OnClassWithStartsWithFunction))
122 .bind("find_fun")),
123 hasArgument(0, expr().bind("needle")),
124 anyOf(
125 // Detect the expression: X.find(Y);
126 argumentCountIs(1),
127 // Detect the expression: X.find(Y, 0);
128 allOf(argumentCountIs(2), hasArgument(1, ZeroLiteral)),
129 // Detect the expression: X.find(Y, 0, LEN(Y));
130 allOf(argumentCountIs(3), hasArgument(1, ZeroLiteral),
131 hasArgument(2, lengthExprForStringNode("needle")))));
132
133 // Case 2: X.rfind(Y, 0, [LEN(Y)]) [!=]= 0 -> starts_with.
134 const auto RFindExpr = cxxMemberCallExpr(
135 callee(cxxMethodDecl(hasName("rfind"),
136 ofClass(OnClassWithStartsWithFunction))
137 .bind("find_fun")),
138 hasArgument(0, expr().bind("needle")),
139 anyOf(
140 // Detect the expression: X.rfind(Y, 0);
141 allOf(argumentCountIs(2), hasArgument(1, ZeroLiteral)),
142 // Detect the expression: X.rfind(Y, 0, LEN(Y));
143 allOf(argumentCountIs(3), hasArgument(1, ZeroLiteral),
144 hasArgument(2, lengthExprForStringNode("needle")))));
145
146 // Case 3: X.compare(0, LEN(Y), Y) [!=]= 0 -> starts_with.
147 const auto CompareExpr = cxxMemberCallExpr(
148 argumentCountIs(3), hasArgument(0, ZeroLiteral),
149 callee(cxxMethodDecl(hasName("compare"),
150 ofClass(OnClassWithStartsWithFunction))
151 .bind("find_fun")),
152 hasArgument(2, expr().bind("needle")),
153 hasArgument(1, lengthExprForStringNode("needle")));
154
155 // Case 4: X.compare(LEN(X) - LEN(Y), LEN(Y), Y) [!=]= 0 -> ends_with.
156 const auto CompareEndsWithExpr = cxxMemberCallExpr(
157 argumentCountIs(3),
158 callee(cxxMethodDecl(hasName("compare"),
159 ofClass(OnClassWithEndsWithFunction))
160 .bind("find_fun")),
161 on(expr().bind("haystack")), hasArgument(2, expr().bind("needle")),
162 hasArgument(1, lengthExprForStringNode("needle")),
163 hasArgument(0,
164 binaryOperator(hasOperatorName("-"),
165 hasLHS(lengthExprForStringNode("haystack")),
166 hasRHS(lengthExprForStringNode("needle")))));
167
168 // All cases comparing to 0.
169 Finder->addMatcher(
170 binaryOperator(
171 matchers::isEqualityOperator(),
172 hasOperands(cxxMemberCallExpr(anyOf(FindExpr, RFindExpr, CompareExpr,
173 CompareEndsWithExpr))
174 .bind("find_expr"),
175 ZeroLiteral))
176 .bind("expr"),
177 this);
178
179 // Case 5: X.rfind(Y) [!=]= LEN(X) - LEN(Y) -> ends_with.
180 Finder->addMatcher(
181 binaryOperator(
182 matchers::isEqualityOperator(),
183 hasOperands(
184 cxxMemberCallExpr(
185 anyOf(
186 argumentCountIs(1),
187 allOf(argumentCountIs(2),
188 hasArgument(
189 1,
190 anyOf(declRefExpr(to(varDecl(hasName("npos")))),
191 memberExpr(member(hasName("npos"))))))),
192 callee(cxxMethodDecl(hasName("rfind"),
193 ofClass(OnClassWithEndsWithFunction))
194 .bind("find_fun")),
195 on(expr().bind("haystack")),
196 hasArgument(0, expr().bind("needle")))
197 .bind("find_expr"),
198 binaryOperator(hasOperatorName("-"),
199 hasLHS(lengthExprForStringNode("haystack")),
200 hasRHS(lengthExprForStringNode("needle")))))
201 .bind("expr"),
202 this);
203
204 // Case 6: X.substr(0, LEN(Y)) [!=]= Y -> starts_with.
205 Finder->addMatcher(
206 binaryOperation(
207 hasAnyOperatorName("==", "!="),
208 hasOperands(
209 expr().bind("needle"),
210 cxxMemberCallExpr(
211 argumentCountIs(2), hasArgument(0, ZeroLiteral),
212 hasArgument(1, lengthExprForStringNode("needle")),
213 callee(cxxMethodDecl(hasName("substr"),
214 ofClass(OnClassWithStartsWithFunction))
215 .bind("find_fun")))
216 .bind("find_expr")))
217 .bind("expr"),
218 this);
219}
220
221void UseStartsEndsWithCheck::check(const MatchFinder::MatchResult &Result) {
222 const auto *ComparisonExpr = Result.Nodes.getNodeAs<Expr>("expr");
223 const auto *FindExpr = Result.Nodes.getNodeAs<CXXMemberCallExpr>("find_expr");
224 const auto *FindFun = Result.Nodes.getNodeAs<CXXMethodDecl>("find_fun");
225 const auto *SearchExpr = Result.Nodes.getNodeAs<Expr>("needle");
226 const auto *StartsWithFunction =
227 Result.Nodes.getNodeAs<CXXMethodDecl>("starts_with_fun");
228 const auto *EndsWithFunction =
229 Result.Nodes.getNodeAs<CXXMethodDecl>("ends_with_fun");
230 assert(bool(StartsWithFunction) != bool(EndsWithFunction));
231
232 const CXXMethodDecl *ReplacementFunction =
233 StartsWithFunction ? StartsWithFunction : EndsWithFunction;
234
235 if (ComparisonExpr->getBeginLoc().isMacroID() ||
236 FindExpr->getBeginLoc().isMacroID())
237 return;
238
239 // Make sure FindExpr->getArg(0) can be used to make a range in the FitItHint.
240 if (FindExpr->getNumArgs() == 0)
241 return;
242
243 // Retrieve the source text of the search expression.
244 const auto SearchExprText = Lexer::getSourceText(
245 CharSourceRange::getTokenRange(SearchExpr->getSourceRange()),
246 *Result.SourceManager, Result.Context->getLangOpts());
247
248 const auto Diagnostic = diag(FindExpr->getExprLoc(), "use %0 instead of %1")
249 << ReplacementFunction->getName()
250 << FindFun->getName();
251
252 // Remove everything before the function call.
253 Diagnostic << FixItHint::CreateRemoval(CharSourceRange::getCharRange(
254 ComparisonExpr->getBeginLoc(), FindExpr->getBeginLoc()));
255
256 // Rename the function to `starts_with` or `ends_with`.
257 Diagnostic << FixItHint::CreateReplacement(FindExpr->getExprLoc(),
258 ReplacementFunction->getName());
259
260 // Replace arguments and everything after the function call.
261 Diagnostic << FixItHint::CreateReplacement(
262 CharSourceRange::getTokenRange(FindExpr->getArg(0)->getBeginLoc(),
263 ComparisonExpr->getEndLoc()),
264 (SearchExprText + ")").str());
265
266 // Add negation if necessary.
267 if (isNegativeComparison(ComparisonExpr))
268 Diagnostic << FixItHint::CreateInsertion(FindExpr->getBeginLoc(), "!");
269}
270
271} // namespace clang::tidy::modernize
Every ClangTidyCheck reports errors through a DiagnosticsEngine provided by this context.
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
void registerMatchers(ast_matchers::MatchFinder *Finder) override
UseStartsEndsWithCheck(StringRef Name, ClangTidyContext *Context)
AST_MATCHER_P(Stmt, isStatementIdenticalToBoundNode, std::string, ID)
static bool isNegativeComparison(const Expr *ComparisonExpr)
bool areStatementsIdentical(const Stmt *FirstStmt, const Stmt *SecondStmt, const ASTContext &Context, bool Canonical)
Definition ASTUtils.cpp:89