clang-tools  7.0.0
UseAutoCheck.cpp
Go to the documentation of this file.
1 //===--- UseAutoCheck.cpp - clang-tidy-------------------------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "UseAutoCheck.h"
11 #include "clang/AST/ASTContext.h"
12 #include "clang/ASTMatchers/ASTMatchFinder.h"
13 #include "clang/ASTMatchers/ASTMatchers.h"
14 #include "clang/Basic/CharInfo.h"
15 #include "clang/Tooling/FixIt.h"
16 
17 using namespace clang;
18 using namespace clang::ast_matchers;
19 using namespace clang::ast_matchers::internal;
20 
21 namespace clang {
22 namespace tidy {
23 namespace modernize {
24 namespace {
25 
26 const char IteratorDeclStmtId[] = "iterator_decl";
27 const char DeclWithNewId[] = "decl_new";
28 const char DeclWithCastId[] = "decl_cast";
29 const char DeclWithTemplateCastId[] = "decl_template";
30 
31 size_t GetTypeNameLength(bool RemoveStars, StringRef Text) {
32  enum CharType { Space, Alpha, Punctuation };
33  CharType LastChar = Space, BeforeSpace = Punctuation;
34  size_t NumChars = 0;
35  int TemplateTypenameCntr = 0;
36  for (const unsigned char C : Text) {
37  if (C == '<')
38  ++TemplateTypenameCntr;
39  else if (C == '>')
40  --TemplateTypenameCntr;
41  const CharType NextChar =
42  isAlphanumeric(C)
43  ? Alpha
44  : (isWhitespace(C) ||
45  (!RemoveStars && TemplateTypenameCntr == 0 && C == '*'))
46  ? Space
47  : Punctuation;
48  if (NextChar != Space) {
49  ++NumChars; // Count the non-space character.
50  if (LastChar == Space && NextChar == Alpha && BeforeSpace == Alpha)
51  ++NumChars; // Count a single space character between two words.
52  BeforeSpace = NextChar;
53  }
54  LastChar = NextChar;
55  }
56  return NumChars;
57 }
58 
59 /// \brief Matches variable declarations that have explicit initializers that
60 /// are not initializer lists.
61 ///
62 /// Given
63 /// \code
64 /// iterator I = Container.begin();
65 /// MyType A(42);
66 /// MyType B{2};
67 /// MyType C;
68 /// \endcode
69 ///
70 /// varDecl(hasWrittenNonListInitializer()) maches \c I and \c A but not \c B
71 /// or \c C.
72 AST_MATCHER(VarDecl, hasWrittenNonListInitializer) {
73  const Expr *Init = Node.getAnyInitializer();
74  if (!Init)
75  return false;
76 
77  Init = Init->IgnoreImplicit();
78 
79  // The following test is based on DeclPrinter::VisitVarDecl() to find if an
80  // initializer is implicit or not.
81  if (const auto *Construct = dyn_cast<CXXConstructExpr>(Init)) {
82  return !Construct->isListInitialization() && Construct->getNumArgs() > 0 &&
83  !Construct->getArg(0)->isDefaultArgument();
84  }
85  return Node.getInitStyle() != VarDecl::ListInit;
86 }
87 
88 /// \brief Matches QualTypes that are type sugar for QualTypes that match \c
89 /// SugarMatcher.
90 ///
91 /// Given
92 /// \code
93 /// class C {};
94 /// typedef C my_type;
95 /// typedef my_type my_other_type;
96 /// \endcode
97 ///
98 /// qualType(isSugarFor(recordType(hasDeclaration(namedDecl(hasName("C"))))))
99 /// matches \c my_type and \c my_other_type.
100 AST_MATCHER_P(QualType, isSugarFor, Matcher<QualType>, SugarMatcher) {
101  QualType QT = Node;
102  while (true) {
103  if (SugarMatcher.matches(QT, Finder, Builder))
104  return true;
105 
106  QualType NewQT = QT.getSingleStepDesugaredType(Finder->getASTContext());
107  if (NewQT == QT)
108  return false;
109  QT = NewQT;
110  }
111 }
112 
113 /// \brief Matches named declarations that have one of the standard iterator
114 /// names: iterator, reverse_iterator, const_iterator, const_reverse_iterator.
115 ///
116 /// Given
117 /// \code
118 /// iterator I;
119 /// const_iterator CI;
120 /// \endcode
121 ///
122 /// namedDecl(hasStdIteratorName()) matches \c I and \c CI.
123 AST_MATCHER(NamedDecl, hasStdIteratorName) {
124  static const char *const IteratorNames[] = {"iterator", "reverse_iterator",
125  "const_iterator",
126  "const_reverse_iterator"};
127 
128  for (const char *Name : IteratorNames) {
129  if (hasName(Name).matches(Node, Finder, Builder))
130  return true;
131  }
132  return false;
133 }
134 
135 /// \brief Matches named declarations that have one of the standard container
136 /// names.
137 ///
138 /// Given
139 /// \code
140 /// class vector {};
141 /// class forward_list {};
142 /// class my_ver{};
143 /// \endcode
144 ///
145 /// recordDecl(hasStdContainerName()) matches \c vector and \c forward_list
146 /// but not \c my_vec.
147 AST_MATCHER(NamedDecl, hasStdContainerName) {
148  static const char *const ContainerNames[] = {
149  "array", "deque",
150  "forward_list", "list",
151  "vector",
152 
153  "map", "multimap",
154  "set", "multiset",
155 
156  "unordered_map", "unordered_multimap",
157  "unordered_set", "unordered_multiset",
158 
159  "queue", "priority_queue",
160  "stack"};
161 
162  for (const char *Name : ContainerNames) {
163  if (hasName(Name).matches(Node, Finder, Builder))
164  return true;
165  }
166  return false;
167 }
168 
169 /// Matches declarations whose declaration context is the C++ standard library
170 /// namespace std.
171 ///
172 /// Note that inline namespaces are silently ignored during the lookup since
173 /// both libstdc++ and libc++ are known to use them for versioning purposes.
174 ///
175 /// Given:
176 /// \code
177 /// namespace ns {
178 /// struct my_type {};
179 /// using namespace std;
180 /// }
181 ///
182 /// using std::vector;
183 /// using ns:my_type;
184 /// using ns::list;
185 /// \code
186 ///
187 /// usingDecl(hasAnyUsingShadowDecl(hasTargetDecl(isFromStdNamespace())))
188 /// matches "using std::vector" and "using ns::list".
189 AST_MATCHER(Decl, isFromStdNamespace) {
190  const DeclContext *D = Node.getDeclContext();
191 
192  while (D->isInlineNamespace())
193  D = D->getParent();
194 
195  if (!D->isNamespace() || !D->getParent()->isTranslationUnit())
196  return false;
197 
198  const IdentifierInfo *Info = cast<NamespaceDecl>(D)->getIdentifier();
199 
200  return (Info && Info->isStr("std"));
201 }
202 
203 /// Matches declaration reference or member expressions with explicit template
204 /// arguments.
205 AST_POLYMORPHIC_MATCHER(hasExplicitTemplateArgs,
206  AST_POLYMORPHIC_SUPPORTED_TYPES(DeclRefExpr,
207  MemberExpr)) {
208  return Node.hasExplicitTemplateArgs();
209 }
210 
211 /// \brief Returns a DeclarationMatcher that matches standard iterators nested
212 /// inside records with a standard container name.
213 DeclarationMatcher standardIterator() {
214  return allOf(
215  namedDecl(hasStdIteratorName()),
216  hasDeclContext(recordDecl(hasStdContainerName(), isFromStdNamespace())));
217 }
218 
219 /// \brief Returns a TypeMatcher that matches typedefs for standard iterators
220 /// inside records with a standard container name.
221 TypeMatcher typedefIterator() {
222  return typedefType(hasDeclaration(standardIterator()));
223 }
224 
225 /// \brief Returns a TypeMatcher that matches records named for standard
226 /// iterators nested inside records named for standard containers.
227 TypeMatcher nestedIterator() {
228  return recordType(hasDeclaration(standardIterator()));
229 }
230 
231 /// \brief Returns a TypeMatcher that matches types declared with using
232 /// declarations and which name standard iterators for standard containers.
233 TypeMatcher iteratorFromUsingDeclaration() {
234  auto HasIteratorDecl = hasDeclaration(namedDecl(hasStdIteratorName()));
235  // Types resulting from using declarations are represented by elaboratedType.
236  return elaboratedType(allOf(
237  // Unwrap the nested name specifier to test for one of the standard
238  // containers.
239  hasQualifier(specifiesType(templateSpecializationType(hasDeclaration(
240  namedDecl(hasStdContainerName(), isFromStdNamespace()))))),
241  // the named type is what comes after the final '::' in the type. It
242  // should name one of the standard iterator names.
243  namesType(
244  anyOf(typedefType(HasIteratorDecl), recordType(HasIteratorDecl)))));
245 }
246 
247 /// \brief This matcher returns declaration statements that contain variable
248 /// declarations with written non-list initializer for standard iterators.
249 StatementMatcher makeIteratorDeclMatcher() {
250  return declStmt(unless(has(
251  varDecl(anyOf(unless(hasWrittenNonListInitializer()),
252  unless(hasType(isSugarFor(anyOf(
253  typedefIterator(), nestedIterator(),
254  iteratorFromUsingDeclaration())))))))))
255  .bind(IteratorDeclStmtId);
256 }
257 
258 StatementMatcher makeDeclWithNewMatcher() {
259  return declStmt(
260  unless(has(varDecl(anyOf(
261  unless(hasInitializer(ignoringParenImpCasts(cxxNewExpr()))),
262  // FIXME: TypeLoc information is not reliable where CV
263  // qualifiers are concerned so these types can't be
264  // handled for now.
265  hasType(pointerType(
266  pointee(hasCanonicalType(hasLocalQualifiers())))),
267 
268  // FIXME: Handle function pointers. For now we ignore them
269  // because the replacement replaces the entire type
270  // specifier source range which includes the identifier.
271  hasType(pointsTo(
272  pointsTo(parenType(innerType(functionType()))))))))))
273  .bind(DeclWithNewId);
274 }
275 
276 StatementMatcher makeDeclWithCastMatcher() {
277  return declStmt(
278  unless(has(varDecl(unless(hasInitializer(explicitCastExpr()))))))
279  .bind(DeclWithCastId);
280 }
281 
282 StatementMatcher makeDeclWithTemplateCastMatcher() {
283  auto ST =
284  substTemplateTypeParmType(hasReplacementType(equalsBoundNode("arg")));
285 
286  auto ExplicitCall =
287  anyOf(has(memberExpr(hasExplicitTemplateArgs())),
288  has(ignoringImpCasts(declRefExpr(hasExplicitTemplateArgs()))));
289 
290  auto TemplateArg =
291  hasTemplateArgument(0, refersToType(qualType().bind("arg")));
292 
293  auto TemplateCall = callExpr(
294  ExplicitCall,
295  callee(functionDecl(TemplateArg,
296  returns(anyOf(ST, pointsTo(ST), references(ST))))));
297 
298  return declStmt(unless(has(varDecl(
299  unless(hasInitializer(ignoringImplicit(TemplateCall)))))))
300  .bind(DeclWithTemplateCastId);
301 }
302 
303 StatementMatcher makeCombinedMatcher() {
304  return declStmt(
305  // At least one varDecl should be a child of the declStmt to ensure
306  // it's a declaration list and avoid matching other declarations,
307  // e.g. using directives.
308  has(varDecl(unless(isImplicit()))),
309  // Skip declarations that are already using auto.
310  unless(has(varDecl(anyOf(hasType(autoType()),
311  hasType(qualType(hasDescendant(autoType()))))))),
312  anyOf(makeIteratorDeclMatcher(), makeDeclWithNewMatcher(),
313  makeDeclWithCastMatcher(), makeDeclWithTemplateCastMatcher()));
314 }
315 
316 } // namespace
317 
318 UseAutoCheck::UseAutoCheck(StringRef Name, ClangTidyContext *Context)
319  : ClangTidyCheck(Name, Context),
320  MinTypeNameLength(Options.get("MinTypeNameLength", 5)),
321  RemoveStars(Options.get("RemoveStars", 0)) {}
322 
323 void UseAutoCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) {
324  Options.store(Opts, "MinTypeNameLength", MinTypeNameLength);
325  Options.store(Opts, "RemoveStars", RemoveStars ? 1 : 0);
326 }
327 
328 void UseAutoCheck::registerMatchers(MatchFinder *Finder) {
329  // Only register the matchers for C++; the functionality currently does not
330  // provide any benefit to other languages, despite being benign.
331  if (getLangOpts().CPlusPlus) {
332  Finder->addMatcher(makeCombinedMatcher(), this);
333  }
334 }
335 
336 void UseAutoCheck::replaceIterators(const DeclStmt *D, ASTContext *Context) {
337  for (const auto *Dec : D->decls()) {
338  const auto *V = cast<VarDecl>(Dec);
339  const Expr *ExprInit = V->getInit();
340 
341  // Skip expressions with cleanups from the intializer expression.
342  if (const auto *E = dyn_cast<ExprWithCleanups>(ExprInit))
343  ExprInit = E->getSubExpr();
344 
345  const auto *Construct = dyn_cast<CXXConstructExpr>(ExprInit);
346  if (!Construct)
347  continue;
348 
349  // Ensure that the constructor receives a single argument.
350  if (Construct->getNumArgs() != 1)
351  return;
352 
353  // Drill down to the as-written initializer.
354  const Expr *E = (*Construct->arg_begin())->IgnoreParenImpCasts();
355  if (E != E->IgnoreConversionOperator()) {
356  // We hit a conversion operator. Early-out now as they imply an implicit
357  // conversion from a different type. Could also mean an explicit
358  // conversion from the same type but that's pretty rare.
359  return;
360  }
361 
362  if (const auto *NestedConstruct = dyn_cast<CXXConstructExpr>(E)) {
363  // If we ran into an implicit conversion contructor, can't convert.
364  //
365  // FIXME: The following only checks if the constructor can be used
366  // implicitly, not if it actually was. Cases where the converting
367  // constructor was used explicitly won't get converted.
368  if (NestedConstruct->getConstructor()->isConvertingConstructor(false))
369  return;
370  }
371  if (!Context->hasSameType(V->getType(), E->getType()))
372  return;
373  }
374 
375  // Get the type location using the first declaration.
376  const auto *V = cast<VarDecl>(*D->decl_begin());
377 
378  // WARNING: TypeLoc::getSourceRange() will include the identifier for things
379  // like function pointers. Not a concern since this action only works with
380  // iterators but something to keep in mind in the future.
381 
382  SourceRange Range(V->getTypeSourceInfo()->getTypeLoc().getSourceRange());
383  diag(Range.getBegin(), "use auto when declaring iterators")
384  << FixItHint::CreateReplacement(Range, "auto");
385 }
386 
387 void UseAutoCheck::replaceExpr(
388  const DeclStmt *D, ASTContext *Context,
389  llvm::function_ref<QualType(const Expr *)> GetType, StringRef Message) {
390  const auto *FirstDecl = dyn_cast<VarDecl>(*D->decl_begin());
391  // Ensure that there is at least one VarDecl within the DeclStmt.
392  if (!FirstDecl)
393  return;
394 
395  const QualType FirstDeclType = FirstDecl->getType().getCanonicalType();
396 
397  std::vector<FixItHint> StarRemovals;
398  for (const auto *Dec : D->decls()) {
399  const auto *V = cast<VarDecl>(Dec);
400  // Ensure that every DeclStmt child is a VarDecl.
401  if (!V)
402  return;
403 
404  const auto *Expr = V->getInit()->IgnoreParenImpCasts();
405  // Ensure that every VarDecl has an initializer.
406  if (!Expr)
407  return;
408 
409  // If VarDecl and Initializer have mismatching unqualified types.
410  if (!Context->hasSameUnqualifiedType(V->getType(), GetType(Expr)))
411  return;
412 
413  // All subsequent variables in this declaration should have the same
414  // canonical type. For example, we don't want to use `auto` in
415  // `T *p = new T, **pp = new T*;`.
416  if (FirstDeclType != V->getType().getCanonicalType())
417  return;
418 
419  if (RemoveStars) {
420  // Remove explicitly written '*' from declarations where there's more than
421  // one declaration in the declaration list.
422  if (Dec == *D->decl_begin())
423  continue;
424 
425  auto Q = V->getTypeSourceInfo()->getTypeLoc().getAs<PointerTypeLoc>();
426  while (!Q.isNull()) {
427  StarRemovals.push_back(FixItHint::CreateRemoval(Q.getStarLoc()));
428  Q = Q.getNextTypeLoc().getAs<PointerTypeLoc>();
429  }
430  }
431  }
432 
433  // FIXME: There is, however, one case we can address: when the VarDecl pointee
434  // is the same as the initializer, just more CV-qualified. However, TypeLoc
435  // information is not reliable where CV qualifiers are concerned so we can't
436  // do anything about this case for now.
437  TypeLoc Loc = FirstDecl->getTypeSourceInfo()->getTypeLoc();
438  if (!RemoveStars) {
439  while (Loc.getTypeLocClass() == TypeLoc::Pointer ||
440  Loc.getTypeLocClass() == TypeLoc::Qualified)
441  Loc = Loc.getNextTypeLoc();
442  }
443  while (Loc.getTypeLocClass() == TypeLoc::LValueReference ||
444  Loc.getTypeLocClass() == TypeLoc::RValueReference ||
445  Loc.getTypeLocClass() == TypeLoc::Qualified) {
446  Loc = Loc.getNextTypeLoc();
447  }
448  SourceRange Range(Loc.getSourceRange());
449 
450  if (MinTypeNameLength != 0 &&
451  GetTypeNameLength(RemoveStars,
452  tooling::fixit::getText(Loc.getSourceRange(),
453  FirstDecl->getASTContext())) <
454  MinTypeNameLength)
455  return;
456 
457  auto Diag = diag(Range.getBegin(), Message);
458 
459  // Space after 'auto' to handle cases where the '*' in the pointer type is
460  // next to the identifier. This avoids changing 'int *p' into 'autop'.
461  // FIXME: This doesn't work for function pointers because the variable name
462  // is inside the type.
463  Diag << FixItHint::CreateReplacement(Range, RemoveStars ? "auto " : "auto")
464  << StarRemovals;
465 }
466 
467 void UseAutoCheck::check(const MatchFinder::MatchResult &Result) {
468  if (const auto *Decl = Result.Nodes.getNodeAs<DeclStmt>(IteratorDeclStmtId)) {
469  replaceIterators(Decl, Result.Context);
470  } else if (const auto *Decl =
471  Result.Nodes.getNodeAs<DeclStmt>(DeclWithNewId)) {
472  replaceExpr(Decl, Result.Context,
473  [](const Expr *Expr) { return Expr->getType(); },
474  "use auto when initializing with new to avoid "
475  "duplicating the type name");
476  } else if (const auto *Decl =
477  Result.Nodes.getNodeAs<DeclStmt>(DeclWithCastId)) {
478  replaceExpr(
479  Decl, Result.Context,
480  [](const Expr *Expr) {
481  return cast<ExplicitCastExpr>(Expr)->getTypeAsWritten();
482  },
483  "use auto when initializing with a cast to avoid duplicating the type "
484  "name");
485  } else if (const auto *Decl =
486  Result.Nodes.getNodeAs<DeclStmt>(DeclWithTemplateCastId)) {
487  replaceExpr(
488  Decl, Result.Context,
489  [](const Expr *Expr) {
490  return cast<CallExpr>(Expr->IgnoreImplicit())
491  ->getDirectCallee()
492  ->getReturnType();
493  },
494  "use auto when initializing with a template cast to avoid duplicating "
495  "the type name");
496  } else {
497  llvm_unreachable("Bad Callback. No node provided.");
498  }
499 }
500 
501 } // namespace modernize
502 } // namespace tidy
503 } // namespace clang
SourceLocation Loc
&#39;#&#39; location in the include directive
llvm::StringRef Name
AST_MATCHER(BinaryOperator, isAssignmentOperator)
Definition: Matchers.h:20
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: ClangTidy.cpp:460
LangOptions getLangOpts() const
Returns the language options from the context.
Definition: ClangTidy.h:187
std::map< std::string, std::string > OptionMap
FunctionInfo Info
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
AST_MATCHER_P(FunctionDecl, throws, internal::Matcher< Type >, InnerMatcher)
CharSourceRange Range
SourceRange for the file name.
DiagnosticBuilder diag(SourceLocation Loc, StringRef Description, DiagnosticIDs::Level Level=DiagnosticIDs::Warning)
Add a diagnostic with the check&#39;s name.
Definition: ClangTidy.cpp:427