clang-tools 23.0.0git
ThrowingStaticInitializationCheck.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 "../utils/Matchers.h"
12#include "clang/AST/ASTContext.h"
13#include "clang/ASTMatchers/ASTMatchFinder.h"
14
15using namespace clang::ast_matchers;
16
17namespace clang::tidy::bugprone {
18
20 StringRef Name, ClangTidyContext *Context)
21 : ClangTidyCheck(Name, Context),
22 AllowedTypes(
23 utils::options::parseStringList(Options.get("AllowedTypes", ""))) {}
24
27 Options.store(Opts, "AllowedTypes",
29}
30
32 // Match any static or thread_local variable declaration that has an
33 // initializer that can throw.
34 Finder->addMatcher(
35 traverse(
36 TK_AsIs,
37 varDecl(
38 anyOf(hasThreadStorageDuration(), hasStaticStorageDuration()),
39 unless(anyOf(
40 isConstexpr(), hasType(cxxRecordDecl(isLambda())),
41 hasAncestor(functionDecl()),
42 hasType(matchers::matchesAnyListedTypeName(AllowedTypes)))),
43 anyOf(hasDescendant(cxxConstructExpr(hasDeclaration(
44 cxxConstructorDecl(unless(isNoThrow())).bind("func")))),
45 hasDescendant(cxxNewExpr(hasDeclaration(
46 functionDecl(unless(isNoThrow())).bind("func")))),
47 hasDescendant(callExpr(hasDeclaration(
48 functionDecl(unless(isNoThrow())).bind("func"))))))
49 .bind("var")),
50 this);
51}
52
54 const MatchFinder::MatchResult &Result) {
55 const auto *VD = Result.Nodes.getNodeAs<VarDecl>("var");
56 const auto *Func = Result.Nodes.getNodeAs<FunctionDecl>("func");
57
58 diag(VD->getLocation(),
59 "initialization of %0 with %select{static|thread_local}1 storage "
60 "duration may throw an exception that cannot be caught")
61 << VD << (VD->getStorageDuration() == SD_Static ? 0 : 1);
62
63 const SourceLocation FuncLocation = Func->getLocation();
64 if (FuncLocation.isValid()) {
65 diag(FuncLocation,
66 "possibly throwing %select{constructor|function}0 declared here",
67 DiagnosticIDs::Note)
68 << (isa<CXXConstructorDecl>(Func) ? 0 : 1);
69 }
70}
71
72} // namespace clang::tidy::bugprone
Every ClangTidyCheck reports errors through a DiagnosticsEngine provided by this context.
void registerMatchers(ast_matchers::MatchFinder *Finder) override
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
inline ::clang::ast_matchers::internal::Matcher< QualType > matchesAnyListedTypeName(llvm::ArrayRef< StringRef > NameList, bool CanonicalTypes)
std::string serializeStringList(ArrayRef< StringRef > Strings)
Serialize a sequence of names that can be parsed by parseStringList.
llvm::StringMap< ClangTidyValue > OptionMap