clang-tools 20.0.0git
CoroutineHostileRAIICheck.cpp
Go to the documentation of this file.
1//===--- CoroutineHostileRAII.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 "../utils/OptionsUtils.h"
11#include "clang/AST/Attr.h"
12#include "clang/AST/Decl.h"
13#include "clang/AST/ExprCXX.h"
14#include "clang/AST/Stmt.h"
15#include "clang/AST/Type.h"
16#include "clang/ASTMatchers/ASTMatchFinder.h"
17#include "clang/ASTMatchers/ASTMatchers.h"
18#include "clang/ASTMatchers/ASTMatchersInternal.h"
19#include "clang/Basic/AttrKinds.h"
20#include "clang/Basic/DiagnosticIDs.h"
21
22using namespace clang::ast_matchers;
23namespace clang::tidy::misc {
24namespace {
25using clang::ast_matchers::internal::BoundNodesTreeBuilder;
26
27AST_MATCHER_P(Stmt, forEachPrevStmt, ast_matchers::internal::Matcher<Stmt>,
28 InnerMatcher) {
29 DynTypedNode P;
30 bool IsHostile = false;
31 for (const Stmt *Child = &Node; Child; Child = P.get<Stmt>()) {
32 auto Parents = Finder->getASTContext().getParents(*Child);
33 if (Parents.empty())
34 break;
35 P = *Parents.begin();
36 auto *PCS = P.get<CompoundStmt>();
37 if (!PCS)
38 continue;
39 for (const auto &Sibling : PCS->children()) {
40 // Child contains suspension. Siblings after Child do not persist across
41 // this suspension.
42 if (Sibling == Child)
43 break;
44 // In case of a match, add the bindings as a separate match. Also don't
45 // clear the bindings if a match is not found (unlike Matcher::matches).
46 BoundNodesTreeBuilder SiblingBuilder;
47 if (InnerMatcher.matches(*Sibling, Finder, &SiblingBuilder)) {
48 Builder->addMatch(SiblingBuilder);
49 IsHostile = true;
50 }
51 }
52 }
53 return IsHostile;
54}
55
56// Matches the expression awaited by the `co_await`.
57AST_MATCHER_P(CoawaitExpr, awaitable, ast_matchers::internal::Matcher<Expr>,
58 InnerMatcher) {
59 if (Expr *E = Node.getOperand())
60 return InnerMatcher.matches(*E, Finder, Builder);
61 return false;
62}
63
64auto typeWithNameIn(const std::vector<StringRef> &Names) {
65 return hasType(
66 hasCanonicalType(hasDeclaration(namedDecl(hasAnyName(Names)))));
67}
68} // namespace
69
71 ClangTidyContext *Context)
72 : ClangTidyCheck(Name, Context),
73 RAIITypesList(utils::options::parseStringList(
74 Options.get("RAIITypesList", "std::lock_guard;std::scoped_lock"))),
75 AllowedAwaitablesList(utils::options::parseStringList(
76 Options.get("AllowedAwaitablesList", ""))) {}
77
79 // A suspension happens with co_await or co_yield.
80 auto ScopedLockable = varDecl(hasType(hasCanonicalType(hasDeclaration(
81 hasAttr(attr::Kind::ScopedLockable)))))
82 .bind("scoped-lockable");
83 auto OtherRAII = varDecl(typeWithNameIn(RAIITypesList)).bind("raii");
84 auto AllowedSuspend = awaitable(typeWithNameIn(AllowedAwaitablesList));
85 Finder->addMatcher(
86 expr(anyOf(coawaitExpr(unless(AllowedSuspend)), coyieldExpr()),
87 forEachPrevStmt(
88 declStmt(forEach(varDecl(anyOf(ScopedLockable, OtherRAII))))))
89 .bind("suspension"),
90 this);
91}
92
93void CoroutineHostileRAIICheck::check(const MatchFinder::MatchResult &Result) {
94 if (const auto *VD = Result.Nodes.getNodeAs<VarDecl>("scoped-lockable"))
95 diag(VD->getLocation(),
96 "%0 holds a lock across a suspension point of coroutine and could be "
97 "unlocked by a different thread")
98 << VD;
99 if (const auto *VD = Result.Nodes.getNodeAs<VarDecl>("raii"))
100 diag(VD->getLocation(),
101 "%0 persists across a suspension point of coroutine")
102 << VD;
103 if (const auto *Suspension = Result.Nodes.getNodeAs<Expr>("suspension"))
104 diag(Suspension->getBeginLoc(), "suspension point is here",
105 DiagnosticIDs::Note);
106}
107
110 Options.store(Opts, "RAIITypesList",
112 Options.store(Opts, "SafeAwaitableList",
113 utils::options::serializeStringList(AllowedAwaitablesList));
114}
115} // namespace clang::tidy::misc
const Expr * E
llvm::SmallString< 256U > Name
CodeCompletionBuilder Builder
::clang::DynTypedNode Node
void store(ClangTidyOptions::OptionMap &Options, StringRef LocalName, StringRef Value) const
Stores an option with the check-local name LocalName with string value Value to Options.
Base class for all clang-tidy checks.
DiagnosticBuilder diag(SourceLocation Loc, StringRef Description, DiagnosticIDs::Level Level=DiagnosticIDs::Warning)
Add a diagnostic with the check's name.
Every ClangTidyCheck reports errors through a DiagnosticsEngine provided by this context.
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
ClangTidyChecks that register ASTMatchers should do the actual work in here.
CoroutineHostileRAIICheck(llvm::StringRef Name, ClangTidyContext *Context)
void storeOptions(ClangTidyOptions::OptionMap &Opts) override
Should store all options supported by this check with their current values or default values for opti...
void registerMatchers(ast_matchers::MatchFinder *Finder) override
Override this to register AST matchers with Finder.
AST_MATCHER_P(UserDefinedLiteral, hasLiteral, clang::ast_matchers::internal::Matcher< Expr >, InnerMatcher)
std::string serializeStringList(ArrayRef< StringRef > Strings)
Serialize a sequence of names that can be parsed by parseStringList.
llvm::StringMap< ClangTidyValue > OptionMap