1//===--- AvoidBindCheck.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 "AvoidBindCheck.h"
10#include "clang/AST/ASTContext.h"
11#include "clang/ASTMatchers/ASTMatchFinder.h"
12#include "clang/Basic/LLVM.h"
13#include "clang/Basic/SourceLocation.h"
14#include "clang/Lex/Lexer.h"
15#include "llvm/ADT/ArrayRef.h"
16#include "llvm/ADT/STLExtras.h"
17#include "llvm/ADT/SmallSet.h"
18#include "llvm/ADT/SmallVector.h"
19#include "llvm/ADT/StringRef.h"
20#include "llvm/ADT/StringSet.h"
21#include "llvm/Support/FormatVariadic.h"
22#include "llvm/Support/Regex.h"
23#include "llvm/Support/raw_ostream.h"
24#include <cstddef>
25#include <string>
26
27using namespace clang::ast_matchers;
28
29namespace clang::tidy::modernize {
30
31namespace {
32
33enum BindArgumentKind { BK_Temporary, BK_Placeholder, BK_CallExpr, BK_Other };
34enum CaptureMode { CM_None, CM_ByRef, CM_ByValue };
35enum CaptureExpr { CE_None, CE_Var, CE_InitExpression };
36
37enum CallableType {
38 CT_Other, // unknown
39 CT_Function, // global or static function
40 CT_MemberFunction, // member function with implicit this
41 CT_Object, // object with operator()
42};
43
44enum CallableMaterializationKind {
45 CMK_Other, // unknown
46 CMK_Function, // callable is the name of a member or non-member function.
47 CMK_VariableRef, // callable is a simple expression involving a global or
48 // local variable.
49 CMK_CallExpression, // callable is obtained as the result of a call expression
50};
51
52struct BindArgument {
53 // A rough classification of the type of expression this argument was.
54 BindArgumentKind Kind = BK_Other;
55
56 // If this argument required a capture, a value indicating how it was
57 // captured.
58 CaptureMode CM = CM_None;
59
60 // Whether the argument is a simple variable (we can capture it directly),
61 // or an expression (we must introduce a capture variable).
62 CaptureExpr CE = CE_None;
63
64 // The exact spelling of this argument in the source code.
65 StringRef SourceTokens;
66
67 // The identifier of the variable within the capture list. This may be
68 // different from UsageIdentifier for example in the expression *d, where the
69 // variable is captured as d, but referred to as *d.
70 std::string CaptureIdentifier;
71
72 // If this is a placeholder or capture init expression, contains the tokens
73 // used to refer to this parameter from within the body of the lambda.
74 std::string UsageIdentifier;
75
76 // If Kind == BK_Placeholder, the index of the placeholder.
77 size_t PlaceHolderIndex = 0;
78
79 // True if the argument is used inside the lambda, false otherwise.
80 bool IsUsed = false;
81
82 // The actual Expr object representing this expression.
83 const Expr *E = nullptr;
84};
85
86struct CallableInfo {
87 CallableType Type = CT_Other;
88 CallableMaterializationKind Materialization = CMK_Other;
89 CaptureMode CM = CM_None;
90 CaptureExpr CE = CE_None;
91 StringRef SourceTokens;
92 std::string CaptureIdentifier;
93 std::string UsageIdentifier;
94 StringRef CaptureInitializer;
95 const FunctionDecl *Decl = nullptr;
96 bool DoesReturn = false;
97};
98
99struct LambdaProperties {
100 CallableInfo Callable;
101 SmallVector<BindArgument, 4> BindArguments;
102 StringRef BindNamespace;
103 bool IsFixitSupported = false;
104};
105
106} // end namespace
107
108static bool tryCaptureAsLocalVariable(const MatchFinder::MatchResult &Result,
109 BindArgument &B, const Expr *E);
110
111static bool tryCaptureAsMemberVariable(const MatchFinder::MatchResult &Result,
112 BindArgument &B, const Expr *E);
113
114static const Expr *ignoreTemporariesAndPointers(const Expr *E) {
115 if (const auto *T = dyn_cast<UnaryOperator>(Val: E))
116 return ignoreTemporariesAndPointers(E: T->getSubExpr());
117
118 const Expr *F = E->IgnoreImplicit();
119 if (E != F)
120 return ignoreTemporariesAndPointers(E: F);
121
122 return E;
123}
124
125static const Expr *ignoreTemporariesAndConstructors(const Expr *E) {
126 if (const auto *T = dyn_cast<CXXConstructExpr>(Val: E))
127 return ignoreTemporariesAndConstructors(E: T->getArg(Arg: 0));
128
129 const Expr *F = E->IgnoreImplicit();
130 if (E != F)
131 return ignoreTemporariesAndPointers(E: F);
132
133 return E;
134}
135
136static StringRef getSourceTextForExpr(const MatchFinder::MatchResult &Result,
137 const Expr *E) {
138 return Lexer::getSourceText(
139 Range: CharSourceRange::getTokenRange(E->getBeginLoc(), E->getEndLoc()),
140 SM: *Result.SourceManager, LangOpts: Result.Context->getLangOpts());
141}
142
143static bool isCallExprNamed(const Expr *E, StringRef Name) {
144 const auto *CE = dyn_cast<CallExpr>(Val: E->IgnoreImplicit());
145 if (!CE)
146 return false;
147 const auto *ND = dyn_cast<NamedDecl>(Val: CE->getCalleeDecl());
148 if (!ND)
149 return false;
150 return ND->getQualifiedNameAsString() == Name;
151}
152
153static void
154initializeBindArgumentForCallExpr(const MatchFinder::MatchResult &Result,
155 BindArgument &B, const CallExpr *CE,
156 unsigned &CaptureIndex) {
157 // std::ref(x) means to capture x by reference.
158 if (isCallExprNamed(CE, "boost::ref") || isCallExprNamed(CE, "std::ref")) {
159 B.Kind = BK_Other;
160 if (tryCaptureAsLocalVariable(Result, B, E: CE->getArg(Arg: 0)) ||
161 tryCaptureAsMemberVariable(Result, B, E: CE->getArg(Arg: 0))) {
162 B.CE = CE_Var;
163 } else {
164 // The argument to std::ref is an expression that produces a reference.
165 // Create a capture reference to hold it.
166 B.CE = CE_InitExpression;
167 B.UsageIdentifier = "capture" + llvm::utostr(X: CaptureIndex++);
168 }
169 // Strip off the reference wrapper.
170 B.SourceTokens = getSourceTextForExpr(Result, E: CE->getArg(Arg: 0));
171 B.CM = CM_ByRef;
172 } else {
173 B.Kind = BK_CallExpr;
174 B.CM = CM_ByValue;
175 B.CE = CE_InitExpression;
176 B.UsageIdentifier = "capture" + llvm::utostr(X: CaptureIndex++);
177 }
178 B.CaptureIdentifier = B.UsageIdentifier;
179}
180
181static bool anyDescendantIsLocal(const Stmt *Statement) {
182 if (const auto *DeclRef = dyn_cast<DeclRefExpr>(Val: Statement)) {
183 const ValueDecl *Decl = DeclRef->getDecl();
184 if (const auto *Var = dyn_cast_or_null<VarDecl>(Val: Decl)) {
185 if (Var->isLocalVarDeclOrParm())
186 return true;
187 }
188 } else if (isa<CXXThisExpr>(Val: Statement))
189 return true;
190
191 return any_of(Range: Statement->children(), P: anyDescendantIsLocal);
192}
193
194static bool tryCaptureAsLocalVariable(const MatchFinder::MatchResult &Result,
195 BindArgument &B, const Expr *E) {
196 if (const auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Val: E)) {
197 if (const auto *CE = dyn_cast<CXXConstructExpr>(Val: BTE->getSubExpr()))
198 return tryCaptureAsLocalVariable(Result, B, E: CE->getArg(Arg: 0));
199 return false;
200 }
201
202 const auto *DRE = dyn_cast<DeclRefExpr>(Val: E->IgnoreImplicit());
203 if (!DRE)
204 return false;
205
206 const auto *VD = dyn_cast<VarDecl>(Val: DRE->getDecl());
207 if (!VD || !VD->isLocalVarDeclOrParm())
208 return false;
209
210 B.CM = CM_ByValue;
211 B.UsageIdentifier = std::string(getSourceTextForExpr(Result, E));
212 B.CaptureIdentifier = B.UsageIdentifier;
213 return true;
214}
215
216static bool tryCaptureAsMemberVariable(const MatchFinder::MatchResult &Result,
217 BindArgument &B, const Expr *E) {
218 if (const auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Val: E)) {
219 if (const auto *CE = dyn_cast<CXXConstructExpr>(Val: BTE->getSubExpr()))
220 return tryCaptureAsMemberVariable(Result, B, E: CE->getArg(Arg: 0));
221 return false;
222 }
223
224 E = E->IgnoreImplicit();
225 if (isa<CXXThisExpr>(Val: E)) {
226 // E is a direct use of "this".
227 B.CM = CM_ByValue;
228 B.UsageIdentifier = std::string(getSourceTextForExpr(Result, E));
229 B.CaptureIdentifier = "this";
230 return true;
231 }
232
233 const auto *ME = dyn_cast<MemberExpr>(Val: E);
234 if (!ME)
235 return false;
236
237 if (!ME->isLValue() || !isa<FieldDecl>(Val: ME->getMemberDecl()))
238 return false;
239
240 if (isa<CXXThisExpr>(Val: ME->getBase())) {
241 // E refers to a data member without an explicit "this".
242 B.CM = CM_ByValue;
243 B.UsageIdentifier = std::string(getSourceTextForExpr(Result, E));
244 B.CaptureIdentifier = "this";
245 return true;
246 }
247
248 return false;
249}
250
251static SmallVector<BindArgument, 4>
252buildBindArguments(const MatchFinder::MatchResult &Result,
253 const CallableInfo &Callable) {
254 SmallVector<BindArgument, 4> BindArguments;
255 static llvm::Regex MatchPlaceholder("^_([0-9]+)$");
256
257 const auto *BindCall = Result.Nodes.getNodeAs<CallExpr>(ID: "bind");
258
259 // Start at index 1 as first argument to bind is the function name.
260 unsigned CaptureIndex = 0;
261 for (size_t I = 1, ArgCount = BindCall->getNumArgs(); I < ArgCount; ++I) {
262
263 const Expr *E = BindCall->getArg(Arg: I);
264 BindArgument &B = BindArguments.emplace_back();
265
266 size_t ArgIndex = I - 1;
267 if (Callable.Type == CT_MemberFunction)
268 --ArgIndex;
269
270 bool IsObjectPtr = (I == 1 && Callable.Type == CT_MemberFunction);
271 B.E = E;
272 B.SourceTokens = getSourceTextForExpr(Result, E);
273
274 if (!Callable.Decl || ArgIndex < Callable.Decl->getNumParams() ||
275 IsObjectPtr)
276 B.IsUsed = true;
277
278 SmallVector<StringRef, 2> Matches;
279 const auto *DRE = dyn_cast<DeclRefExpr>(Val: E);
280 if (MatchPlaceholder.match(String: B.SourceTokens, Matches: &Matches) ||
281 // Check for match with qualifiers removed.
282 (DRE && MatchPlaceholder.match(String: DRE->getDecl()->getName(), Matches: &Matches))) {
283 B.Kind = BK_Placeholder;
284 B.PlaceHolderIndex = std::stoi(str: std::string(Matches[1]));
285 B.UsageIdentifier = "PH" + llvm::utostr(X: B.PlaceHolderIndex);
286 B.CaptureIdentifier = B.UsageIdentifier;
287 continue;
288 }
289
290 if (const auto *CE =
291 dyn_cast<CallExpr>(Val: ignoreTemporariesAndConstructors(E))) {
292 initializeBindArgumentForCallExpr(Result, B, CE, CaptureIndex);
293 continue;
294 }
295
296 if (tryCaptureAsLocalVariable(Result, B, E: B.E) ||
297 tryCaptureAsMemberVariable(Result, B, E: B.E))
298 continue;
299
300 // If it's not something we recognize, capture it by init expression to be
301 // safe.
302 B.Kind = BK_Other;
303 if (IsObjectPtr) {
304 B.CE = CE_InitExpression;
305 B.CM = CM_ByValue;
306 B.UsageIdentifier = "ObjectPtr";
307 B.CaptureIdentifier = B.UsageIdentifier;
308 } else if (anyDescendantIsLocal(B.E)) {
309 B.CE = CE_InitExpression;
310 B.CM = CM_ByValue;
311 B.CaptureIdentifier = "capture" + llvm::utostr(X: CaptureIndex++);
312 B.UsageIdentifier = B.CaptureIdentifier;
313 }
314 }
315 return BindArguments;
316}
317
318static int findPositionOfPlaceholderUse(ArrayRef<BindArgument> Args,
319 size_t PlaceholderIndex) {
320 for (size_t I = 0; I < Args.size(); ++I)
321 if (Args[I].PlaceHolderIndex == PlaceholderIndex)
322 return I;
323
324 return -1;
325}
326
327static void addPlaceholderArgs(const LambdaProperties &LP,
328 llvm::raw_ostream &Stream,
329 bool PermissiveParameterList) {
330
331 ArrayRef<BindArgument> Args = LP.BindArguments;
332
333 const auto *MaxPlaceholderIt = llvm::max_element(
334 Range&: Args, C: [](const BindArgument &B1, const BindArgument &B2) {
335 return B1.PlaceHolderIndex < B2.PlaceHolderIndex;
336 });
337
338 // Placeholders (if present) have index 1 or greater.
339 if (!PermissiveParameterList && (MaxPlaceholderIt == Args.end() ||
340 MaxPlaceholderIt->PlaceHolderIndex == 0))
341 return;
342
343 size_t PlaceholderCount = MaxPlaceholderIt->PlaceHolderIndex;
344 Stream << "(";
345 StringRef Delimiter = "";
346 for (size_t I = 1; I <= PlaceholderCount; ++I) {
347 Stream << Delimiter << "auto &&";
348
349 int ArgIndex = findPositionOfPlaceholderUse(Args, PlaceholderIndex: I);
350
351 if (ArgIndex != -1 && Args[ArgIndex].IsUsed)
352 Stream << " " << Args[ArgIndex].UsageIdentifier;
353 Delimiter = ", ";
354 }
355 if (PermissiveParameterList)
356 Stream << Delimiter << "auto && ...";
357 Stream << ")";
358}
359
360static void addFunctionCallArgs(ArrayRef<BindArgument> Args,
361 llvm::raw_ostream &Stream) {
362 StringRef Delimiter = "";
363
364 for (const BindArgument &B : Args) {
365 Stream << Delimiter;
366
367 if (B.Kind == BK_Placeholder) {
368 Stream << "std::forward<decltype(" << B.UsageIdentifier << ")>";
369 Stream << "(" << B.UsageIdentifier << ")";
370 } else if (B.CM != CM_None)
371 Stream << B.UsageIdentifier;
372 else
373 Stream << B.SourceTokens;
374
375 Delimiter = ", ";
376 }
377}
378
379static bool isPlaceHolderIndexRepeated(const ArrayRef<BindArgument> Args) {
380 llvm::SmallSet<size_t, 4> PlaceHolderIndices;
381 for (const BindArgument &B : Args) {
382 if (B.PlaceHolderIndex) {
383 if (!PlaceHolderIndices.insert(V: B.PlaceHolderIndex).second)
384 return true;
385 }
386 }
387 return false;
388}
389
390static std::vector<const FunctionDecl *>
391findCandidateCallOperators(const CXXRecordDecl *RecordDecl, size_t NumArgs) {
392 std::vector<const FunctionDecl *> Candidates;
393
394 for (const clang::CXXMethodDecl *Method : RecordDecl->methods()) {
395 OverloadedOperatorKind OOK = Method->getOverloadedOperator();
396
397 if (OOK != OverloadedOperatorKind::OO_Call)
398 continue;
399
400 if (Method->getNumParams() > NumArgs)
401 continue;
402
403 Candidates.push_back(Method);
404 }
405
406 // Find templated operator(), if any.
407 for (const clang::Decl *D : RecordDecl->decls()) {
408 const auto *FTD = dyn_cast<FunctionTemplateDecl>(D);
409 if (!FTD)
410 continue;
411 const FunctionDecl *FD = FTD->getTemplatedDecl();
412
413 OverloadedOperatorKind OOK = FD->getOverloadedOperator();
414 if (OOK != OverloadedOperatorKind::OO_Call)
415 continue;
416
417 if (FD->getNumParams() > NumArgs)
418 continue;
419
420 Candidates.push_back(FD);
421 }
422
423 return Candidates;
424}
425
426static bool isFixitSupported(const CallableInfo &Callee,
427 ArrayRef<BindArgument> Args) {
428 // Do not attempt to create fixits for nested std::bind or std::ref.
429 // Supporting nested std::bind will be more difficult due to placeholder
430 // sharing between outer and inner std::bind invocations, and std::ref
431 // requires us to capture some parameters by reference instead of by value.
432 if (any_of(Range&: Args, P: [](const BindArgument &B) {
433 return isCallExprNamed(E: B.E, Name: "boost::bind") ||
434 isCallExprNamed(E: B.E, Name: "std::bind");
435 })) {
436 return false;
437 }
438
439 // Do not attempt to create fixits when placeholders are reused.
440 // Unused placeholders are supported by requiring C++14 generic lambdas.
441 // FIXME: Support this case by deducing the common type.
442 if (isPlaceHolderIndexRepeated(Args))
443 return false;
444
445 // If we can't determine the Decl being used, don't offer a fixit.
446 if (!Callee.Decl)
447 return false;
448
449 if (Callee.Type == CT_Other || Callee.Materialization == CMK_Other)
450 return false;
451
452 return true;
453}
454
455static const FunctionDecl *getCallOperator(const CXXRecordDecl *Callable,
456 size_t NumArgs) {
457 std::vector<const FunctionDecl *> Candidates =
458 findCandidateCallOperators(RecordDecl: Callable, NumArgs);
459 if (Candidates.size() != 1)
460 return nullptr;
461
462 return Candidates.front();
463}
464
465static const FunctionDecl *
466getCallMethodDecl(const MatchFinder::MatchResult &Result, CallableType Type,
467 CallableMaterializationKind Materialization) {
468
469 const Expr *Callee = Result.Nodes.getNodeAs<Expr>(ID: "ref");
470 const Expr *CallExpression = ignoreTemporariesAndPointers(E: Callee);
471
472 if (Type == CT_Object) {
473 const auto *BindCall = Result.Nodes.getNodeAs<CallExpr>(ID: "bind");
474 size_t NumArgs = BindCall->getNumArgs() - 1;
475 return getCallOperator(Callable: Callee->getType()->getAsCXXRecordDecl(), NumArgs);
476 }
477
478 if (Materialization == CMK_Function) {
479 if (const auto *DRE = dyn_cast<DeclRefExpr>(Val: CallExpression))
480 return dyn_cast<FunctionDecl>(Val: DRE->getDecl());
481 }
482
483 // Maybe this is an indirect call through a function pointer or something
484 // where we can't determine the exact decl.
485 return nullptr;
486}
487
488static CallableType getCallableType(const MatchFinder::MatchResult &Result) {
489 const auto *CallableExpr = Result.Nodes.getNodeAs<Expr>(ID: "ref");
490
491 QualType QT = CallableExpr->getType();
492 if (QT->isMemberFunctionPointerType())
493 return CT_MemberFunction;
494
495 if (QT->isFunctionPointerType() || QT->isFunctionReferenceType() ||
496 QT->isFunctionType())
497 return CT_Function;
498
499 if (QT->isRecordType()) {
500 const CXXRecordDecl *Decl = QT->getAsCXXRecordDecl();
501 if (!Decl)
502 return CT_Other;
503
504 return CT_Object;
505 }
506
507 return CT_Other;
508}
509
510static CallableMaterializationKind
511getCallableMaterialization(const MatchFinder::MatchResult &Result) {
512 const auto *CallableExpr = Result.Nodes.getNodeAs<Expr>(ID: "ref");
513
514 const auto *NoTemporaries = ignoreTemporariesAndPointers(E: CallableExpr);
515
516 const auto *CE = dyn_cast<CXXConstructExpr>(Val: NoTemporaries);
517 const auto *FC = dyn_cast<CXXFunctionalCastExpr>(Val: NoTemporaries);
518 if ((isa<CallExpr>(Val: NoTemporaries)) || (CE && (CE->getNumArgs() > 0)) ||
519 (FC && (FC->getCastKind() == CK_ConstructorConversion)))
520 // CE is something that looks like a call, with arguments - either
521 // a function call or a constructor invocation.
522 return CMK_CallExpression;
523
524 if (isa<CXXFunctionalCastExpr>(Val: NoTemporaries) || CE)
525 return CMK_Function;
526
527 if (const auto *DRE = dyn_cast<DeclRefExpr>(Val: NoTemporaries)) {
528 if (isa<FunctionDecl>(Val: DRE->getDecl()))
529 return CMK_Function;
530 if (isa<VarDecl>(Val: DRE->getDecl()))
531 return CMK_VariableRef;
532 }
533
534 return CMK_Other;
535}
536
537static LambdaProperties
538getLambdaProperties(const MatchFinder::MatchResult &Result) {
539 const auto *CalleeExpr = Result.Nodes.getNodeAs<Expr>(ID: "ref");
540
541 LambdaProperties LP;
542
543 const auto *Bind = Result.Nodes.getNodeAs<CallExpr>(ID: "bind");
544 const auto *Decl = cast<FunctionDecl>(Val: Bind->getCalleeDecl());
545 const auto *NS = cast<NamespaceDecl>(Decl->getEnclosingNamespaceContext());
546 while (NS->isInlineNamespace())
547 NS = cast<NamespaceDecl>(NS->getDeclContext());
548 LP.BindNamespace = NS->getName();
549
550 LP.Callable.Type = getCallableType(Result);
551 LP.Callable.Materialization = getCallableMaterialization(Result);
552 LP.Callable.Decl =
553 getCallMethodDecl(Result, Type: LP.Callable.Type, Materialization: LP.Callable.Materialization);
554 if (LP.Callable.Decl)
555 if (const Type *ReturnType =
556 LP.Callable.Decl->getReturnType().getCanonicalType().getTypePtr())
557 LP.Callable.DoesReturn = !ReturnType->isVoidType();
558 LP.Callable.SourceTokens = getSourceTextForExpr(Result, E: CalleeExpr);
559 if (LP.Callable.Materialization == CMK_VariableRef) {
560 LP.Callable.CE = CE_Var;
561 LP.Callable.CM = CM_ByValue;
562 LP.Callable.UsageIdentifier =
563 std::string(getSourceTextForExpr(Result, E: CalleeExpr));
564 LP.Callable.CaptureIdentifier = std::string(
565 getSourceTextForExpr(Result, E: ignoreTemporariesAndPointers(E: CalleeExpr)));
566 } else if (LP.Callable.Materialization == CMK_CallExpression) {
567 LP.Callable.CE = CE_InitExpression;
568 LP.Callable.CM = CM_ByValue;
569 LP.Callable.UsageIdentifier = "Func";
570 LP.Callable.CaptureIdentifier = "Func";
571 LP.Callable.CaptureInitializer = getSourceTextForExpr(Result, E: CalleeExpr);
572 }
573
574 LP.BindArguments = buildBindArguments(Result, Callable: LP.Callable);
575
576 LP.IsFixitSupported = isFixitSupported(Callee: LP.Callable, Args: LP.BindArguments);
577
578 return LP;
579}
580
581static bool emitCapture(llvm::StringSet<> &CaptureSet, StringRef Delimiter,
582 CaptureMode CM, CaptureExpr CE, StringRef Identifier,
583 StringRef InitExpression, raw_ostream &Stream) {
584 if (CM == CM_None)
585 return false;
586
587 // This capture has already been emitted.
588 if (CaptureSet.count(Key: Identifier) != 0)
589 return false;
590
591 Stream << Delimiter;
592
593 if (CM == CM_ByRef)
594 Stream << "&";
595 Stream << Identifier;
596 if (CE == CE_InitExpression)
597 Stream << " = " << InitExpression;
598
599 CaptureSet.insert(key: Identifier);
600 return true;
601}
602
603static void emitCaptureList(const LambdaProperties &LP,
604 const MatchFinder::MatchResult &Result,
605 raw_ostream &Stream) {
606 llvm::StringSet<> CaptureSet;
607 bool AnyCapturesEmitted = false;
608
609 AnyCapturesEmitted = emitCapture(
610 CaptureSet, Delimiter: "", CM: LP.Callable.CM, CE: LP.Callable.CE,
611 Identifier: LP.Callable.CaptureIdentifier, InitExpression: LP.Callable.CaptureInitializer, Stream);
612
613 for (const BindArgument &B : LP.BindArguments) {
614 if (B.CM == CM_None || !B.IsUsed)
615 continue;
616
617 StringRef Delimiter = AnyCapturesEmitted ? ", " : "";
618
619 if (emitCapture(CaptureSet, Delimiter, CM: B.CM, CE: B.CE, Identifier: B.CaptureIdentifier,
620 InitExpression: B.SourceTokens, Stream))
621 AnyCapturesEmitted = true;
622 }
623}
624
625static ArrayRef<BindArgument>
626getForwardedArgumentList(const LambdaProperties &P) {
627 ArrayRef<BindArgument> Args = ArrayRef(P.BindArguments);
628 if (P.Callable.Type != CT_MemberFunction)
629 return Args;
630
631 return Args.drop_front();
632}
633AvoidBindCheck::AvoidBindCheck(StringRef Name, ClangTidyContext *Context)
634 : ClangTidyCheck(Name, Context),
635 PermissiveParameterList(Options.get(LocalName: "PermissiveParameterList", Default: false)) {}
636
637void AvoidBindCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) {
638 Options.store(Options&: Opts, LocalName: "PermissiveParameterList", Value: PermissiveParameterList);
639}
640
641void AvoidBindCheck::registerMatchers(MatchFinder *Finder) {
642 Finder->addMatcher(
643 NodeMatch: callExpr(
644 callee(InnerMatcher: namedDecl(hasAnyName("::boost::bind", "::std::bind"))),
645 hasArgument(
646 N: 0, InnerMatcher: anyOf(expr(hasType(InnerMatcher: memberPointerType())).bind(ID: "ref"),
647 expr(hasParent(materializeTemporaryExpr().bind(ID: "ref"))),
648 expr().bind(ID: "ref"))))
649 .bind(ID: "bind"),
650 Action: this);
651}
652
653void AvoidBindCheck::check(const MatchFinder::MatchResult &Result) {
654 const auto *MatchedDecl = Result.Nodes.getNodeAs<CallExpr>(ID: "bind");
655
656 LambdaProperties LP = getLambdaProperties(Result);
657 auto Diag =
658 diag(Loc: MatchedDecl->getBeginLoc(),
659 Description: formatv(Fmt: "prefer a lambda to {0}::bind", Vals&: LP.BindNamespace).str());
660 if (!LP.IsFixitSupported)
661 return;
662
663 const auto *Ref = Result.Nodes.getNodeAs<Expr>(ID: "ref");
664
665 std::string Buffer;
666 llvm::raw_string_ostream Stream(Buffer);
667
668 Stream << "[";
669 emitCaptureList(LP, Result, Stream);
670 Stream << "]";
671
672 ArrayRef<BindArgument> FunctionCallArgs = ArrayRef(LP.BindArguments);
673
674 addPlaceholderArgs(LP, Stream, PermissiveParameterList);
675
676 Stream << " { ";
677
678 if (LP.Callable.DoesReturn) {
679 Stream << "return ";
680 }
681
682 if (LP.Callable.Type == CT_Function) {
683 StringRef SourceTokens = LP.Callable.SourceTokens;
684 SourceTokens.consume_front(Prefix: "&");
685 Stream << SourceTokens;
686 } else if (LP.Callable.Type == CT_MemberFunction) {
687 const auto *MethodDecl = dyn_cast<CXXMethodDecl>(Val: LP.Callable.Decl);
688 const BindArgument &ObjPtr = FunctionCallArgs.front();
689
690 if (MethodDecl->getOverloadedOperator() == OO_Call) {
691 Stream << "(*" << ObjPtr.UsageIdentifier << ')';
692 } else {
693 if (!isa<CXXThisExpr>(Val: ignoreTemporariesAndPointers(E: ObjPtr.E))) {
694 Stream << ObjPtr.UsageIdentifier;
695 Stream << "->";
696 }
697 Stream << MethodDecl->getNameAsString();
698 }
699 } else {
700 switch (LP.Callable.CE) {
701 case CE_Var:
702 if (LP.Callable.UsageIdentifier != LP.Callable.CaptureIdentifier) {
703 Stream << "(" << LP.Callable.UsageIdentifier << ")";
704 break;
705 }
706 [[fallthrough]];
707 case CE_InitExpression:
708 Stream << LP.Callable.UsageIdentifier;
709 break;
710 default:
711 Stream << getSourceTextForExpr(Result, E: Ref);
712 }
713 }
714
715 Stream << "(";
716
717 addFunctionCallArgs(Args: getForwardedArgumentList(P: LP), Stream);
718 Stream << "); }";
719
720 Diag << FixItHint::CreateReplacement(MatchedDecl->getSourceRange(),
721 Stream.str());
722}
723
724} // namespace clang::tidy::modernize
725

Provided by KDAB

Privacy Policy
Update your C++ knowledge – Modern C++11/14/17 Training
Find out more

source code of clang-tools-extra/clang-tidy/modernize/AvoidBindCheck.cpp