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 { 20 namespace tidy { 21 namespace readability { 22 23 namespace { 24 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 '&'. 49 return std::string(tooling::fixit::getText( 50 *Op->getSubExpr()->IgnoreParens(), *Result.Context)); 51 } 52 } 53 StringRef Text = tooling::fixit::getText(ExprNode, *Result.Context); 54 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 64 AST_MATCHER(MaterializeTemporaryExpr, isBoundToLValue) { 65 return Node.isBoundToLvalueReference(); 66 } 67 68 } // end namespace 69 70 void RedundantStringCStrCheck::registerMatchers( 71 ast_matchers::MatchFinder *Finder) { 72 // Match expressions of type 'string' or 'string*'. 73 const auto StringDecl = type(hasUnqualifiedDesugaredType(recordType( 74 hasDeclaration(cxxRecordDecl(hasName("::std::basic_string")))))); 75 const auto StringExpr = 76 expr(anyOf(hasType(StringDecl), hasType(qualType(pointsTo(StringDecl))))); 77 78 // Match string constructor. 79 const auto StringConstructorExpr = expr(anyOf( 80 cxxConstructExpr(argumentCountIs(1), 81 hasDeclaration(cxxMethodDecl(hasName("basic_string")))), 82 cxxConstructExpr( 83 argumentCountIs(2), 84 hasDeclaration(cxxMethodDecl(hasName("basic_string"))), 85 // If present, the second argument is the alloc object which must not 86 // be present explicitly. 87 hasArgument(1, cxxDefaultArgExpr())))); 88 89 // Match a call to the string 'c_str()' method. 90 const auto StringCStrCallExpr = 91 cxxMemberCallExpr(on(StringExpr.bind("arg")), 92 callee(memberExpr().bind("member")), 93 callee(cxxMethodDecl(hasAnyName("c_str", "data")))) 94 .bind("call"); 95 96 // Detect redundant 'c_str()' calls through a string constructor. 97 // If CxxConstructExpr is the part of some CallExpr we need to 98 // check that matched ParamDecl of the ancestor CallExpr is not rvalue. 99 Finder->addMatcher( 100 traverse(ast_type_traits::TK_AsIs, 101 cxxConstructExpr(StringConstructorExpr, 102 hasArgument(0, StringCStrCallExpr), 103 unless(hasParent(materializeTemporaryExpr( 104 unless(isBoundToLValue())))))), 105 this); 106 107 // Detect: 's == str.c_str()' -> 's == str' 108 Finder->addMatcher( 109 cxxOperatorCallExpr( 110 hasAnyOverloadedOperatorName("<", ">", ">=", "<=", "!=", "==", "+"), 111 anyOf(allOf(hasArgument(0, StringExpr), 112 hasArgument(1, StringCStrCallExpr)), 113 allOf(hasArgument(0, StringCStrCallExpr), 114 hasArgument(1, StringExpr)))), 115 this); 116 117 // Detect: 'dst += str.c_str()' -> 'dst += str' 118 // Detect: 's = str.c_str()' -> 's = str' 119 Finder->addMatcher( 120 cxxOperatorCallExpr(hasAnyOverloadedOperatorName("=", "+="), 121 hasArgument(0, StringExpr), 122 hasArgument(1, StringCStrCallExpr)), 123 this); 124 125 // Detect: 'dst.append(str.c_str())' -> 'dst.append(str)' 126 Finder->addMatcher( 127 cxxMemberCallExpr(on(StringExpr), callee(decl(cxxMethodDecl(hasAnyName( 128 "append", "assign", "compare")))), 129 argumentCountIs(1), hasArgument(0, StringCStrCallExpr)), 130 this); 131 132 // Detect: 'dst.compare(p, n, str.c_str())' -> 'dst.compare(p, n, str)' 133 Finder->addMatcher( 134 cxxMemberCallExpr(on(StringExpr), 135 callee(decl(cxxMethodDecl(hasName("compare")))), 136 argumentCountIs(3), hasArgument(2, StringCStrCallExpr)), 137 this); 138 139 // Detect: 'dst.find(str.c_str())' -> 'dst.find(str)' 140 Finder->addMatcher( 141 cxxMemberCallExpr(on(StringExpr), 142 callee(decl(cxxMethodDecl(hasAnyName( 143 "find", "find_first_not_of", "find_first_of", 144 "find_last_not_of", "find_last_of", "rfind")))), 145 anyOf(argumentCountIs(1), argumentCountIs(2)), 146 hasArgument(0, StringCStrCallExpr)), 147 this); 148 149 // Detect: 'dst.insert(pos, str.c_str())' -> 'dst.insert(pos, str)' 150 Finder->addMatcher( 151 cxxMemberCallExpr(on(StringExpr), 152 callee(decl(cxxMethodDecl(hasName("insert")))), 153 argumentCountIs(2), hasArgument(1, StringCStrCallExpr)), 154 this); 155 156 // Detect redundant 'c_str()' calls through a StringRef constructor. 157 Finder->addMatcher( 158 traverse( 159 ast_type_traits::TK_AsIs, 160 cxxConstructExpr( 161 // Implicit constructors of these classes are overloaded 162 // wrt. string types and they internally make a StringRef 163 // referring to the argument. Passing a string directly to 164 // them is preferred to passing a char pointer. 165 hasDeclaration(cxxMethodDecl(hasAnyName( 166 "::llvm::StringRef::StringRef", "::llvm::Twine::Twine"))), 167 argumentCountIs(1), 168 // The only argument must have the form x.c_str() or p->c_str() 169 // where the method is string::c_str(). StringRef also has 170 // a constructor from string which is more efficient (avoids 171 // strlen), so we can construct StringRef from the string 172 // directly. 173 hasArgument(0, StringCStrCallExpr))), 174 this); 175 } 176 177 void RedundantStringCStrCheck::check(const MatchFinder::MatchResult &Result) { 178 const auto *Call = Result.Nodes.getNodeAs<CallExpr>("call"); 179 const auto *Arg = Result.Nodes.getNodeAs<Expr>("arg"); 180 const auto *Member = Result.Nodes.getNodeAs<MemberExpr>("member"); 181 bool Arrow = Member->isArrow(); 182 // Replace the "call" node with the "arg" node, prefixed with '*' 183 // if the call was using '->' rather than '.'. 184 std::string ArgText = 185 Arrow ? formatDereference(Result, *Arg) 186 : tooling::fixit::getText(*Arg, *Result.Context).str(); 187 if (ArgText.empty()) 188 return; 189 190 diag(Call->getBeginLoc(), "redundant call to %0") 191 << Member->getMemberDecl() 192 << FixItHint::CreateReplacement(Call->getSourceRange(), ArgText); 193 } 194 195 } // namespace readability 196 } // namespace tidy 197 } // namespace clang 198