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