clang-tools 19.0.0git
InitVariablesCheck.cpp
Go to the documentation of this file.
1//===--- InitVariablesCheck.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
11#include "clang/AST/ASTContext.h"
12#include "clang/ASTMatchers/ASTMatchFinder.h"
13#include "clang/Lex/PPCallbacks.h"
14#include "clang/Lex/Preprocessor.h"
15#include <optional>
16
17using namespace clang::ast_matchers;
18
20
21namespace {
22AST_MATCHER(VarDecl, isLocalVarDecl) { return Node.isLocalVarDecl(); }
23} // namespace
24
26 ClangTidyContext *Context)
27 : ClangTidyCheck(Name, Context),
28 IncludeInserter(Options.getLocalOrGlobal("IncludeStyle",
29 utils::IncludeSorter::IS_LLVM),
30 areDiagsSelfContained()),
31 MathHeader(Options.get("MathHeader", "<math.h>")) {}
32
34 Options.store(Opts, "IncludeStyle", IncludeInserter.getStyle());
35 Options.store(Opts, "MathHeader", MathHeader);
36}
37
38void InitVariablesCheck::registerMatchers(MatchFinder *Finder) {
39 std::string BadDecl = "badDecl";
40 Finder->addMatcher(
41 varDecl(unless(hasInitializer(anything())), unless(isInstantiated()),
42 isLocalVarDecl(), unless(isStaticLocal()), isDefinition(),
43 unless(hasParent(cxxCatchStmt())),
44 optionally(hasParent(declStmt(hasParent(
45 cxxForRangeStmt(hasLoopVariable(varDecl().bind(BadDecl))))))),
46 unless(equalsBoundNode(BadDecl)))
47 .bind("vardecl"),
48 this);
49}
50
51void InitVariablesCheck::registerPPCallbacks(const SourceManager &SM,
52 Preprocessor *PP,
53 Preprocessor *ModuleExpanderPP) {
54 IncludeInserter.registerPreprocessor(PP);
55}
56
57void InitVariablesCheck::check(const MatchFinder::MatchResult &Result) {
58 const auto *MatchedDecl = Result.Nodes.getNodeAs<VarDecl>("vardecl");
59 const ASTContext &Context = *Result.Context;
60 const SourceManager &Source = Context.getSourceManager();
61
62 // Clang diagnostic error may cause the variable to be an invalid int vardecl
63 if (MatchedDecl->isInvalidDecl())
64 return;
65
66 // We want to warn about cases where the type name
67 // comes from a macro like this:
68 //
69 // TYPENAME_FROM_MACRO var;
70 //
71 // but not if the entire declaration comes from
72 // one:
73 //
74 // DEFINE_SOME_VARIABLE();
75 //
76 // or if the definition comes from a macro like SWAP
77 // that uses an internal temporary variable.
78 //
79 // Thus check that the variable name does
80 // not come from a macro expansion.
81 if (MatchedDecl->getEndLoc().isMacroID())
82 return;
83
84 QualType TypePtr = MatchedDecl->getType();
85 std::optional<const char *> InitializationString;
86 bool AddMathInclude = false;
87
88 if (TypePtr->isEnumeralType())
89 InitializationString = nullptr;
90 else if (TypePtr->isBooleanType())
91 InitializationString = " = false";
92 else if (TypePtr->isIntegerType())
93 InitializationString = " = 0";
94 else if (TypePtr->isFloatingType()) {
95 InitializationString = " = NAN";
96 AddMathInclude = true;
97 } else if (TypePtr->isAnyPointerType()) {
98 if (getLangOpts().CPlusPlus11)
99 InitializationString = " = nullptr";
100 else
101 InitializationString = " = NULL";
102 }
103
104 if (InitializationString) {
105 auto Diagnostic =
106 diag(MatchedDecl->getLocation(), "variable %0 is not initialized")
107 << MatchedDecl;
108 if (*InitializationString != nullptr)
109 Diagnostic << FixItHint::CreateInsertion(
110 MatchedDecl->getLocation().getLocWithOffset(
111 MatchedDecl->getName().size()),
112 *InitializationString);
113 if (AddMathInclude) {
114 Diagnostic << IncludeInserter.createIncludeInsertion(
115 Source.getFileID(MatchedDecl->getBeginLoc()), MathHeader);
116 }
117 }
118}
119} // namespace clang::tidy::cppcoreguidelines
llvm::SmallString< 256U > Name
DiagnosticCallback Diagnostic
::clang::DynTypedNode Node
void store(ClangTidyOptions::OptionMap &Options, StringRef LocalName, StringRef Value) const
Stores an option with the check-local name LocalName with string value Value to Options.
Base class for all clang-tidy checks.
DiagnosticBuilder diag(SourceLocation Loc, StringRef Description, DiagnosticIDs::Level Level=DiagnosticIDs::Warning)
Add a diagnostic with the check's name.
const LangOptions & getLangOpts() const
Returns the language options from the context.
Every ClangTidyCheck reports errors through a DiagnosticsEngine provided by this context.
void registerMatchers(ast_matchers::MatchFinder *Finder) override
Override this to register AST matchers with Finder.
void storeOptions(ClangTidyOptions::OptionMap &Opts) override
Should store all options supported by this check with their current values or default values for opti...
void registerPPCallbacks(const SourceManager &SM, Preprocessor *PP, Preprocessor *ModuleExpanderPP) override
Override this to register PPCallbacks in the preprocessor.
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
ClangTidyChecks that register ASTMatchers should do the actual work in here.
InitVariablesCheck(StringRef Name, ClangTidyContext *Context)
void registerPreprocessor(Preprocessor *PP)
Registers this with the Preprocessor PP, must be called before this class is used.
std::optional< FixItHint > createIncludeInsertion(FileID FileID, llvm::StringRef Header)
Creates a Header inclusion directive fixit in the File FileID.
IncludeSorter::IncludeStyle getStyle() const
AST_MATCHER(CXXRecordDecl, hasPublicVirtualOrProtectedNonVirtualDestructor)
llvm::StringMap< ClangTidyValue > OptionMap