blob: 1f371eed2db8028199ad004e6b8be555442cd62d [file] [log] [blame]
Alexander Kornienko57a5c6b2015-03-16 00:32:25 +00001//===- RedundantStringCStrCheck.cpp - Check for redundant c_str calls -----===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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 Kornienko57a5c6b2015-03-16 00:32:25 +00006//
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 Wu75f6cad2018-12-07 11:25:37 +000015#include "clang/Tooling/FixIt.h"
Alexander Kornienko57a5c6b2015-03-16 00:32:25 +000016
Etienne Bergeron456177b2016-05-02 18:00:29 +000017using namespace clang::ast_matchers;
Alexander Kornienko57a5c6b2015-03-16 00:32:25 +000018
Etienne Bergeron456177b2016-05-02 18:00:29 +000019namespace clang {
20namespace tidy {
21namespace readability {
Alexander Kornienko57a5c6b2015-03-16 00:32:25 +000022
23namespace {
24
Alexander Kornienko57a5c6b2015-03-16 00:32:25 +000025// 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.
28bool 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.
43std::string
44formatDereference(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 Krameradcd0262020-01-28 20:23:46 +010049 return std::string(tooling::fixit::getText(
50 *Op->getSubExpr()->IgnoreParens(), *Result.Context));
Alexander Kornienko57a5c6b2015-03-16 00:32:25 +000051 }
52 }
Haojian Wu75f6cad2018-12-07 11:25:37 +000053 StringRef Text = tooling::fixit::getText(ExprNode, *Result.Context);
54
Alexander Kornienko57a5c6b2015-03-16 00:32:25 +000055 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
Nathan James38070792020-03-25 19:22:09 +000064AST_MATCHER(MaterializeTemporaryExpr, isBoundToLValue) {
65 return Node.isBoundToLvalueReference();
Karasev Nikita47282b12020-02-18 15:32:03 -050066}
67
Alexander Kornienko57a5c6b2015-03-16 00:32:25 +000068} // end namespace
69
Alexander Kornienko57a5c6b2015-03-16 00:32:25 +000070void RedundantStringCStrCheck::registerMatchers(
71 ast_matchers::MatchFinder *Finder) {
Etienne Bergeroncb7ce982016-03-24 19:42:36 +000072 // Match expressions of type 'string' or 'string*'.
Manuel Klimek7b9c1172017-08-02 13:13:11 +000073 const auto StringDecl = type(hasUnqualifiedDesugaredType(recordType(
74 hasDeclaration(cxxRecordDecl(hasName("::std::basic_string"))))));
Etienne Bergeroncb7ce982016-03-24 19:42:36 +000075 const auto StringExpr =
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +000076 expr(anyOf(hasType(StringDecl), hasType(qualType(pointsTo(StringDecl)))));
Etienne Bergeroncb7ce982016-03-24 19:42:36 +000077
Etienne Bergeron4c3b55c2016-03-22 18:00:13 +000078 // Match string constructor.
79 const auto StringConstructorExpr = expr(anyOf(
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +000080 cxxConstructExpr(argumentCountIs(1),
81 hasDeclaration(cxxMethodDecl(hasName("basic_string")))),
Etienne Bergeron4c3b55c2016-03-22 18:00:13 +000082 cxxConstructExpr(
Alexander Kornienko57a5c6b2015-03-16 00:32:25 +000083 argumentCountIs(2),
Etienne Bergeroncb7ce982016-03-24 19:42:36 +000084 hasDeclaration(cxxMethodDecl(hasName("basic_string"))),
Etienne Bergeron4c3b55c2016-03-22 18:00:13 +000085 // 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.
Etienne Bergeroncb7ce982016-03-24 19:42:36 +000090 const auto StringCStrCallExpr =
91 cxxMemberCallExpr(on(StringExpr.bind("arg")),
92 callee(memberExpr().bind("member")),
Malcolm Parsons8b70e262016-11-03 12:56:48 +000093 callee(cxxMethodDecl(hasAnyName("c_str", "data"))))
Etienne Bergeroncb7ce982016-03-24 19:42:36 +000094 .bind("call");
Nathan Jamesb99630e2020-07-29 15:35:28 +010095 const auto HasRValueTempParent =
96 hasParent(materializeTemporaryExpr(unless(isBoundToLValue())));
Etienne Bergeron9cfd8ce2016-04-15 18:12:06 +000097 // Detect redundant 'c_str()' calls through a string constructor.
Karasev Nikita47282b12020-02-18 15:32:03 -050098 // If CxxConstructExpr is the part of some CallExpr we need to
99 // check that matched ParamDecl of the ancestor CallExpr is not rvalue.
Stephen Kellya72307c2019-11-12 15:15:56 +0000100 Finder->addMatcher(
Nathan Jamesb99630e2020-07-29 15:35:28 +0100101 traverse(
102 ast_type_traits::TK_AsIs,
103 cxxConstructExpr(
104 StringConstructorExpr, hasArgument(0, StringCStrCallExpr),
105 unless(anyOf(HasRValueTempParent, hasParent(cxxBindTemporaryExpr(
106 HasRValueTempParent)))))),
Stephen Kellya72307c2019-11-12 15:15:56 +0000107 this);
Etienne Bergeron4c3b55c2016-03-22 18:00:13 +0000108
Etienne Bergeron9cfd8ce2016-04-15 18:12:06 +0000109 // Detect: 's == str.c_str()' -> 's == str'
110 Finder->addMatcher(
111 cxxOperatorCallExpr(
Nathan James97572fa2020-03-10 00:42:21 +0000112 hasAnyOverloadedOperatorName("<", ">", ">=", "<=", "!=", "==", "+"),
Etienne Bergeron9cfd8ce2016-04-15 18:12:06 +0000113 anyOf(allOf(hasArgument(0, StringExpr),
114 hasArgument(1, StringCStrCallExpr)),
115 allOf(hasArgument(0, StringCStrCallExpr),
116 hasArgument(1, StringExpr)))),
117 this);
118
119 // Detect: 'dst += str.c_str()' -> 'dst += str'
120 // Detect: 's = str.c_str()' -> 's = str'
Nathan James97572fa2020-03-10 00:42:21 +0000121 Finder->addMatcher(
122 cxxOperatorCallExpr(hasAnyOverloadedOperatorName("=", "+="),
123 hasArgument(0, StringExpr),
124 hasArgument(1, StringCStrCallExpr)),
125 this);
Etienne Bergeron9cfd8ce2016-04-15 18:12:06 +0000126
127 // Detect: 'dst.append(str.c_str())' -> 'dst.append(str)'
128 Finder->addMatcher(
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +0000129 cxxMemberCallExpr(on(StringExpr), callee(decl(cxxMethodDecl(hasAnyName(
130 "append", "assign", "compare")))),
131 argumentCountIs(1), hasArgument(0, StringCStrCallExpr)),
Etienne Bergeron9cfd8ce2016-04-15 18:12:06 +0000132 this);
133
134 // Detect: 'dst.compare(p, n, str.c_str())' -> 'dst.compare(p, n, str)'
135 Finder->addMatcher(
136 cxxMemberCallExpr(on(StringExpr),
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +0000137 callee(decl(cxxMethodDecl(hasName("compare")))),
138 argumentCountIs(3), hasArgument(2, StringCStrCallExpr)),
Etienne Bergeron9cfd8ce2016-04-15 18:12:06 +0000139 this);
140
141 // Detect: 'dst.find(str.c_str())' -> 'dst.find(str)'
142 Finder->addMatcher(
143 cxxMemberCallExpr(on(StringExpr),
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +0000144 callee(decl(cxxMethodDecl(hasAnyName(
145 "find", "find_first_not_of", "find_first_of",
146 "find_last_not_of", "find_last_of", "rfind")))),
147 anyOf(argumentCountIs(1), argumentCountIs(2)),
148 hasArgument(0, StringCStrCallExpr)),
Etienne Bergeron9cfd8ce2016-04-15 18:12:06 +0000149 this);
150
151 // Detect: 'dst.insert(pos, str.c_str())' -> 'dst.insert(pos, str)'
152 Finder->addMatcher(
153 cxxMemberCallExpr(on(StringExpr),
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +0000154 callee(decl(cxxMethodDecl(hasName("insert")))),
155 argumentCountIs(2), hasArgument(1, StringCStrCallExpr)),
Etienne Bergeron9cfd8ce2016-04-15 18:12:06 +0000156 this);
157
158 // Detect redundant 'c_str()' calls through a StringRef constructor.
Alexander Kornienko57a5c6b2015-03-16 00:32:25 +0000159 Finder->addMatcher(
Stephen Kellya72307c2019-11-12 15:15:56 +0000160 traverse(
161 ast_type_traits::TK_AsIs,
162 cxxConstructExpr(
163 // Implicit constructors of these classes are overloaded
164 // wrt. string types and they internally make a StringRef
165 // referring to the argument. Passing a string directly to
166 // them is preferred to passing a char pointer.
167 hasDeclaration(cxxMethodDecl(hasAnyName(
168 "::llvm::StringRef::StringRef", "::llvm::Twine::Twine"))),
169 argumentCountIs(1),
170 // The only argument must have the form x.c_str() or p->c_str()
171 // where the method is string::c_str(). StringRef also has
172 // a constructor from string which is more efficient (avoids
173 // strlen), so we can construct StringRef from the string
174 // directly.
175 hasArgument(0, StringCStrCallExpr))),
Alexander Kornienko57a5c6b2015-03-16 00:32:25 +0000176 this);
177}
178
179void RedundantStringCStrCheck::check(const MatchFinder::MatchResult &Result) {
Alexander Kornienko9f58fe02016-12-13 16:19:19 +0000180 const auto *Call = Result.Nodes.getNodeAs<CallExpr>("call");
181 const auto *Arg = Result.Nodes.getNodeAs<Expr>("arg");
182 const auto *Member = Result.Nodes.getNodeAs<MemberExpr>("member");
Malcolm Parsons8b70e262016-11-03 12:56:48 +0000183 bool Arrow = Member->isArrow();
Alexander Kornienko57a5c6b2015-03-16 00:32:25 +0000184 // Replace the "call" node with the "arg" node, prefixed with '*'
185 // if the call was using '->' rather than '.'.
186 std::string ArgText =
Haojian Wu75f6cad2018-12-07 11:25:37 +0000187 Arrow ? formatDereference(Result, *Arg)
188 : tooling::fixit::getText(*Arg, *Result.Context).str();
Alexander Kornienko57a5c6b2015-03-16 00:32:25 +0000189 if (ArgText.empty())
190 return;
191
Stephen Kelly43465bf2018-08-09 22:42:26 +0000192 diag(Call->getBeginLoc(), "redundant call to %0")
Malcolm Parsons8b70e262016-11-03 12:56:48 +0000193 << Member->getMemberDecl()
Alexander Kornienko57a5c6b2015-03-16 00:32:25 +0000194 << FixItHint::CreateReplacement(Call->getSourceRange(), ArgText);
195}
196
197} // namespace readability
198} // namespace tidy
199} // namespace clang