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