Debian Codegraph @

llvm-project/clang-tools-extra/clang-tidy/readability/RedundantStringCStrCheck.cpp

raw
1 //===- RedundantStringCStrCheck.cpp - Check for redundant c_str calls -----===//
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 //
9 // This file implements a check for redundant calls of c_str() on strings.
10 //
11 //===----------------------------------------------------------------------===//
12
13 #include "RedundantStringCStrCheck.h"
14 #include "clang/Lex/Lexer.h"
15 #include "clang/Tooling/FixIt.h"
16
17 using namespace clang::ast_matchers;
18
19 namespace clang::tidy::readability {
20
21 namespace {
22
23 // Return true if expr needs to be put in parens when it is an argument of a
24 // prefix unary operator, e.g. when it is a binary or ternary operator
25 // syntactically.
26 bool needParensAfterUnaryOperator(const Expr &ExprNode) {
27 if (isa<clang::BinaryOperator>(&ExprNode) ||
28 isa<clang::ConditionalOperator>(&ExprNode)) {
29 return true;
30 }
31 if (const auto *Op = dyn_cast<CXXOperatorCallExpr>(&ExprNode)) {
32 return Op->getNumArgs() == 2 && Op->getOperator() != OO_PlusPlus &&
33 Op->getOperator() != OO_MinusMinus && Op->getOperator() != OO_Call &&
34 Op->getOperator() != OO_Subscript;
35 }
36 return false;
37 }
38
39 // Format a pointer to an expression: prefix with '*' but simplify
40 // when it already begins with '&'. Return empty string on failure.
41 std::string
42 formatDereference(const ast_matchers::MatchFinder::MatchResult &Result,
43 const Expr &ExprNode) {
44 if (const auto *Op = dyn_cast<clang::UnaryOperator>(&ExprNode)) {
45 if (Op->getOpcode() == UO_AddrOf) {
46 // Strip leading '&'.
47 return std::string(tooling::fixit::getText(
48 *Op->getSubExpr()->IgnoreParens(), *Result.Context));
49 }
50 }
51 StringRef Text = tooling::fixit::getText(ExprNode, *Result.Context);
52
53 if (Text.empty())
54 return std::string();
55 // Add leading '*'.
56 if (needParensAfterUnaryOperator(ExprNode)) {
57 return (llvm::Twine("*(") + Text + ")").str();
58 }
59 return (llvm::Twine("*") + Text).str();
60 }
61
62 AST_MATCHER(MaterializeTemporaryExpr, isBoundToLValue) {
63 return Node.isBoundToLvalueReference();
64 }
65
66 } // end namespace
67
68 void RedundantStringCStrCheck::registerMatchers(
69 ast_matchers::MatchFinder *Finder) {
70 // Match expressions of type 'string' or 'string*'.
71 const auto StringDecl = type(hasUnqualifiedDesugaredType(recordType(
72 hasDeclaration(cxxRecordDecl(hasName("::std::basic_string"))))));
73 const auto StringExpr =
74 expr(anyOf(hasType(StringDecl), hasType(qualType(pointsTo(StringDecl)))));
75
76 // Match string constructor.
77 const auto StringConstructorExpr = expr(anyOf(
78 cxxConstructExpr(argumentCountIs(1),
79 hasDeclaration(cxxMethodDecl(hasName("basic_string")))),
80 cxxConstructExpr(
81 argumentCountIs(2),
82 hasDeclaration(cxxMethodDecl(hasName("basic_string"))),
83 // If present, the second argument is the alloc object which must not
84 // be present explicitly.
85 hasArgument(1, cxxDefaultArgExpr()))));
86
87 // Match string constructor.
88 const auto StringViewConstructorExpr = cxxConstructExpr(
89 argumentCountIs(1),
90 hasDeclaration(cxxMethodDecl(hasName("basic_string_view"))));
91
92 // Match a call to the string 'c_str()' method.
93 const auto StringCStrCallExpr =
94 cxxMemberCallExpr(on(StringExpr.bind("arg")),
95 callee(memberExpr().bind("member")),
96 callee(cxxMethodDecl(hasAnyName("c_str", "data"))))
97 .bind("call");
98 const auto HasRValueTempParent =
99 hasParent(materializeTemporaryExpr(unless(isBoundToLValue())));
100 // Detect redundant 'c_str()' calls through a string constructor.
101 // If CxxConstructExpr is the part of some CallExpr we need to
102 // check that matched ParamDecl of the ancestor CallExpr is not rvalue.
103 Finder->addMatcher(
104 traverse(
105 TK_AsIs,
106 cxxConstructExpr(
107 anyOf(StringConstructorExpr, StringViewConstructorExpr),
108 hasArgument(0, StringCStrCallExpr),
109 unless(anyOf(HasRValueTempParent, hasParent(cxxBindTemporaryExpr(
110 HasRValueTempParent)))))),
111 this);
112
113 // Detect: 's == str.c_str()' -> 's == str'
114 Finder->addMatcher(
115 cxxOperatorCallExpr(
116 hasAnyOverloadedOperatorName("<", ">", ">=", "<=", "!=", "==", "+"),
117 anyOf(allOf(hasArgument(0, StringExpr),
118 hasArgument(1, StringCStrCallExpr)),
119 allOf(hasArgument(0, StringCStrCallExpr),
120 hasArgument(1, StringExpr)))),
121 this);
122
123 // Detect: 'dst += str.c_str()' -> 'dst += str'
124 // Detect: 's = str.c_str()' -> 's = str'
125 Finder->addMatcher(
126 cxxOperatorCallExpr(hasAnyOverloadedOperatorName("=", "+="),
127 hasArgument(0, StringExpr),
128 hasArgument(1, StringCStrCallExpr)),
129 this);
130
131 // Detect: 'dst.append(str.c_str())' -> 'dst.append(str)'
132 Finder->addMatcher(
133 cxxMemberCallExpr(on(StringExpr), callee(decl(cxxMethodDecl(hasAnyName(
134 "append", "assign", "compare")))),
135 argumentCountIs(1), hasArgument(0, StringCStrCallExpr)),
136 this);
137
138 // Detect: 'dst.compare(p, n, str.c_str())' -> 'dst.compare(p, n, str)'
139 Finder->addMatcher(
140 cxxMemberCallExpr(on(StringExpr),
141 callee(decl(cxxMethodDecl(hasName("compare")))),
142 argumentCountIs(3), hasArgument(2, StringCStrCallExpr)),
143 this);
144
145 // Detect: 'dst.find(str.c_str())' -> 'dst.find(str)'
146 Finder->addMatcher(
147 cxxMemberCallExpr(on(StringExpr),
148 callee(decl(cxxMethodDecl(hasAnyName(
149 "find", "find_first_not_of", "find_first_of",
150 "find_last_not_of", "find_last_of", "rfind")))),
151 anyOf(argumentCountIs(1), argumentCountIs(2)),
152 hasArgument(0, StringCStrCallExpr)),
153 this);
154
155 // Detect: 'dst.insert(pos, str.c_str())' -> 'dst.insert(pos, str)'
156 Finder->addMatcher(
157 cxxMemberCallExpr(on(StringExpr),
158 callee(decl(cxxMethodDecl(hasName("insert")))),
159 argumentCountIs(2), hasArgument(1, StringCStrCallExpr)),
160 this);
161
162 // Detect redundant 'c_str()' calls through a StringRef constructor.
163 Finder->addMatcher(
164 traverse(
165 TK_AsIs,
166 cxxConstructExpr(
167 // Implicit constructors of these classes are overloaded
168 // wrt. string types and they internally make a StringRef
169 // referring to the argument. Passing a string directly to
170 // them is preferred to passing a char pointer.
171 hasDeclaration(cxxMethodDecl(hasAnyName(
172 "::llvm::StringRef::StringRef", "::llvm::Twine::Twine"))),
173 argumentCountIs(1),
174 // The only argument must have the form x.c_str() or p->c_str()
175 // where the method is string::c_str(). StringRef also has
176 // a constructor from string which is more efficient (avoids
177 // strlen), so we can construct StringRef from the string
178 // directly.
179 hasArgument(0, StringCStrCallExpr))),
180 this);
181 }
182
183 void RedundantStringCStrCheck::check(const MatchFinder::MatchResult &Result) {
184 const auto *Call = Result.Nodes.getNodeAs<CallExpr>("call");
185 const auto *Arg = Result.Nodes.getNodeAs<Expr>("arg");
186 const auto *Member = Result.Nodes.getNodeAs<MemberExpr>("member");
187 bool Arrow = Member->isArrow();
188 // Replace the "call" node with the "arg" node, prefixed with '*'
189 // if the call was using '->' rather than '.'.
190 std::string ArgText =
191 Arrow ? formatDereference(Result, *Arg)
192 : tooling::fixit::getText(*Arg, *Result.Context).str();
193 if (ArgText.empty())
194 return;
195
196 diag(Call->getBeginLoc(), "redundant call to %0")
197 << Member->getMemberDecl()
198 << FixItHint::CreateReplacement(Call->getSourceRange(), ArgText);
199 }
200
201 } // namespace clang::tidy::readability