clang-tools 20.0.0git
AvoidCapturingLambdaCoroutinesCheck.cpp
Go to the documentation of this file.
1//===--- AvoidCapturingLambdaCoroutinesCheck.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
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 && CoroutineBodyStmt::classof(Body);
21}
22
23AST_MATCHER(LambdaExpr, hasCaptures) { return Node.capture_size() != 0U; }
24} // namespace
25
27 MatchFinder *Finder) {
28 Finder->addMatcher(
29 lambdaExpr(hasCaptures(), hasCoroutineBody()).bind("lambda"), this);
30}
31
33 const LangOptions &LangOpts) const {
34 return LangOpts.CPlusPlus20;
35}
36
38 const MatchFinder::MatchResult &Result) {
39 const auto *MatchedLambda = Result.Nodes.getNodeAs<LambdaExpr>("lambda");
40 diag(MatchedLambda->getExprLoc(),
41 "coroutine lambda may cause use-after-free, avoid captures or ensure "
42 "lambda closure object has guaranteed lifetime");
43}
44
45} // namespace clang::tidy::cppcoreguidelines
::clang::DynTypedNode Node
DiagnosticBuilder diag(SourceLocation Loc, StringRef Description, DiagnosticIDs::Level Level=DiagnosticIDs::Warning)
Add a diagnostic with the check's name.
bool isLanguageVersionSupported(const LangOptions &LangOpts) const override
Override this to disable registering matchers and PP callbacks if an invalid language version is bein...
void registerMatchers(ast_matchers::MatchFinder *Finder) override
Override this to register AST matchers with Finder.
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
ClangTidyChecks that register ASTMatchers should do the actual work in here.
AST_MATCHER(CXXRecordDecl, hasPublicVirtualOrProtectedNonVirtualDestructor)