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       IncludeStyle(Options.getLocalOrGlobal("IncludeStyle",
30                                             utils::IncludeSorter::getMapping(),
31                                             utils::IncludeSorter::IS_LLVM)),
32       MathHeader(Options.get("MathHeader", "math.h")) {}
33 
34 void InitVariablesCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) {
35   Options.store(Opts, "IncludeStyle", IncludeStyle,
36                 utils::IncludeSorter::getMapping());
37   Options.store(Opts, "MathHeader", MathHeader);
38 }
39 
40 void InitVariablesCheck::registerMatchers(MatchFinder *Finder) {
41   std::string BadDecl = "badDecl";
42   Finder->addMatcher(
43       varDecl(unless(hasInitializer(anything())), unless(isInstantiated()),
44               isLocalVarDecl(), unless(isStaticLocal()), isDefinition(),
45               unless(hasParent(cxxCatchStmt())),
46               optionally(hasParent(declStmt(hasParent(
47                   cxxForRangeStmt(hasLoopVariable(varDecl().bind(BadDecl))))))),
48               unless(equalsBoundNode(BadDecl)))
49           .bind("vardecl"),
50       this);
51 }
52 
53 void InitVariablesCheck::registerPPCallbacks(const SourceManager &SM,
54                                              Preprocessor *PP,
55                                              Preprocessor *ModuleExpanderPP) {
56   IncludeInserter =
57       std::make_unique<utils::IncludeInserter>(SM, getLangOpts(), IncludeStyle);
58   PP->addPPCallbacks(IncludeInserter->CreatePPCallbacks());
59 }
60 
61 void InitVariablesCheck::check(const MatchFinder::MatchResult &Result) {
62   const auto *MatchedDecl = Result.Nodes.getNodeAs<VarDecl>("vardecl");
63   const ASTContext &Context = *Result.Context;
64   const SourceManager &Source = Context.getSourceManager();
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   const char *InitializationString = nullptr;
86   bool AddMathInclude = false;
87 
88   if (TypePtr->isIntegerType())
89     InitializationString = " = 0";
90   else if (TypePtr->isFloatingType()) {
91     InitializationString = " = NAN";
92     AddMathInclude = true;
93   } else if (TypePtr->isAnyPointerType()) {
94     if (getLangOpts().CPlusPlus11)
95       InitializationString = " = nullptr";
96     else
97       InitializationString = " = NULL";
98   }
99 
100   if (InitializationString) {
101     auto Diagnostic =
102         diag(MatchedDecl->getLocation(), "variable %0 is not initialized")
103         << MatchedDecl
104         << FixItHint::CreateInsertion(
105                MatchedDecl->getLocation().getLocWithOffset(
106                    MatchedDecl->getName().size()),
107                InitializationString);
108     if (AddMathInclude) {
109       Diagnostic << IncludeInserter->CreateIncludeInsertion(
110           Source.getFileID(MatchedDecl->getBeginLoc()), MathHeader, false);
111     }
112   }
113 }
114 } // namespace cppcoreguidelines
115 } // namespace tidy
116 } // namespace clang
117