clang-tools 20.0.0git
InterfacesGlobalInitCheck.cpp
Go to the documentation of this file.
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
10#include "clang/AST/ASTContext.h"
11#include "clang/ASTMatchers/ASTMatchFinder.h"
12
13using namespace clang::ast_matchers;
14
16
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
36void 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
DiagnosticBuilder diag(SourceLocation Loc, StringRef Description, DiagnosticIDs::Level Level=DiagnosticIDs::Warning)
Add a diagnostic with the check's name.
void registerMatchers(ast_matchers::MatchFinder *Finder) override
Override this to register AST matchers with Finder.
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
ClangTidyChecks that register ASTMatchers should do the actual work in here.