xref: /llvm-project/clang-tools-extra/clang-tidy/cppcoreguidelines/InterfacesGlobalInitCheck.cpp (revision 7d2ea6c422d3f5712b7253407005e1a465a76946)
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 //===----------------------------------------------------------------------===//
8 
9 #include "InterfacesGlobalInitCheck.h"
10 #include "clang/AST/ASTContext.h"
11 #include "clang/ASTMatchers/ASTMatchFinder.h"
12 
13 using namespace clang::ast_matchers;
14 
15 namespace clang::tidy::cppcoreguidelines {
16 
registerMatchers(MatchFinder * Finder)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()));
24 
25   const auto ReferencesUndefinedGlobalVar = declRefExpr(hasDeclaration(
26       varDecl(GlobalVarDecl, unless(isDefinition())).bind("referencee")));
27 
28   Finder->addMatcher(
29       traverse(TK_AsIs, varDecl(GlobalVarDecl, isDefinition(),
30                                 hasInitializer(expr(hasDescendant(
31                                     ReferencesUndefinedGlobalVar))))
32                             .bind("var")),
33       this);
34 }
35 
check(const MatchFinder::MatchResult & Result)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;
48   }
49   diag(Var->getLocation(),
50        "initializing non-local variable with non-const expression depending on "
51        "uninitialized non-local variable %0")
52       << Referencee;
53 }
54 
55 } // namespace clang::tidy::cppcoreguidelines
56