clang-tools 23.0.0git
AvoidCapturingLambdaCoroutinesCheck.cpp
Go to the documentation of this file.
1//===----------------------------------------------------------------------===//
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
10#include "clang/AST/ASTContext.h"
11#include "clang/ASTMatchers/ASTMatchFinder.h"
12
13using namespace clang::ast_matchers;
14
16
17namespace {
18AST_MATCHER(LambdaExpr, hasCoroutineBody) {
19 const Stmt *Body = Node.getBody();
20 return Body != nullptr && isa<CoroutineBodyStmt>(Body);
21}
22
23AST_MATCHER(LambdaExpr, hasCaptures) { return Node.capture_size() != 0U; }
24
25AST_MATCHER(LambdaExpr, hasDeducingThis) {
26 return Node.getCallOperator()->isExplicitObjectMemberFunction();
27}
28} // namespace
29
31 StringRef Name, ClangTidyContext *Context)
32 : ClangTidyCheck(Name, Context),
33 AllowExplicitObjectParameters(
34 Options.get("AllowExplicitObjectParameters", false)) {}
35
37 MatchFinder *Finder) {
38 using LambdaExprMatcher = ast_matchers::internal::Matcher<LambdaExpr>;
39 const auto ExplicitObjectFilter =
40 AllowExplicitObjectParameters
41 ? LambdaExprMatcher(unless(hasDeducingThis()))
42 : LambdaExprMatcher(anything());
43 Finder->addMatcher(
44 lambdaExpr(hasCaptures(), hasCoroutineBody(), ExplicitObjectFilter)
45 .bind("lambda"),
46 this);
47}
48
50 const LangOptions &LangOpts) const {
51 return LangOpts.CPlusPlus20;
52}
53
56 Options.store(Opts, "AllowExplicitObjectParameters",
57 AllowExplicitObjectParameters);
58}
59
61 const MatchFinder::MatchResult &Result) {
62 const auto *MatchedLambda = Result.Nodes.getNodeAs<LambdaExpr>("lambda");
63 diag(MatchedLambda->getExprLoc(),
64 "coroutine lambda may cause use-after-free, avoid captures or ensure "
65 "lambda closure object has guaranteed lifetime");
66}
67
68} // namespace clang::tidy::cppcoreguidelines
Every ClangTidyCheck reports errors through a DiagnosticsEngine provided by this context.
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
llvm::StringMap< ClangTidyValue > OptionMap