clang-tools  10.0.0svn
UnusedParametersCheck.cpp
Go to the documentation of this file.
1 //===--- UnusedParametersCheck.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/AST/RecursiveASTVisitor.h"
12 #include "clang/ASTMatchers/ASTMatchFinder.h"
13 #include "clang/Lex/Lexer.h"
14 #include "llvm/ADT/STLExtras.h"
15 #include <unordered_set>
16 
17 using namespace clang::ast_matchers;
18 
19 namespace clang {
20 namespace tidy {
21 namespace misc {
22 
23 namespace {
24 bool isOverrideMethod(const FunctionDecl *Function) {
25  if (const auto *MD = dyn_cast<CXXMethodDecl>(Function))
26  return MD->size_overridden_methods() > 0 || MD->hasAttr<OverrideAttr>();
27  return false;
28 }
29 } // namespace
30 
31 void UnusedParametersCheck::registerMatchers(MatchFinder *Finder) {
32  Finder->addMatcher(
33  functionDecl(isDefinition(), hasBody(stmt()), hasAnyParameter(decl()))
34  .bind("function"),
35  this);
36 }
37 
38 template <typename T>
39 static CharSourceRange removeNode(const MatchFinder::MatchResult &Result,
40  const T *PrevNode, const T *Node,
41  const T *NextNode) {
42  if (NextNode)
43  return CharSourceRange::getCharRange(Node->getBeginLoc(),
44  NextNode->getBeginLoc());
45 
46  if (PrevNode)
48  Lexer::getLocForEndOfToken(PrevNode->getEndLoc(), 0,
49  *Result.SourceManager,
50  Result.Context->getLangOpts()),
51  Node->getEndLoc());
52 
53  return CharSourceRange::getTokenRange(Node->getSourceRange());
54 }
55 
56 static FixItHint removeParameter(const MatchFinder::MatchResult &Result,
57  const FunctionDecl *Function, unsigned Index) {
58  return FixItHint::CreateRemoval(removeNode(
59  Result, Index > 0 ? Function->getParamDecl(Index - 1) : nullptr,
60  Function->getParamDecl(Index),
61  Index + 1 < Function->getNumParams() ? Function->getParamDecl(Index + 1)
62  : nullptr));
63 }
64 
65 static FixItHint removeArgument(const MatchFinder::MatchResult &Result,
66  const CallExpr *Call, unsigned Index) {
67  return FixItHint::CreateRemoval(removeNode(
68  Result, Index > 0 ? Call->getArg(Index - 1) : nullptr,
69  Call->getArg(Index),
70  Index + 1 < Call->getNumArgs() ? Call->getArg(Index + 1) : nullptr));
71 }
72 
74  : public RecursiveASTVisitor<IndexerVisitor> {
75 public:
76  IndexerVisitor(ASTContext &Ctx) { TraverseAST(Ctx); }
77 
78  const std::unordered_set<const CallExpr *> &
79  getFnCalls(const FunctionDecl *Fn) {
80  return Index[Fn->getCanonicalDecl()].Calls;
81  }
82 
83  const std::unordered_set<const DeclRefExpr *> &
84  getOtherRefs(const FunctionDecl *Fn) {
85  return Index[Fn->getCanonicalDecl()].OtherRefs;
86  }
87 
88  bool shouldTraversePostOrder() const { return true; }
89 
90  bool WalkUpFromDeclRefExpr(DeclRefExpr *DeclRef) {
91  if (const auto *Fn = dyn_cast<FunctionDecl>(DeclRef->getDecl())) {
92  Fn = Fn->getCanonicalDecl();
93  Index[Fn].OtherRefs.insert(DeclRef);
94  }
95  return true;
96  }
97 
98  bool WalkUpFromCallExpr(CallExpr *Call) {
99  if (const auto *Fn =
100  dyn_cast_or_null<FunctionDecl>(Call->getCalleeDecl())) {
101  Fn = Fn->getCanonicalDecl();
102  if (const auto *Ref =
103  dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit())) {
104  Index[Fn].OtherRefs.erase(Ref);
105  }
106  Index[Fn].Calls.insert(Call);
107  }
108  return true;
109  }
110 
111 private:
112  struct IndexEntry {
113  std::unordered_set<const CallExpr *> Calls;
114  std::unordered_set<const DeclRefExpr *> OtherRefs;
115  };
116 
117  std::unordered_map<const FunctionDecl *, IndexEntry> Index;
118 };
119 
120 UnusedParametersCheck::~UnusedParametersCheck() = default;
121 
122 UnusedParametersCheck::UnusedParametersCheck(StringRef Name,
123  ClangTidyContext *Context)
124  : ClangTidyCheck(Name, Context),
125  StrictMode(Options.getLocalOrGlobal("StrictMode", 0) != 0) {}
126 
128  Options.store(Opts, "StrictMode", StrictMode);
129 }
130 
131 void UnusedParametersCheck::warnOnUnusedParameter(
132  const MatchFinder::MatchResult &Result, const FunctionDecl *Function,
133  unsigned ParamIndex) {
134  const auto *Param = Function->getParamDecl(ParamIndex);
135  auto MyDiag = diag(Param->getLocation(), "parameter %0 is unused") << Param;
136 
137  if (!Indexer) {
138  Indexer = std::make_unique<IndexerVisitor>(*Result.Context);
139  }
140 
141  // Cannot remove parameter for non-local functions.
142  if (Function->isExternallyVisible() ||
143  !Result.SourceManager->isInMainFile(Function->getLocation()) ||
144  !Indexer->getOtherRefs(Function).empty() || isOverrideMethod(Function)) {
145 
146  // It is illegal to omit parameter name here in C code, so early-out.
147  if (!Result.Context->getLangOpts().CPlusPlus)
148  return;
149 
150  SourceRange RemovalRange(Param->getLocation());
151  // Note: We always add a space before the '/*' to not accidentally create
152  // a '*/*' for pointer types, which doesn't start a comment. clang-format
153  // will clean this up afterwards.
154  MyDiag << FixItHint::CreateReplacement(
155  RemovalRange, (Twine(" /*") + Param->getName() + "*/").str());
156  return;
157  }
158 
159  // Fix all redeclarations.
160  for (const FunctionDecl *FD : Function->redecls())
161  if (FD->param_size())
162  MyDiag << removeParameter(Result, FD, ParamIndex);
163 
164  // Fix all call sites.
165  for (const CallExpr *Call : Indexer->getFnCalls(Function))
166  if (ParamIndex < Call->getNumArgs()) // See PR38055 for example.
167  MyDiag << removeArgument(Result, Call, ParamIndex);
168 }
169 
170 void UnusedParametersCheck::check(const MatchFinder::MatchResult &Result) {
171  const auto *Function = Result.Nodes.getNodeAs<FunctionDecl>("function");
172  if (!Function->hasWrittenPrototype() || Function->isTemplateInstantiation())
173  return;
174  if (const auto *Method = dyn_cast<CXXMethodDecl>(Function))
175  if (Method->isLambdaStaticInvoker())
176  return;
177  for (unsigned i = 0, e = Function->getNumParams(); i != e; ++i) {
178  const auto *Param = Function->getParamDecl(i);
179  if (Param->isUsed() || Param->isReferenced() || !Param->getDeclName() ||
180  Param->hasAttr<UnusedAttr>())
181  continue;
182 
183  // In non-strict mode ignore function definitions with empty bodies
184  // (constructor initializer counts for non-empty body).
185  if (StrictMode ||
186  (Function->getBody()->child_begin() !=
187  Function->getBody()->child_end()) ||
188  (isa<CXXConstructorDecl>(Function) &&
189  cast<CXXConstructorDecl>(Function)->getNumCtorInitializers() > 0))
190  warnOnUnusedParameter(Result, Function, i);
191  }
192 }
193 
194 } // namespace misc
195 } // namespace tidy
196 } // namespace clang
static bool isOverrideMethod(const CXXMethodDecl *MD)
Finds out if the given method overrides some method.
static FixItHint removeArgument(const MatchFinder::MatchResult &Result, const CallExpr *Call, unsigned Index)
void storeOptions(ClangTidyOptions::OptionMap &Opts) override
Should store all options supported by this check with their current values or default values for opti...
Base class for all clang-tidy checks.
const std::unordered_set< const CallExpr * > & getFnCalls(const FunctionDecl *Fn)
Context Ctx
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.
static constexpr llvm::StringLiteral Name
std::map< std::string, std::string > OptionMap
llvm::Optional< Range > getTokenRange(const SourceManager &SM, const LangOptions &LangOpts, SourceLocation TokLoc)
Returns the taken range at TokLoc.
Definition: SourceCode.cpp:229
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
static GeneratorRegistry::Add< MDGenerator > MD(MDGenerator::Format, "Generator for MD output.")
const std::unordered_set< const DeclRefExpr * > & getOtherRefs(const FunctionDecl *Fn)
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
ClangTidyChecks that register ASTMatchers should do the actual work in here.
Every ClangTidyCheck reports errors through a DiagnosticsEngine provided by this context.
static CharSourceRange removeNode(const MatchFinder::MatchResult &Result, const T *PrevNode, const T *Node, const T *NextNode)
const DeclRefExpr * DeclRef
DiagnosticBuilder diag(SourceLocation Loc, StringRef Description, DiagnosticIDs::Level Level=DiagnosticIDs::Warning)
Add a diagnostic with the check&#39;s name.
static FixItHint removeParameter(const MatchFinder::MatchResult &Result, const FunctionDecl *Function, unsigned Index)
const SymbolIndex * Index
Definition: Dexp.cpp:84