| 1 |
//===--- UseEmplaceCheck.cpp - clang-tidy----------------------------------===// |
| 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 |
#include "UseEmplaceCheck.h" |
| 10 |
#include "../utils/OptionsUtils.h" |
| 11 |
using namespace clang::ast_matchers; |
| 12 |
|
| 13 |
namespace clang::tidy::modernize { |
| 14 |
|
| 15 |
namespace { |
| 16 |
// Identical to hasAnyName, except it does not take template specifiers into |
| 17 |
// account. This is used to match the functions names as in |
| 18 |
// DefaultEmplacyFunctions below without caring about the template types of the |
| 19 |
// containers. |
| 20 |
AST_MATCHER_P(NamedDecl, hasAnyNameIgnoringTemplates, std::vector<StringRef>, |
| 21 |
Names) { |
| 22 |
const std::string FullName = "::" + Node.getQualifiedNameAsString(); |
| 23 |
|
| 24 |
// This loop removes template specifiers by only keeping characters not within |
| 25 |
// template brackets. We keep a depth count to handle nested templates. For |
| 26 |
// example, it'll transform a::b<c<d>>::e<f> to simply a::b::e. |
| 27 |
std::string FullNameTrimmed; |
| 28 |
int Depth = 0; |
| 29 |
for (const auto &Character : FullName) { |
| 30 |
if (Character == '<') { |
| 31 |
++Depth; |
| 32 |
} else if (Character == '>') { |
| 33 |
--Depth; |
| 34 |
} else if (Depth == 0) { |
| 35 |
FullNameTrimmed.append(1, Character); |
| 36 |
} |
| 37 |
} |
| 38 |
|
| 39 |
// This loop is taken from HasNameMatcher::matchesNodeFullSlow in |
| 40 |
// clang/lib/ASTMatchers/ASTMatchersInternal.cpp and checks whether |
| 41 |
// FullNameTrimmed matches any of the given Names. |
| 42 |
const StringRef FullNameTrimmedRef = FullNameTrimmed; |
| 43 |
for (const StringRef Pattern : Names) { |
| 44 |
if (Pattern.startswith("::")) { |
| 45 |
if (FullNameTrimmed == Pattern) |
| 46 |
return true; |
| 47 |
} else if (FullNameTrimmedRef.endswith(Pattern) && |
| 48 |
FullNameTrimmedRef.drop_back(Pattern.size()).endswith("::")) { |
| 49 |
return true; |
| 50 |
} |
| 51 |
} |
| 52 |
|
| 53 |
return false; |
| 54 |
} |
| 55 |
|
| 56 |
// Checks if the given matcher is the last argument of the given CallExpr. |
| 57 |
AST_MATCHER_P(CallExpr, hasLastArgument, |
| 58 |
clang::ast_matchers::internal::Matcher<Expr>, InnerMatcher) { |
| 59 |
if (Node.getNumArgs() == 0) |
| 60 |
return false; |
| 61 |
|
| 62 |
return InnerMatcher.matches(*Node.getArg(Node.getNumArgs() - 1), Finder, |
| 63 |
Builder); |
| 64 |
} |
| 65 |
|
| 66 |
// Checks if the given member call has the same number of arguments as the |
| 67 |
// function had parameters defined (this is useful to check if there is only one |
| 68 |
// variadic argument). |
| 69 |
AST_MATCHER(CXXMemberCallExpr, hasSameNumArgsAsDeclNumParams) { |
| 70 |
if (Node.getMethodDecl()->isFunctionTemplateSpecialization()) |
| 71 |
return Node.getNumArgs() == Node.getMethodDecl() |
| 72 |
->getPrimaryTemplate() |
| 73 |
->getTemplatedDecl() |
| 74 |
->getNumParams(); |
| 75 |
|
| 76 |
return Node.getNumArgs() == Node.getMethodDecl()->getNumParams(); |
| 77 |
} |
| 78 |
|
| 79 |
AST_MATCHER(DeclRefExpr, hasExplicitTemplateArgs) { |
| 80 |
return Node.hasExplicitTemplateArgs(); |
| 81 |
} |
| 82 |
|
| 83 |
const auto DefaultContainersWithPushBack = |
| 84 |
"::std::vector; ::std::list; ::std::deque"; |
| 85 |
const auto DefaultContainersWithPush = |
| 86 |
"::std::stack; ::std::queue; ::std::priority_queue"; |
| 87 |
const auto DefaultContainersWithPushFront = |
| 88 |
"::std::forward_list; ::std::list; ::std::deque"; |
| 89 |
const auto DefaultSmartPointers = |
| 90 |
"::std::shared_ptr; ::std::unique_ptr; ::std::auto_ptr; ::std::weak_ptr"; |
| 91 |
const auto DefaultTupleTypes = "::std::pair; ::std::tuple"; |
| 92 |
const auto DefaultTupleMakeFunctions = "::std::make_pair; ::std::make_tuple"; |
| 93 |
const auto DefaultEmplacyFunctions = |
| 94 |
"vector::emplace_back; vector::emplace;" |
| 95 |
"deque::emplace; deque::emplace_front; deque::emplace_back;" |
| 96 |
"forward_list::emplace_after; forward_list::emplace_front;" |
| 97 |
"list::emplace; list::emplace_back; list::emplace_front;" |
| 98 |
"set::emplace; set::emplace_hint;" |
| 99 |
"map::emplace; map::emplace_hint;" |
| 100 |
"multiset::emplace; multiset::emplace_hint;" |
| 101 |
"multimap::emplace; multimap::emplace_hint;" |
| 102 |
"unordered_set::emplace; unordered_set::emplace_hint;" |
| 103 |
"unordered_map::emplace; unordered_map::emplace_hint;" |
| 104 |
"unordered_multiset::emplace; unordered_multiset::emplace_hint;" |
| 105 |
"unordered_multimap::emplace; unordered_multimap::emplace_hint;" |
| 106 |
"stack::emplace; queue::emplace; priority_queue::emplace"; |
| 107 |
} // namespace |
| 108 |
|
| 109 |
UseEmplaceCheck::UseEmplaceCheck(StringRef Name, ClangTidyContext *Context) |
| 110 |
: ClangTidyCheck(Name, Context), IgnoreImplicitConstructors(Options.get( |
| 111 |
"IgnoreImplicitConstructors", false)), |
| 112 |
ContainersWithPushBack(utils::options::parseStringList(Options.get( |
| 113 |
"ContainersWithPushBack", DefaultContainersWithPushBack))), |
| 114 |
ContainersWithPush(utils::options::parseStringList( |
| 115 |
Options.get("ContainersWithPush", DefaultContainersWithPush))), |
| 116 |
ContainersWithPushFront(utils::options::parseStringList(Options.get( |
| 117 |
"ContainersWithPushFront", DefaultContainersWithPushFront))), |
| 118 |
SmartPointers(utils::options::parseStringList( |
| 119 |
Options.get("SmartPointers", DefaultSmartPointers))), |
| 120 |
TupleTypes(utils::options::parseStringList( |
| 121 |
Options.get("TupleTypes", DefaultTupleTypes))), |
| 122 |
TupleMakeFunctions(utils::options::parseStringList( |
| 123 |
Options.get("TupleMakeFunctions", DefaultTupleMakeFunctions))), |
| 124 |
EmplacyFunctions(utils::options::parseStringList( |
| 125 |
Options.get("EmplacyFunctions", DefaultEmplacyFunctions))) {} |
| 126 |
|
| 127 |
void UseEmplaceCheck::registerMatchers(MatchFinder *Finder) { |
| 128 |
// FIXME: Bunch of functionality that could be easily added: |
| 129 |
// + add handling of `insert` for stl associative container, but be careful |
| 130 |
// because this requires special treatment (it could cause performance |
| 131 |
// regression) |
| 132 |
// + match for emplace calls that should be replaced with insertion |
| 133 |
auto CallPushBack = cxxMemberCallExpr( |
| 134 |
hasDeclaration(functionDecl(hasName("push_back"))), |
| 135 |
on(hasType(hasCanonicalType( |
| 136 |
hasDeclaration(cxxRecordDecl(hasAnyName(ContainersWithPushBack))))))); |
| 137 |
|
| 138 |
auto CallPush = |
| 139 |
cxxMemberCallExpr(hasDeclaration(functionDecl(hasName("push"))), |
| 140 |
on(hasType(hasCanonicalType(hasDeclaration( |
| 141 |
cxxRecordDecl(hasAnyName(ContainersWithPush))))))); |
| 142 |
|
| 143 |
auto CallPushFront = cxxMemberCallExpr( |
| 144 |
hasDeclaration(functionDecl(hasName("push_front"))), |
| 145 |
on(hasType(hasCanonicalType(hasDeclaration( |
| 146 |
cxxRecordDecl(hasAnyName(ContainersWithPushFront))))))); |
| 147 |
|
| 148 |
auto CallEmplacy = cxxMemberCallExpr( |
| 149 |
hasDeclaration( |
| 150 |
functionDecl(hasAnyNameIgnoringTemplates(EmplacyFunctions))), |
| 151 |
on(hasType(hasCanonicalType(hasDeclaration(has(typedefNameDecl( |
| 152 |
hasName("value_type"), hasType(type(hasUnqualifiedDesugaredType( |
| 153 |
recordType().bind("value_type"))))))))))); |
| 154 |
|
| 155 |
// We can't replace push_backs of smart pointer because |
| 156 |
// if emplacement fails (f.e. bad_alloc in vector) we will have leak of |
| 157 |
// passed pointer because smart pointer won't be constructed |
| 158 |
// (and destructed) as in push_back case. |
| 159 |
auto IsCtorOfSmartPtr = |
| 160 |
hasDeclaration(cxxConstructorDecl(ofClass(hasAnyName(SmartPointers)))); |
| 161 |
|
| 162 |
// Bitfields binds only to consts and emplace_back take it by universal ref. |
| 163 |
auto BitFieldAsArgument = hasAnyArgument( |
| 164 |
ignoringImplicit(memberExpr(hasDeclaration(fieldDecl(isBitField()))))); |
| 165 |
|
| 166 |
// Initializer list can't be passed to universal reference. |
| 167 |
auto InitializerListAsArgument = hasAnyArgument( |
| 168 |
ignoringImplicit(cxxConstructExpr(isListInitialization()))); |
| 169 |
|
| 170 |
// We could have leak of resource. |
| 171 |
auto NewExprAsArgument = hasAnyArgument(ignoringImplicit(cxxNewExpr())); |
| 172 |
// We would call another constructor. |
| 173 |
auto ConstructingDerived = |
| 174 |
hasParent(implicitCastExpr(hasCastKind(CastKind::CK_DerivedToBase))); |
| 175 |
|
| 176 |
// emplace_back can't access private or protected constructors. |
| 177 |
auto IsPrivateOrProtectedCtor = |
| 178 |
hasDeclaration(cxxConstructorDecl(anyOf(isPrivate(), isProtected()))); |
| 179 |
|
| 180 |
auto HasInitList = anyOf(has(ignoringImplicit(initListExpr())), |
| 181 |
has(cxxStdInitializerListExpr())); |
| 182 |
|
| 183 |
// FIXME: Discard 0/NULL (as nullptr), static inline const data members, |
| 184 |
// overloaded functions and template names. |
| 185 |
auto SoughtConstructExpr = |
| 186 |
cxxConstructExpr( |
| 187 |
unless(anyOf(IsCtorOfSmartPtr, HasInitList, BitFieldAsArgument, |
| 188 |
InitializerListAsArgument, NewExprAsArgument, |
| 189 |
ConstructingDerived, IsPrivateOrProtectedCtor))) |
| 190 |
.bind("ctor"); |
| 191 |
auto HasConstructExpr = has(ignoringImplicit(SoughtConstructExpr)); |
| 192 |
|
| 193 |
auto MakeTuple = ignoringImplicit( |
| 194 |
callExpr(callee(expr(ignoringImplicit(declRefExpr( |
| 195 |
unless(hasExplicitTemplateArgs()), |
| 196 |
to(functionDecl(hasAnyName(TupleMakeFunctions)))))))) |
| 197 |
.bind("make")); |
| 198 |
|
| 199 |
// make_something can return type convertible to container's element type. |
| 200 |
// Allow the conversion only on containers of pairs. |
| 201 |
auto MakeTupleCtor = ignoringImplicit(cxxConstructExpr( |
| 202 |
has(materializeTemporaryExpr(MakeTuple)), |
| 203 |
hasDeclaration(cxxConstructorDecl(ofClass(hasAnyName(TupleTypes)))))); |
| 204 |
|
| 205 |
auto SoughtParam = materializeTemporaryExpr( |
| 206 |
anyOf(has(MakeTuple), has(MakeTupleCtor), HasConstructExpr, |
| 207 |
has(cxxFunctionalCastExpr(HasConstructExpr)))); |
| 208 |
|
| 209 |
auto HasConstructExprWithValueTypeType = |
| 210 |
has(ignoringImplicit(cxxConstructExpr( |
| 211 |
SoughtConstructExpr, hasType(type(hasUnqualifiedDesugaredType( |
| 212 |
type(equalsBoundNode("value_type")))))))); |
| 213 |
|
| 214 |
auto HasConstructExprWithValueTypeTypeAsLastArgument = |
| 215 |
hasLastArgument(materializeTemporaryExpr(anyOf( |
| 216 |
HasConstructExprWithValueTypeType, |
| 217 |
has(cxxFunctionalCastExpr(HasConstructExprWithValueTypeType))))); |
| 218 |
|
| 219 |
Finder->addMatcher( |
| 220 |
traverse(TK_AsIs, cxxMemberCallExpr(CallPushBack, has(SoughtParam), |
| 221 |
unless(isInTemplateInstantiation())) |
| 222 |
.bind("push_back_call")), |
| 223 |
this); |
| 224 |
|
| 225 |
Finder->addMatcher( |
| 226 |
traverse(TK_AsIs, cxxMemberCallExpr(CallPush, has(SoughtParam), |
| 227 |
unless(isInTemplateInstantiation())) |
| 228 |
.bind("push_call")), |
| 229 |
this); |
| 230 |
|
| 231 |
Finder->addMatcher( |
| 232 |
traverse(TK_AsIs, cxxMemberCallExpr(CallPushFront, has(SoughtParam), |
| 233 |
unless(isInTemplateInstantiation())) |
| 234 |
.bind("push_front_call")), |
| 235 |
this); |
| 236 |
|
| 237 |
Finder->addMatcher( |
| 238 |
traverse(TK_AsIs, |
| 239 |
cxxMemberCallExpr( |
| 240 |
CallEmplacy, HasConstructExprWithValueTypeTypeAsLastArgument, |
| 241 |
hasSameNumArgsAsDeclNumParams(), |
| 242 |
unless(isInTemplateInstantiation())) |
| 243 |
.bind("emplacy_call")), |
| 244 |
this); |
| 245 |
|
| 246 |
Finder->addMatcher( |
| 247 |
traverse( |
| 248 |
TK_AsIs, |
| 249 |
cxxMemberCallExpr( |
| 250 |
CallEmplacy, |
| 251 |
on(hasType(cxxRecordDecl(has(typedefNameDecl( |
| 252 |
hasName("value_type"), |
| 253 |
hasType(type( |
| 254 |
hasUnqualifiedDesugaredType(recordType(hasDeclaration( |
| 255 |
cxxRecordDecl(hasAnyName(SmallVector<StringRef, 2>( |
| 256 |
TupleTypes.begin(), TupleTypes.end()))))))))))))), |
| 257 |
has(MakeTuple), hasSameNumArgsAsDeclNumParams(), |
| 258 |
unless(isInTemplateInstantiation())) |
| 259 |
.bind("emplacy_call")), |
| 260 |
this); |
| 261 |
} |
| 262 |
|
| 263 |
void UseEmplaceCheck::check(const MatchFinder::MatchResult &Result) { |
| 264 |
const auto *PushBackCall = |
| 265 |
Result.Nodes.getNodeAs<CXXMemberCallExpr>("push_back_call"); |
| 266 |
const auto *PushCall = Result.Nodes.getNodeAs<CXXMemberCallExpr>("push_call"); |
| 267 |
const auto *PushFrontCall = |
| 268 |
Result.Nodes.getNodeAs<CXXMemberCallExpr>("push_front_call"); |
| 269 |
const auto *EmplacyCall = |
| 270 |
Result.Nodes.getNodeAs<CXXMemberCallExpr>("emplacy_call"); |
| 271 |
const auto *CtorCall = Result.Nodes.getNodeAs<CXXConstructExpr>("ctor"); |
| 272 |
const auto *MakeCall = Result.Nodes.getNodeAs<CallExpr>("make"); |
| 273 |
|
| 274 |
const CXXMemberCallExpr *Call = [&]() { |
| 275 |
if (PushBackCall) { |
| 276 |
return PushBackCall; |
| 277 |
} |
| 278 |
if (PushCall) { |
| 279 |
return PushCall; |
| 280 |
} |
| 281 |
if (PushFrontCall) { |
| 282 |
return PushFrontCall; |
| 283 |
} |
| 284 |
return EmplacyCall; |
| 285 |
}(); |
| 286 |
|
| 287 |
assert(Call && "No call matched"); |
| 288 |
assert((CtorCall || MakeCall) && "No push_back parameter matched"); |
| 289 |
|
| 290 |
if (IgnoreImplicitConstructors && CtorCall && CtorCall->getNumArgs() >= 1 && |
| 291 |
CtorCall->getArg(0)->getSourceRange() == CtorCall->getSourceRange()) |
| 292 |
return; |
| 293 |
|
| 294 |
const auto FunctionNameSourceRange = CharSourceRange::getCharRange( |
| 295 |
Call->getExprLoc(), Call->getArg(0)->getExprLoc()); |
| 296 |
|
| 297 |
auto Diag = |
| 298 |
EmplacyCall |
| 299 |
? diag(CtorCall ? CtorCall->getBeginLoc() : MakeCall->getBeginLoc(), |
| 300 |
"unnecessary temporary object created while calling %0") |
| 301 |
: diag(Call->getExprLoc(), "use emplace%select{|_back|_front}0 " |
| 302 |
"instead of push%select{|_back|_front}0"); |
| 303 |
if (EmplacyCall) |
| 304 |
Diag << Call->getMethodDecl()->getName(); |
| 305 |
else if (PushCall) |
| 306 |
Diag << 0; |
| 307 |
else if (PushBackCall) |
| 308 |
Diag << 1; |
| 309 |
else |
| 310 |
Diag << 2; |
| 311 |
|
| 312 |
if (FunctionNameSourceRange.getBegin().isMacroID()) |
| 313 |
return; |
| 314 |
|
| 315 |
if (PushBackCall) { |
| 316 |
const char *EmplacePrefix = MakeCall ? "emplace_back" : "emplace_back("; |
| 317 |
Diag << FixItHint::CreateReplacement(FunctionNameSourceRange, |
| 318 |
EmplacePrefix); |
| 319 |
} else if (PushCall) { |
| 320 |
const char *EmplacePrefix = MakeCall ? "emplace" : "emplace("; |
| 321 |
Diag << FixItHint::CreateReplacement(FunctionNameSourceRange, |
| 322 |
EmplacePrefix); |
| 323 |
} else if (PushFrontCall) { |
| 324 |
const char *EmplacePrefix = MakeCall ? "emplace_front" : "emplace_front("; |
| 325 |
Diag << FixItHint::CreateReplacement(FunctionNameSourceRange, |
| 326 |
EmplacePrefix); |
| 327 |
} |
| 328 |
|
| 329 |
const SourceRange CallParensRange = |
| 330 |
MakeCall ? SourceRange(MakeCall->getCallee()->getEndLoc(), |
| 331 |
MakeCall->getRParenLoc()) |
| 332 |
: CtorCall->getParenOrBraceRange(); |
| 333 |
|
| 334 |
// Finish if there is no explicit constructor call. |
| 335 |
if (CallParensRange.getBegin().isInvalid()) |
| 336 |
return; |
| 337 |
|
| 338 |
const SourceLocation ExprBegin = |
| 339 |
CtorCall ? CtorCall->getExprLoc() : MakeCall->getExprLoc(); |
| 340 |
|
| 341 |
// Range for constructor name and opening brace. |
| 342 |
const auto ParamCallSourceRange = |
| 343 |
CharSourceRange::getTokenRange(ExprBegin, CallParensRange.getBegin()); |
| 344 |
|
| 345 |
Diag << FixItHint::CreateRemoval(ParamCallSourceRange) |
| 346 |
<< FixItHint::CreateRemoval(CharSourceRange::getTokenRange( |
| 347 |
CallParensRange.getEnd(), CallParensRange.getEnd())); |
| 348 |
|
| 349 |
if (MakeCall && EmplacyCall) { |
| 350 |
// Remove extra left parenthesis |
| 351 |
Diag << FixItHint::CreateRemoval( |
| 352 |
CharSourceRange::getCharRange(MakeCall->getCallee()->getEndLoc(), |
| 353 |
MakeCall->getArg(0)->getBeginLoc())); |
| 354 |
} |
| 355 |
} |
| 356 |
|
| 357 |
void UseEmplaceCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) { |
| 358 |
Options.store(Opts, "IgnoreImplicitConstructors", IgnoreImplicitConstructors); |
| 359 |
Options.store(Opts, "ContainersWithPushBack", |
| 360 |
utils::options::serializeStringList(ContainersWithPushBack)); |
| 361 |
Options.store(Opts, "ContainersWithPush", |
| 362 |
utils::options::serializeStringList(ContainersWithPush)); |
| 363 |
Options.store(Opts, "ContainersWithPushFront", |
| 364 |
utils::options::serializeStringList(ContainersWithPushFront)); |
| 365 |
Options.store(Opts, "SmartPointers", |
| 366 |
utils::options::serializeStringList(SmartPointers)); |
| 367 |
Options.store(Opts, "TupleTypes", |
| 368 |
utils::options::serializeStringList(TupleTypes)); |
| 369 |
Options.store(Opts, "TupleMakeFunctions", |
| 370 |
utils::options::serializeStringList(TupleMakeFunctions)); |
| 371 |
Options.store(Opts, "EmplacyFunctions", |
| 372 |
utils::options::serializeStringList(EmplacyFunctions)); |
| 373 |
} |
| 374 |
|
| 375 |
} // namespace clang::tidy::modernize |