Alexander Kornienko | 57a5c6b | 2015-03-16 00:32:25 +0000 | [diff] [blame] | 1 | //===- RedundantStringCStrCheck.cpp - Check for redundant c_str calls -----===// |
| 2 | // |
Chandler Carruth | 2946cd7 | 2019-01-19 08:50:56 +0000 | [diff] [blame] | 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 |
Alexander Kornienko | 57a5c6b | 2015-03-16 00:32:25 +0000 | [diff] [blame] | 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" |
Haojian Wu | 75f6cad | 2018-12-07 11:25:37 +0000 | [diff] [blame] | 15 | #include "clang/Tooling/FixIt.h" |
Alexander Kornienko | 57a5c6b | 2015-03-16 00:32:25 +0000 | [diff] [blame] | 16 | |
Etienne Bergeron | 456177b | 2016-05-02 18:00:29 +0000 | [diff] [blame] | 17 | using namespace clang::ast_matchers; |
Alexander Kornienko | 57a5c6b | 2015-03-16 00:32:25 +0000 | [diff] [blame] | 18 | |
Etienne Bergeron | 456177b | 2016-05-02 18:00:29 +0000 | [diff] [blame] | 19 | namespace clang { |
| 20 | namespace tidy { |
| 21 | namespace readability { |
Alexander Kornienko | 57a5c6b | 2015-03-16 00:32:25 +0000 | [diff] [blame] | 22 | |
| 23 | namespace { |
| 24 | |
Alexander Kornienko | 57a5c6b | 2015-03-16 00:32:25 +0000 | [diff] [blame] | 25 | // Return true if expr needs to be put in parens when it is an argument of a |
| 26 | // prefix unary operator, e.g. when it is a binary or ternary operator |
| 27 | // syntactically. |
| 28 | bool needParensAfterUnaryOperator(const Expr &ExprNode) { |
| 29 | if (isa<clang::BinaryOperator>(&ExprNode) || |
| 30 | isa<clang::ConditionalOperator>(&ExprNode)) { |
| 31 | return true; |
| 32 | } |
| 33 | if (const auto *Op = dyn_cast<CXXOperatorCallExpr>(&ExprNode)) { |
| 34 | return Op->getNumArgs() == 2 && Op->getOperator() != OO_PlusPlus && |
| 35 | Op->getOperator() != OO_MinusMinus && Op->getOperator() != OO_Call && |
| 36 | Op->getOperator() != OO_Subscript; |
| 37 | } |
| 38 | return false; |
| 39 | } |
| 40 | |
| 41 | // Format a pointer to an expression: prefix with '*' but simplify |
| 42 | // when it already begins with '&'. Return empty string on failure. |
| 43 | std::string |
| 44 | formatDereference(const ast_matchers::MatchFinder::MatchResult &Result, |
| 45 | const Expr &ExprNode) { |
| 46 | if (const auto *Op = dyn_cast<clang::UnaryOperator>(&ExprNode)) { |
| 47 | if (Op->getOpcode() == UO_AddrOf) { |
| 48 | // Strip leading '&'. |
Benjamin Kramer | adcd026 | 2020-01-28 20:23:46 +0100 | [diff] [blame] | 49 | return std::string(tooling::fixit::getText( |
| 50 | *Op->getSubExpr()->IgnoreParens(), *Result.Context)); |
Alexander Kornienko | 57a5c6b | 2015-03-16 00:32:25 +0000 | [diff] [blame] | 51 | } |
| 52 | } |
Haojian Wu | 75f6cad | 2018-12-07 11:25:37 +0000 | [diff] [blame] | 53 | StringRef Text = tooling::fixit::getText(ExprNode, *Result.Context); |
| 54 | |
Alexander Kornienko | 57a5c6b | 2015-03-16 00:32:25 +0000 | [diff] [blame] | 55 | if (Text.empty()) |
| 56 | return std::string(); |
| 57 | // Add leading '*'. |
| 58 | if (needParensAfterUnaryOperator(ExprNode)) { |
| 59 | return (llvm::Twine("*(") + Text + ")").str(); |
| 60 | } |
| 61 | return (llvm::Twine("*") + Text).str(); |
| 62 | } |
| 63 | |
Karasev Nikita | 47282b1 | 2020-02-18 15:32:03 -0500 | [diff] [blame] | 64 | // Trying to get CallExpr in which CxxConstructExpr is called. |
| 65 | static const clang::CallExpr * |
| 66 | tryGetCallExprAncestorForCxxConstructExpr(const Expr *TheExpr, |
| 67 | ASTContext &Context) { |
| 68 | // We skip nodes such as CXXBindTemporaryExpr, MaterializeTemporaryExpr. |
| 69 | for (ast_type_traits::DynTypedNode DynParent : Context.getParents(*TheExpr)) { |
| 70 | if (const auto *Parent = DynParent.get<Expr>()) { |
| 71 | if (const auto *TheCallExpr = dyn_cast<CallExpr>(Parent)) |
| 72 | return TheCallExpr; |
| 73 | |
| 74 | if (const clang::CallExpr *TheCallExpr = |
| 75 | tryGetCallExprAncestorForCxxConstructExpr(Parent, Context)) |
| 76 | return TheCallExpr; |
| 77 | } |
| 78 | } |
| 79 | |
| 80 | return nullptr; |
| 81 | } |
| 82 | |
| 83 | // Check that ParamDecl of CallExprDecl has rvalue type. |
| 84 | static bool checkParamDeclOfAncestorCallExprHasRValueRefType( |
| 85 | const Expr *TheCxxConstructExpr, ASTContext &Context) { |
| 86 | if (const clang::CallExpr *TheCallExpr = |
| 87 | tryGetCallExprAncestorForCxxConstructExpr(TheCxxConstructExpr, |
| 88 | Context)) { |
Eric Christopher | 28728bf | 2020-02-18 17:49:22 -0800 | [diff] [blame] | 89 | for (unsigned i = 0; i < TheCallExpr->getNumArgs(); ++i) { |
Karasev Nikita | 47282b1 | 2020-02-18 15:32:03 -0500 | [diff] [blame] | 90 | const Expr *Arg = TheCallExpr->getArg(i); |
| 91 | if (Arg->getSourceRange() == TheCxxConstructExpr->getSourceRange()) { |
| 92 | if (const auto *TheCallExprFuncProto = |
| 93 | TheCallExpr->getCallee() |
| 94 | ->getType() |
| 95 | ->getPointeeType() |
| 96 | ->getAs<FunctionProtoType>()) { |
| 97 | if (TheCallExprFuncProto->getParamType(i)->isRValueReferenceType()) |
| 98 | return true; |
| 99 | } |
| 100 | } |
| 101 | } |
| 102 | } |
| 103 | |
| 104 | return false; |
| 105 | } |
| 106 | |
| 107 | AST_MATCHER(CXXConstructExpr, |
| 108 | matchedParamDeclOfAncestorCallExprHasRValueRefType) { |
| 109 | return checkParamDeclOfAncestorCallExprHasRValueRefType( |
| 110 | &Node, Finder->getASTContext()); |
| 111 | } |
| 112 | |
Alexander Kornienko | 57a5c6b | 2015-03-16 00:32:25 +0000 | [diff] [blame] | 113 | } // end namespace |
| 114 | |
Alexander Kornienko | 57a5c6b | 2015-03-16 00:32:25 +0000 | [diff] [blame] | 115 | void RedundantStringCStrCheck::registerMatchers( |
| 116 | ast_matchers::MatchFinder *Finder) { |
Etienne Bergeron | cb7ce98 | 2016-03-24 19:42:36 +0000 | [diff] [blame] | 117 | // Match expressions of type 'string' or 'string*'. |
Manuel Klimek | 7b9c117 | 2017-08-02 13:13:11 +0000 | [diff] [blame] | 118 | const auto StringDecl = type(hasUnqualifiedDesugaredType(recordType( |
| 119 | hasDeclaration(cxxRecordDecl(hasName("::std::basic_string")))))); |
Etienne Bergeron | cb7ce98 | 2016-03-24 19:42:36 +0000 | [diff] [blame] | 120 | const auto StringExpr = |
Mandeep Singh Grang | 7c7ea7d | 2016-11-08 07:50:19 +0000 | [diff] [blame] | 121 | expr(anyOf(hasType(StringDecl), hasType(qualType(pointsTo(StringDecl))))); |
Etienne Bergeron | cb7ce98 | 2016-03-24 19:42:36 +0000 | [diff] [blame] | 122 | |
Etienne Bergeron | 4c3b55c | 2016-03-22 18:00:13 +0000 | [diff] [blame] | 123 | // Match string constructor. |
| 124 | const auto StringConstructorExpr = expr(anyOf( |
Mandeep Singh Grang | 7c7ea7d | 2016-11-08 07:50:19 +0000 | [diff] [blame] | 125 | cxxConstructExpr(argumentCountIs(1), |
| 126 | hasDeclaration(cxxMethodDecl(hasName("basic_string")))), |
Etienne Bergeron | 4c3b55c | 2016-03-22 18:00:13 +0000 | [diff] [blame] | 127 | cxxConstructExpr( |
Alexander Kornienko | 57a5c6b | 2015-03-16 00:32:25 +0000 | [diff] [blame] | 128 | argumentCountIs(2), |
Etienne Bergeron | cb7ce98 | 2016-03-24 19:42:36 +0000 | [diff] [blame] | 129 | hasDeclaration(cxxMethodDecl(hasName("basic_string"))), |
Etienne Bergeron | 4c3b55c | 2016-03-22 18:00:13 +0000 | [diff] [blame] | 130 | // If present, the second argument is the alloc object which must not |
| 131 | // be present explicitly. |
| 132 | hasArgument(1, cxxDefaultArgExpr())))); |
| 133 | |
| 134 | // Match a call to the string 'c_str()' method. |
Etienne Bergeron | cb7ce98 | 2016-03-24 19:42:36 +0000 | [diff] [blame] | 135 | const auto StringCStrCallExpr = |
| 136 | cxxMemberCallExpr(on(StringExpr.bind("arg")), |
| 137 | callee(memberExpr().bind("member")), |
Malcolm Parsons | 8b70e26 | 2016-11-03 12:56:48 +0000 | [diff] [blame] | 138 | callee(cxxMethodDecl(hasAnyName("c_str", "data")))) |
Etienne Bergeron | cb7ce98 | 2016-03-24 19:42:36 +0000 | [diff] [blame] | 139 | .bind("call"); |
Etienne Bergeron | 4c3b55c | 2016-03-22 18:00:13 +0000 | [diff] [blame] | 140 | |
Etienne Bergeron | 9cfd8ce | 2016-04-15 18:12:06 +0000 | [diff] [blame] | 141 | // Detect redundant 'c_str()' calls through a string constructor. |
Karasev Nikita | 47282b1 | 2020-02-18 15:32:03 -0500 | [diff] [blame] | 142 | // If CxxConstructExpr is the part of some CallExpr we need to |
| 143 | // check that matched ParamDecl of the ancestor CallExpr is not rvalue. |
| 144 | Finder->addMatcher( |
| 145 | cxxConstructExpr( |
| 146 | StringConstructorExpr, hasArgument(0, StringCStrCallExpr), |
| 147 | unless(matchedParamDeclOfAncestorCallExprHasRValueRefType())), |
| 148 | this); |
Etienne Bergeron | 4c3b55c | 2016-03-22 18:00:13 +0000 | [diff] [blame] | 149 | |
Etienne Bergeron | 9cfd8ce | 2016-04-15 18:12:06 +0000 | [diff] [blame] | 150 | // Detect: 's == str.c_str()' -> 's == str' |
| 151 | Finder->addMatcher( |
| 152 | cxxOperatorCallExpr( |
Nathan James | 97572fa | 2020-03-10 00:42:21 +0000 | [diff] [blame^] | 153 | hasAnyOverloadedOperatorName("<", ">", ">=", "<=", "!=", "==", "+"), |
Etienne Bergeron | 9cfd8ce | 2016-04-15 18:12:06 +0000 | [diff] [blame] | 154 | anyOf(allOf(hasArgument(0, StringExpr), |
| 155 | hasArgument(1, StringCStrCallExpr)), |
| 156 | allOf(hasArgument(0, StringCStrCallExpr), |
| 157 | hasArgument(1, StringExpr)))), |
| 158 | this); |
| 159 | |
| 160 | // Detect: 'dst += str.c_str()' -> 'dst += str' |
| 161 | // Detect: 's = str.c_str()' -> 's = str' |
Nathan James | 97572fa | 2020-03-10 00:42:21 +0000 | [diff] [blame^] | 162 | Finder->addMatcher( |
| 163 | cxxOperatorCallExpr(hasAnyOverloadedOperatorName("=", "+="), |
| 164 | hasArgument(0, StringExpr), |
| 165 | hasArgument(1, StringCStrCallExpr)), |
| 166 | this); |
Etienne Bergeron | 9cfd8ce | 2016-04-15 18:12:06 +0000 | [diff] [blame] | 167 | |
| 168 | // Detect: 'dst.append(str.c_str())' -> 'dst.append(str)' |
| 169 | Finder->addMatcher( |
Mandeep Singh Grang | 7c7ea7d | 2016-11-08 07:50:19 +0000 | [diff] [blame] | 170 | cxxMemberCallExpr(on(StringExpr), callee(decl(cxxMethodDecl(hasAnyName( |
| 171 | "append", "assign", "compare")))), |
| 172 | argumentCountIs(1), hasArgument(0, StringCStrCallExpr)), |
Etienne Bergeron | 9cfd8ce | 2016-04-15 18:12:06 +0000 | [diff] [blame] | 173 | this); |
| 174 | |
| 175 | // Detect: 'dst.compare(p, n, str.c_str())' -> 'dst.compare(p, n, str)' |
| 176 | Finder->addMatcher( |
| 177 | cxxMemberCallExpr(on(StringExpr), |
Mandeep Singh Grang | 7c7ea7d | 2016-11-08 07:50:19 +0000 | [diff] [blame] | 178 | callee(decl(cxxMethodDecl(hasName("compare")))), |
| 179 | argumentCountIs(3), hasArgument(2, StringCStrCallExpr)), |
Etienne Bergeron | 9cfd8ce | 2016-04-15 18:12:06 +0000 | [diff] [blame] | 180 | this); |
| 181 | |
| 182 | // Detect: 'dst.find(str.c_str())' -> 'dst.find(str)' |
| 183 | Finder->addMatcher( |
| 184 | cxxMemberCallExpr(on(StringExpr), |
Mandeep Singh Grang | 7c7ea7d | 2016-11-08 07:50:19 +0000 | [diff] [blame] | 185 | callee(decl(cxxMethodDecl(hasAnyName( |
| 186 | "find", "find_first_not_of", "find_first_of", |
| 187 | "find_last_not_of", "find_last_of", "rfind")))), |
| 188 | anyOf(argumentCountIs(1), argumentCountIs(2)), |
| 189 | hasArgument(0, StringCStrCallExpr)), |
Etienne Bergeron | 9cfd8ce | 2016-04-15 18:12:06 +0000 | [diff] [blame] | 190 | this); |
| 191 | |
| 192 | // Detect: 'dst.insert(pos, str.c_str())' -> 'dst.insert(pos, str)' |
| 193 | Finder->addMatcher( |
| 194 | cxxMemberCallExpr(on(StringExpr), |
Mandeep Singh Grang | 7c7ea7d | 2016-11-08 07:50:19 +0000 | [diff] [blame] | 195 | callee(decl(cxxMethodDecl(hasName("insert")))), |
| 196 | argumentCountIs(2), hasArgument(1, StringCStrCallExpr)), |
Etienne Bergeron | 9cfd8ce | 2016-04-15 18:12:06 +0000 | [diff] [blame] | 197 | this); |
| 198 | |
| 199 | // Detect redundant 'c_str()' calls through a StringRef constructor. |
Alexander Kornienko | 57a5c6b | 2015-03-16 00:32:25 +0000 | [diff] [blame] | 200 | Finder->addMatcher( |
Aaron Ballman | b9ea09c | 2015-09-17 13:31:25 +0000 | [diff] [blame] | 201 | cxxConstructExpr( |
Alexander Kornienko | 57a5c6b | 2015-03-16 00:32:25 +0000 | [diff] [blame] | 202 | // Implicit constructors of these classes are overloaded |
| 203 | // wrt. string types and they internally make a StringRef |
| 204 | // referring to the argument. Passing a string directly to |
| 205 | // them is preferred to passing a char pointer. |
Mandeep Singh Grang | 7c7ea7d | 2016-11-08 07:50:19 +0000 | [diff] [blame] | 206 | hasDeclaration(cxxMethodDecl(hasAnyName( |
| 207 | "::llvm::StringRef::StringRef", "::llvm::Twine::Twine"))), |
Alexander Kornienko | 57a5c6b | 2015-03-16 00:32:25 +0000 | [diff] [blame] | 208 | argumentCountIs(1), |
| 209 | // The only argument must have the form x.c_str() or p->c_str() |
| 210 | // where the method is string::c_str(). StringRef also has |
| 211 | // a constructor from string which is more efficient (avoids |
| 212 | // strlen), so we can construct StringRef from the string |
| 213 | // directly. |
Etienne Bergeron | 4c3b55c | 2016-03-22 18:00:13 +0000 | [diff] [blame] | 214 | hasArgument(0, StringCStrCallExpr)), |
Alexander Kornienko | 57a5c6b | 2015-03-16 00:32:25 +0000 | [diff] [blame] | 215 | this); |
| 216 | } |
| 217 | |
| 218 | void RedundantStringCStrCheck::check(const MatchFinder::MatchResult &Result) { |
Alexander Kornienko | 9f58fe0 | 2016-12-13 16:19:19 +0000 | [diff] [blame] | 219 | const auto *Call = Result.Nodes.getNodeAs<CallExpr>("call"); |
| 220 | const auto *Arg = Result.Nodes.getNodeAs<Expr>("arg"); |
| 221 | const auto *Member = Result.Nodes.getNodeAs<MemberExpr>("member"); |
Malcolm Parsons | 8b70e26 | 2016-11-03 12:56:48 +0000 | [diff] [blame] | 222 | bool Arrow = Member->isArrow(); |
Alexander Kornienko | 57a5c6b | 2015-03-16 00:32:25 +0000 | [diff] [blame] | 223 | // Replace the "call" node with the "arg" node, prefixed with '*' |
| 224 | // if the call was using '->' rather than '.'. |
| 225 | std::string ArgText = |
Haojian Wu | 75f6cad | 2018-12-07 11:25:37 +0000 | [diff] [blame] | 226 | Arrow ? formatDereference(Result, *Arg) |
| 227 | : tooling::fixit::getText(*Arg, *Result.Context).str(); |
Alexander Kornienko | 57a5c6b | 2015-03-16 00:32:25 +0000 | [diff] [blame] | 228 | if (ArgText.empty()) |
| 229 | return; |
| 230 | |
Stephen Kelly | 43465bf | 2018-08-09 22:42:26 +0000 | [diff] [blame] | 231 | diag(Call->getBeginLoc(), "redundant call to %0") |
Malcolm Parsons | 8b70e26 | 2016-11-03 12:56:48 +0000 | [diff] [blame] | 232 | << Member->getMemberDecl() |
Alexander Kornienko | 57a5c6b | 2015-03-16 00:32:25 +0000 | [diff] [blame] | 233 | << FixItHint::CreateReplacement(Call->getSourceRange(), ArgText); |
| 234 | } |
| 235 | |
| 236 | } // namespace readability |
| 237 | } // namespace tidy |
| 238 | } // namespace clang |