[clang][modules] Don't prevent translation of FW_Private includes when explicitly...
[llvm-project.git] / clang-tools-extra / clang-tidy / bugprone / DynamicStaticInitializersCheck.cpp
blob4a467120181b4e4d0f2b0c892b3277f4949602de
1 //===--- DynamicStaticInitializersCheck.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 //===----------------------------------------------------------------------===//
9 #include "DynamicStaticInitializersCheck.h"
10 #include "../utils/FileExtensionsUtils.h"
11 #include "clang/AST/ASTContext.h"
12 #include "clang/ASTMatchers/ASTMatchFinder.h"
14 using namespace clang::ast_matchers;
16 namespace clang::tidy::bugprone {
18 AST_MATCHER(clang::VarDecl, hasConstantDeclaration) {
19 const Expr *Init = Node.getInit();
20 if (Init && !Init->isValueDependent()) {
21 if (Node.isConstexpr())
22 return true;
23 return Node.evaluateValue();
25 return false;
28 DynamicStaticInitializersCheck::DynamicStaticInitializersCheck(
29 StringRef Name, ClangTidyContext *Context)
30 : ClangTidyCheck(Name, Context) {
31 std::optional<StringRef> HeaderFileExtensionsOption =
32 Options.get("HeaderFileExtensions");
33 RawStringHeaderFileExtensions =
34 HeaderFileExtensionsOption.value_or(utils::defaultHeaderFileExtensions());
35 if (HeaderFileExtensionsOption) {
36 if (!utils::parseFileExtensions(RawStringHeaderFileExtensions,
37 HeaderFileExtensions,
38 utils::defaultFileExtensionDelimiters())) {
39 this->configurationDiag("Invalid header file extension: '%0'")
40 << RawStringHeaderFileExtensions;
42 } else
43 HeaderFileExtensions = Context->getHeaderFileExtensions();
46 void DynamicStaticInitializersCheck::storeOptions(
47 ClangTidyOptions::OptionMap &Opts) {
48 Options.store(Opts, "HeaderFileExtensions", RawStringHeaderFileExtensions);
51 void DynamicStaticInitializersCheck::registerMatchers(MatchFinder *Finder) {
52 Finder->addMatcher(
53 varDecl(hasGlobalStorage(), unless(hasConstantDeclaration())).bind("var"),
54 this);
57 void DynamicStaticInitializersCheck::check(const MatchFinder::MatchResult &Result) {
58 const auto *Var = Result.Nodes.getNodeAs<VarDecl>("var");
59 SourceLocation Loc = Var->getLocation();
60 if (!Loc.isValid() || !utils::isPresumedLocInHeaderFile(Loc, *Result.SourceManager,
61 HeaderFileExtensions))
62 return;
63 // If the initializer is a constant expression, then the compiler
64 // doesn't have to dynamically initialize it.
65 diag(Loc, "static variable %0 may be dynamically initialized in this header file")
66 << Var;
69 } // namespace clang::tidy::bugprone