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
13using namespace clang::ast_matchers;
14
15namespace clang::tidy::cppcoreguidelines {
16
17void InterfacesGlobalInitCheck::registerMatchers(MatchFinder *Finder) {
18 const auto GlobalVarDecl =
19 varDecl(hasGlobalStorage(),
20 hasDeclContext(InnerMatcher: anyOf(translationUnitDecl(), // Global scope.
21 namespaceDecl(), // Namespace scope.
22 recordDecl())), // Class scope.
23 unless(isConstexpr()));
24
25 const auto ReferencesUndefinedGlobalVar = declRefExpr(hasDeclaration(
26 InnerMatcher: varDecl(GlobalVarDecl, unless(isDefinition())).bind(ID: "referencee")));
27
28 Finder->addMatcher(
29 NodeMatch: traverse(TK: TK_AsIs, InnerMatcher: varDecl(GlobalVarDecl, isDefinition(),
30 hasInitializer(InnerMatcher: expr(hasDescendant(
31 ReferencesUndefinedGlobalVar))))
32 .bind(ID: "var")),
33 Action: this);
34}
35
36void InterfacesGlobalInitCheck::check(const MatchFinder::MatchResult &Result) {
37 const auto *const Var = Result.Nodes.getNodeAs<VarDecl>(ID: "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>(ID: "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 LHS: ReferenceeDef->getLocation(), RHS: 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

source code of clang-tools-extra/clang-tidy/cppcoreguidelines/InterfacesGlobalInitCheck.cpp