clang-tools 8.0.0

StaticallyConstructedObjectsCheck.cpp
Go to the documentation of this file.
1 //===--- StaticallyConstructedObjectsCheck.cpp - clang-tidy----------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #include "StaticallyConstructedObjectsCheck.h"
11
12 using namespace clang::ast_matchers;
13
14 namespace clang {
15 namespace tidy {
16 namespace fuchsia {
17
18 namespace {
19 AST_MATCHER(Expr, isConstantInitializer) {
20 return Node.isConstantInitializer(Finder->getASTContext(), false);
21 }
22
23 AST_MATCHER(VarDecl, isGlobalStatic) {
24 return Node.getStorageDuration() == SD_Static && !Node.isLocalVarDecl();
25 }
26 } // namespace
27
28 void StaticallyConstructedObjectsCheck::registerMatchers(MatchFinder *Finder) {
29 // Constructing global, non-trivial objects with static storage is
30 // disallowed, unless the object is statically initialized with a constexpr
31 // constructor or has no explicit constructor.
32
33 // Constexpr requires C++11 or later.
34 if (!getLangOpts().CPlusPlus11)
35 return;
36
37 Finder->addMatcher(varDecl(
38 // Match global, statically stored objects...
39 isGlobalStatic(),
40 // ... that have C++ constructors...
41 hasDescendant(cxxConstructExpr(unless(allOf(
42 // ... unless it is constexpr ...
43 hasDeclaration(cxxConstructorDecl(isConstexpr())),
44 // ... and is statically initialized.
45 isConstantInitializer())))))
46 .bind("decl"),
47 this);
48 }
49
50 void StaticallyConstructedObjectsCheck::check(
51 const MatchFinder::MatchResult &Result) {
52 if (const auto *D = Result.Nodes.getNodeAs<VarDecl>("decl"))
53 diag(D->getBeginLoc(), "static objects are disallowed; if possible, use a "
54 "constexpr constructor instead");
55 }
56
57 } // namespace fuchsia
58 } // namespace tidy
59 } // namespace clang
clang::ast_matchers
Definition: AbseilMatcher.h:15
clang::tidy::matchers::AST_MATCHER
AST_MATCHER(BinaryOperator, isAssignmentOperator)
Definition: Matchers.h:20
D
const Decl * D
Definition: XRefs.cpp:79
Result
llvm::Optional< llvm::Expected< tooling::AtomicChanges > > Result
Definition: ClangdServer.cpp:60
clang
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
Definition: ChangeNamespace.cpp:18
StaticallyConstructedObjectsCheck.h