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 
14 using namespace clang::ast_matchers;
15 
16 namespace clang {
17 namespace tidy {
18 namespace cppcoreguidelines {
19 
20 namespace {
21 AST_MATCHER(VarDecl, isLocalVarDecl) { return Node.isLocalVarDecl(); }
22 } // namespace
23 
24 InitVariablesCheck::InitVariablesCheck(StringRef Name,
25                                        ClangTidyContext *Context)
26     : ClangTidyCheck(Name, Context),
27       IncludeStyle(Options.getLocalOrGlobal("IncludeStyle",
28                                             utils::IncludeSorter::getMapping(),
29                                             utils::IncludeSorter::IS_LLVM)),
30       MathHeader(Options.get("MathHeader", "math.h")) {}
31 
32 void InitVariablesCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) {
33   Options.store(Opts, "IncludeStyle", IncludeStyle,
34                 utils::IncludeSorter::getMapping());
35   Options.store(Opts, "MathHeader", MathHeader);
36 }
37 
38 void 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               optionally(hasParent(declStmt(hasParent(
44                   cxxForRangeStmt(hasLoopVariable(varDecl().bind(BadDecl))))))),
45               unless(equalsBoundNode(BadDecl)))
46           .bind("vardecl"),
47       this);
48 }
49 
50 void InitVariablesCheck::registerPPCallbacks(const SourceManager &SM,
51                                              Preprocessor *PP,
52                                              Preprocessor *ModuleExpanderPP) {
53   IncludeInserter =
54       std::make_unique<utils::IncludeInserter>(SM, getLangOpts(), IncludeStyle);
55   PP->addPPCallbacks(IncludeInserter->CreatePPCallbacks());
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   const char *InitializationString = nullptr;
83   bool AddMathInclude = false;
84 
85   if (TypePtr->isIntegerType())
86     InitializationString = " = 0";
87   else if (TypePtr->isFloatingType()) {
88     InitializationString = " = NAN";
89     AddMathInclude = true;
90   } else if (TypePtr->isAnyPointerType()) {
91     if (getLangOpts().CPlusPlus11)
92       InitializationString = " = nullptr";
93     else
94       InitializationString = " = NULL";
95   }
96 
97   if (InitializationString) {
98     auto Diagnostic =
99         diag(MatchedDecl->getLocation(), "variable %0 is not initialized")
100         << MatchedDecl
101         << FixItHint::CreateInsertion(
102                MatchedDecl->getLocation().getLocWithOffset(
103                    MatchedDecl->getName().size()),
104                InitializationString);
105     if (AddMathInclude) {
106       Diagnostic << IncludeInserter->CreateIncludeInsertion(
107           Source.getFileID(MatchedDecl->getBeginLoc()), MathHeader, false);
108     }
109   }
110 }
111 } // namespace cppcoreguidelines
112 } // namespace tidy
113 } // namespace clang
114