[clang][modules] Don't prevent translation of FW_Private includes when explicitly...
[llvm-project.git] / clang-tools-extra / clang-tidy / cppcoreguidelines / InterfacesGlobalInitCheck.cpp
blob18d297f4161bfb3852ef642704f4079ea1977eeb
1 //===--- InterfacesGlobalInitCheck.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 "InterfacesGlobalInitCheck.h"
10 #include "clang/AST/ASTContext.h"
11 #include "clang/ASTMatchers/ASTMatchFinder.h"
13 using namespace clang::ast_matchers;
15 namespace clang::tidy::cppcoreguidelines {
17 void InterfacesGlobalInitCheck::registerMatchers(MatchFinder *Finder) {
18 const auto GlobalVarDecl =
19 varDecl(hasGlobalStorage(),
20 hasDeclContext(anyOf(translationUnitDecl(), // Global scope.
21 namespaceDecl(), // Namespace scope.
22 recordDecl())), // Class scope.
23 unless(isConstexpr()));
25 const auto ReferencesUndefinedGlobalVar = declRefExpr(hasDeclaration(
26 varDecl(GlobalVarDecl, unless(isDefinition())).bind("referencee")));
28 Finder->addMatcher(
29 traverse(TK_AsIs, varDecl(GlobalVarDecl, isDefinition(),
30 hasInitializer(expr(hasDescendant(
31 ReferencesUndefinedGlobalVar))))
32 .bind("var")),
33 this);
36 void InterfacesGlobalInitCheck::check(const MatchFinder::MatchResult &Result) {
37 const auto *const Var = Result.Nodes.getNodeAs<VarDecl>("var");
38 // For now assume that people who write macros know what they're doing.
39 if (Var->getLocation().isMacroID())
40 return;
41 const auto *const Referencee = Result.Nodes.getNodeAs<VarDecl>("referencee");
42 // If the variable has been defined, we're good.
43 const auto *const ReferenceeDef = Referencee->getDefinition();
44 if (ReferenceeDef != nullptr &&
45 Result.SourceManager->isBeforeInTranslationUnit(
46 ReferenceeDef->getLocation(), Var->getLocation())) {
47 return;
49 diag(Var->getLocation(),
50 "initializing non-local variable with non-const expression depending on "
51 "uninitialized non-local variable %0")
52 << Referencee;
55 } // namespace clang::tidy::cppcoreguidelines