1 //===--- StaticObjectExceptionCheck.cpp - clang-tidy-----------------------===//
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
7 //===----------------------------------------------------------------------===//
9 #include "StaticObjectExceptionCheck.h"
10 #include "../utils/Matchers.h"
11 #include "clang/AST/ASTContext.h"
12 #include "clang/ASTMatchers/ASTMatchFinder.h"
14 using namespace clang::ast_matchers
;
16 namespace clang::tidy::cert
{
18 void StaticObjectExceptionCheck::registerMatchers(MatchFinder
*Finder
) {
19 // Match any static or thread_local variable declaration that has an
20 // initializer that can throw.
25 anyOf(hasThreadStorageDuration(), hasStaticStorageDuration()),
26 unless(anyOf(isConstexpr(), hasType(cxxRecordDecl(isLambda())),
27 hasAncestor(functionDecl()))),
28 anyOf(hasDescendant(cxxConstructExpr(hasDeclaration(
29 cxxConstructorDecl(unless(isNoThrow())).bind("func")))),
30 hasDescendant(cxxNewExpr(hasDeclaration(
31 functionDecl(unless(isNoThrow())).bind("func")))),
32 hasDescendant(callExpr(hasDeclaration(
33 functionDecl(unless(isNoThrow())).bind("func"))))))
38 void StaticObjectExceptionCheck::check(const MatchFinder::MatchResult
&Result
) {
39 const auto *VD
= Result
.Nodes
.getNodeAs
<VarDecl
>("var");
40 const auto *Func
= Result
.Nodes
.getNodeAs
<FunctionDecl
>("func");
42 diag(VD
->getLocation(),
43 "initialization of %0 with %select{static|thread_local}1 storage "
44 "duration may throw an exception that cannot be caught")
45 << VD
<< (VD
->getStorageDuration() == SD_Static
? 0 : 1);
47 SourceLocation FuncLocation
= Func
->getLocation();
48 if (FuncLocation
.isValid()) {
50 "possibly throwing %select{constructor|function}0 declared here",
52 << (isa
<CXXConstructorDecl
>(Func
) ? 0 : 1);
56 } // namespace clang::tidy::cert