1//===--- StaticObjectExceptionCheck.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 "StaticObjectExceptionCheck.h"
10#include "clang/AST/ASTContext.h"
11#include "clang/ASTMatchers/ASTMatchFinder.h"
12
13using namespace clang::ast_matchers;
14
15namespace clang::tidy::cert {
16
17void StaticObjectExceptionCheck::registerMatchers(MatchFinder *Finder) {
18 // Match any static or thread_local variable declaration that has an
19 // initializer that can throw.
20 Finder->addMatcher(
21 NodeMatch: traverse(
22 TK: TK_AsIs,
23 InnerMatcher: varDecl(
24 anyOf(hasThreadStorageDuration(), hasStaticStorageDuration()),
25 unless(anyOf(isConstexpr(), hasType(InnerMatcher: cxxRecordDecl(isLambda())),
26 hasAncestor(functionDecl()))),
27 anyOf(hasDescendant(cxxConstructExpr(hasDeclaration(
28 InnerMatcher: cxxConstructorDecl(unless(isNoThrow())).bind(ID: "func")))),
29 hasDescendant(cxxNewExpr(hasDeclaration(
30 InnerMatcher: functionDecl(unless(isNoThrow())).bind(ID: "func")))),
31 hasDescendant(callExpr(hasDeclaration(
32 InnerMatcher: functionDecl(unless(isNoThrow())).bind(ID: "func"))))))
33 .bind(ID: "var")),
34 Action: this);
35}
36
37void StaticObjectExceptionCheck::check(const MatchFinder::MatchResult &Result) {
38 const auto *VD = Result.Nodes.getNodeAs<VarDecl>(ID: "var");
39 const auto *Func = Result.Nodes.getNodeAs<FunctionDecl>(ID: "func");
40
41 diag(VD->getLocation(),
42 "initialization of %0 with %select{static|thread_local}1 storage "
43 "duration may throw an exception that cannot be caught")
44 << VD << (VD->getStorageDuration() == SD_Static ? 0 : 1);
45
46 SourceLocation FuncLocation = Func->getLocation();
47 if (FuncLocation.isValid()) {
48 diag(Loc: FuncLocation,
49 Description: "possibly throwing %select{constructor|function}0 declared here",
50 Level: DiagnosticIDs::Note)
51 << (isa<CXXConstructorDecl>(Val: Func) ? 0 : 1);
52 }
53}
54
55} // namespace clang::tidy::cert
56

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/cert/StaticObjectExceptionCheck.cpp