1 | //===--- UseAutoCheck.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 "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 | |
18 | using namespace clang; |
19 | using namespace clang::ast_matchers; |
20 | using namespace clang::ast_matchers::internal; |
21 | |
22 | namespace clang::tidy::modernize { |
23 | namespace { |
24 | |
25 | const char IteratorDeclStmtId[] = "iterator_decl"; |
26 | const char DeclWithNewId[] = "decl_new"; |
27 | const char DeclWithCastId[] = "decl_cast"; |
28 | const char DeclWithTemplateCastId[] = "decl_template"; |
29 | |
30 | size_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: C) ? Alpha |
42 | : (isWhitespace(c: C) || |
43 | (!RemoveStars && TemplateTypenameCntr == 0 && C == '*')) |
44 | ? Space |
45 | : Punctuation; |
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. |
70 | AST_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>(Val: Init)) { |
80 | return !Construct->isListInitialization() && Construct->getNumArgs() > 0 && |
81 | !Construct->getArg(Arg: 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. |
98 | AST_MATCHER_P(QualType, isSugarFor, Matcher<QualType>, SugarMatcher) { |
99 | QualType QT = Node; |
100 | while (true) { |
101 | if (SugarMatcher.matches(Node: QT, Finder, Builder)) |
102 | return true; |
103 | |
104 | QualType NewQT = QT.getSingleStepDesugaredType(Context: 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. |
121 | Matcher<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. |
140 | Matcher<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. |
159 | AST_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. |
167 | DeclarationMatcher standardIterator() { |
168 | return decl( |
169 | namedDecl(hasStdIteratorName()), |
170 | hasDeclContext(InnerMatcher: recordDecl(hasStdContainerName(), isInStdNamespace()))); |
171 | } |
172 | |
173 | /// Returns a TypeMatcher that matches typedefs for standard iterators |
174 | /// inside records with a standard container name. |
175 | TypeMatcher typedefIterator() { |
176 | return typedefType(hasDeclaration(InnerMatcher: standardIterator())); |
177 | } |
178 | |
179 | /// Returns a TypeMatcher that matches records named for standard |
180 | /// iterators nested inside records named for standard containers. |
181 | TypeMatcher nestedIterator() { |
182 | return recordType(hasDeclaration(InnerMatcher: standardIterator())); |
183 | } |
184 | |
185 | /// Returns a TypeMatcher that matches types declared with using |
186 | /// declarations and which name standard iterators for standard containers. |
187 | TypeMatcher iteratorFromUsingDeclaration() { |
188 | auto HasIteratorDecl = hasDeclaration(InnerMatcher: namedDecl(hasStdIteratorName())); |
189 | // Types resulting from using declarations are represented by elaboratedType. |
190 | return elaboratedType( |
191 | // Unwrap the nested name specifier to test for one of the standard |
192 | // containers. |
193 | hasQualifier(InnerMatcher: specifiesType(InnerMatcher: templateSpecializationType(hasDeclaration( |
194 | InnerMatcher: namedDecl(hasStdContainerName(), isInStdNamespace()))))), |
195 | // the named type is what comes after the final '::' in the type. It |
196 | // should name one of the standard iterator names. |
197 | namesType( |
198 | InnerMatcher: anyOf(typedefType(HasIteratorDecl), recordType(HasIteratorDecl)))); |
199 | } |
200 | |
201 | /// This matcher returns declaration statements that contain variable |
202 | /// declarations with written non-list initializer for standard iterators. |
203 | StatementMatcher makeIteratorDeclMatcher() { |
204 | return declStmt(unless(has( |
205 | varDecl(anyOf(unless(hasWrittenNonListInitializer()), |
206 | unless(hasType(InnerMatcher: isSugarFor(SugarMatcher: anyOf( |
207 | typedefIterator(), nestedIterator(), |
208 | iteratorFromUsingDeclaration()))))))))) |
209 | .bind(ID: IteratorDeclStmtId); |
210 | } |
211 | |
212 | StatementMatcher makeDeclWithNewMatcher() { |
213 | return declStmt( |
214 | unless(has(varDecl(anyOf( |
215 | unless(hasInitializer(InnerMatcher: ignoringParenImpCasts(InnerMatcher: cxxNewExpr()))), |
216 | // FIXME: TypeLoc information is not reliable where CV |
217 | // qualifiers are concerned so these types can't be |
218 | // handled for now. |
219 | hasType(InnerMatcher: pointerType( |
220 | pointee(hasCanonicalType(InnerMatcher: hasLocalQualifiers())))), |
221 | |
222 | // FIXME: Handle function pointers. For now we ignore them |
223 | // because the replacement replaces the entire type |
224 | // specifier source range which includes the identifier. |
225 | hasType(InnerMatcher: pointsTo( |
226 | InnerMatcher: pointsTo(InnerMatcher: parenType(innerType(functionType())))))))))) |
227 | .bind(ID: DeclWithNewId); |
228 | } |
229 | |
230 | StatementMatcher makeDeclWithCastMatcher() { |
231 | return declStmt( |
232 | unless(has(varDecl(unless(hasInitializer(InnerMatcher: explicitCastExpr())))))) |
233 | .bind(ID: DeclWithCastId); |
234 | } |
235 | |
236 | StatementMatcher makeDeclWithTemplateCastMatcher() { |
237 | auto ST = |
238 | substTemplateTypeParmType(hasReplacementType(equalsBoundNode(ID: "arg"))); |
239 | |
240 | auto ExplicitCall = |
241 | anyOf(has(memberExpr(hasExplicitTemplateArgs())), |
242 | has(ignoringImpCasts(InnerMatcher: declRefExpr(hasExplicitTemplateArgs())))); |
243 | |
244 | auto TemplateArg = |
245 | hasTemplateArgument(N: 0, InnerMatcher: refersToType(InnerMatcher: qualType().bind(ID: "arg"))); |
246 | |
247 | auto TemplateCall = callExpr( |
248 | ExplicitCall, |
249 | callee(InnerMatcher: functionDecl(TemplateArg, |
250 | returns(InnerMatcher: anyOf(ST, pointsTo(InnerMatcher: ST), references(InnerMatcher: ST)))))); |
251 | |
252 | return declStmt(unless(has(varDecl( |
253 | unless(hasInitializer(InnerMatcher: ignoringImplicit(InnerMatcher: TemplateCall))))))) |
254 | .bind(ID: DeclWithTemplateCastId); |
255 | } |
256 | |
257 | StatementMatcher makeCombinedMatcher() { |
258 | return declStmt( |
259 | // At least one varDecl should be a child of the declStmt to ensure |
260 | // it's a declaration list and avoid matching other declarations, |
261 | // e.g. using directives. |
262 | has(varDecl(unless(isImplicit()))), |
263 | // Skip declarations that are already using auto. |
264 | unless(has(varDecl(anyOf(hasType(InnerMatcher: autoType()), |
265 | hasType(InnerMatcher: qualType(hasDescendant(autoType()))))))), |
266 | anyOf(makeIteratorDeclMatcher(), makeDeclWithNewMatcher(), |
267 | makeDeclWithCastMatcher(), makeDeclWithTemplateCastMatcher())); |
268 | } |
269 | |
270 | } // namespace |
271 | |
272 | UseAutoCheck::UseAutoCheck(StringRef Name, ClangTidyContext *Context) |
273 | : ClangTidyCheck(Name, Context), |
274 | MinTypeNameLength(Options.get(LocalName: "MinTypeNameLength", Default: 5)), |
275 | RemoveStars(Options.get(LocalName: "RemoveStars", Default: false)) {} |
276 | |
277 | void UseAutoCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) { |
278 | Options.store(Options&: Opts, LocalName: "MinTypeNameLength", Value: MinTypeNameLength); |
279 | Options.store(Options&: Opts, LocalName: "RemoveStars", Value: RemoveStars); |
280 | } |
281 | |
282 | void UseAutoCheck::registerMatchers(MatchFinder *Finder) { |
283 | Finder->addMatcher(NodeMatch: traverse(TK: TK_AsIs, InnerMatcher: makeCombinedMatcher()), Action: this); |
284 | } |
285 | |
286 | void UseAutoCheck::replaceIterators(const DeclStmt *D, ASTContext *Context) { |
287 | for (const auto *Dec : D->decls()) { |
288 | const auto *V = cast<VarDecl>(Val: Dec); |
289 | const Expr *ExprInit = V->getInit(); |
290 | |
291 | // Skip expressions with cleanups from the initializer expression. |
292 | if (const auto *E = dyn_cast<ExprWithCleanups>(Val: ExprInit)) |
293 | ExprInit = E->getSubExpr(); |
294 | |
295 | const auto *Construct = dyn_cast<CXXConstructExpr>(Val: ExprInit); |
296 | if (!Construct) |
297 | continue; |
298 | |
299 | // Ensure that the constructor receives a single argument. |
300 | if (Construct->getNumArgs() != 1) |
301 | return; |
302 | |
303 | // Drill down to the as-written initializer. |
304 | const Expr *E = (*Construct->arg_begin())->IgnoreParenImpCasts(); |
305 | if (E != E->IgnoreConversionOperatorSingleStep()) { |
306 | // We hit a conversion operator. Early-out now as they imply an implicit |
307 | // conversion from a different type. Could also mean an explicit |
308 | // conversion from the same type but that's pretty rare. |
309 | return; |
310 | } |
311 | |
312 | if (const auto *NestedConstruct = dyn_cast<CXXConstructExpr>(E)) { |
313 | // If we ran into an implicit conversion constructor, can't convert. |
314 | // |
315 | // FIXME: The following only checks if the constructor can be used |
316 | // implicitly, not if it actually was. Cases where the converting |
317 | // constructor was used explicitly won't get converted. |
318 | if (NestedConstruct->getConstructor()->isConvertingConstructor(false)) |
319 | return; |
320 | } |
321 | if (!Context->hasSameType(V->getType(), E->getType())) |
322 | return; |
323 | } |
324 | |
325 | // Get the type location using the first declaration. |
326 | const auto *V = cast<VarDecl>(Val: *D->decl_begin()); |
327 | |
328 | // WARNING: TypeLoc::getSourceRange() will include the identifier for things |
329 | // like function pointers. Not a concern since this action only works with |
330 | // iterators but something to keep in mind in the future. |
331 | |
332 | SourceRange Range(V->getTypeSourceInfo()->getTypeLoc().getSourceRange()); |
333 | diag(Loc: Range.getBegin(), Description: "use auto when declaring iterators") |
334 | << FixItHint::CreateReplacement(RemoveRange: Range, Code: "auto"); |
335 | } |
336 | |
337 | static void ignoreTypeLocClasses( |
338 | TypeLoc &Loc, |
339 | std::initializer_list<TypeLoc::TypeLocClass> const &LocClasses) { |
340 | while (llvm::is_contained(Set: LocClasses, Element: Loc.getTypeLocClass())) |
341 | Loc = Loc.getNextTypeLoc(); |
342 | } |
343 | |
344 | static bool isMultiLevelPointerToTypeLocClasses( |
345 | TypeLoc Loc, |
346 | std::initializer_list<TypeLoc::TypeLocClass> const &LocClasses) { |
347 | ignoreTypeLocClasses(Loc, {TypeLoc::Paren, TypeLoc::Qualified}); |
348 | TypeLoc::TypeLocClass TLC = Loc.getTypeLocClass(); |
349 | if (TLC != TypeLoc::Pointer && TLC != TypeLoc::MemberPointer) |
350 | return false; |
351 | ignoreTypeLocClasses(Loc, {TypeLoc::Paren, TypeLoc::Qualified, |
352 | TypeLoc::Pointer, TypeLoc::MemberPointer}); |
353 | return llvm::is_contained(Set: LocClasses, Element: Loc.getTypeLocClass()); |
354 | } |
355 | |
356 | void UseAutoCheck::replaceExpr( |
357 | const DeclStmt *D, ASTContext *Context, |
358 | llvm::function_ref<QualType(const Expr *)> GetType, StringRef Message) { |
359 | const auto *FirstDecl = dyn_cast<VarDecl>(Val: *D->decl_begin()); |
360 | // Ensure that there is at least one VarDecl within the DeclStmt. |
361 | if (!FirstDecl) |
362 | return; |
363 | |
364 | const QualType FirstDeclType = FirstDecl->getType().getCanonicalType(); |
365 | TypeSourceInfo *TSI = FirstDecl->getTypeSourceInfo(); |
366 | |
367 | if (TSI == nullptr) |
368 | return; |
369 | |
370 | std::vector<FixItHint> StarRemovals; |
371 | for (const auto *Dec : D->decls()) { |
372 | const auto *V = cast<VarDecl>(Val: Dec); |
373 | // Ensure that every DeclStmt child is a VarDecl. |
374 | if (!V) |
375 | return; |
376 | |
377 | const auto *Expr = V->getInit()->IgnoreParenImpCasts(); |
378 | // Ensure that every VarDecl has an initializer. |
379 | if (!Expr) |
380 | return; |
381 | |
382 | // If VarDecl and Initializer have mismatching unqualified types. |
383 | if (!Context->hasSameUnqualifiedType(T1: V->getType(), T2: GetType(Expr))) |
384 | return; |
385 | |
386 | // All subsequent variables in this declaration should have the same |
387 | // canonical type. For example, we don't want to use `auto` in |
388 | // `T *p = new T, **pp = new T*;`. |
389 | if (FirstDeclType != V->getType().getCanonicalType()) |
390 | return; |
391 | |
392 | if (RemoveStars) { |
393 | // Remove explicitly written '*' from declarations where there's more than |
394 | // one declaration in the declaration list. |
395 | if (Dec == *D->decl_begin()) |
396 | continue; |
397 | |
398 | auto Q = V->getTypeSourceInfo()->getTypeLoc().getAs<PointerTypeLoc>(); |
399 | while (!Q.isNull()) { |
400 | StarRemovals.push_back(FixItHint::CreateRemoval(Q.getStarLoc())); |
401 | Q = Q.getNextTypeLoc().getAs<PointerTypeLoc>(); |
402 | } |
403 | } |
404 | } |
405 | |
406 | // FIXME: There is, however, one case we can address: when the VarDecl pointee |
407 | // is the same as the initializer, just more CV-qualified. However, TypeLoc |
408 | // information is not reliable where CV qualifiers are concerned so we can't |
409 | // do anything about this case for now. |
410 | TypeLoc Loc = TSI->getTypeLoc(); |
411 | if (!RemoveStars) |
412 | ignoreTypeLocClasses(Loc, {TypeLoc::Pointer, TypeLoc::Qualified}); |
413 | ignoreTypeLocClasses(Loc, {TypeLoc::LValueReference, TypeLoc::RValueReference, |
414 | TypeLoc::Qualified}); |
415 | SourceRange Range(Loc.getSourceRange()); |
416 | |
417 | if (MinTypeNameLength != 0 && |
418 | getTypeNameLength(RemoveStars, |
419 | tooling::fixit::getText(Loc.getSourceRange(), |
420 | FirstDecl->getASTContext())) < |
421 | MinTypeNameLength) |
422 | return; |
423 | |
424 | auto Diag = diag(Loc: Range.getBegin(), Description: Message); |
425 | |
426 | bool ShouldReplenishVariableName = isMultiLevelPointerToTypeLocClasses( |
427 | TSI->getTypeLoc(), {TypeLoc::FunctionProto, TypeLoc::ConstantArray}); |
428 | |
429 | // Space after 'auto' to handle cases where the '*' in the pointer type is |
430 | // next to the identifier. This avoids changing 'int *p' into 'autop'. |
431 | llvm::StringRef Auto = ShouldReplenishVariableName |
432 | ? (RemoveStars ? "auto ": "auto *") |
433 | : (RemoveStars ? "auto ": "auto"); |
434 | std::string ReplenishedVariableName = |
435 | ShouldReplenishVariableName ? FirstDecl->getQualifiedNameAsString() : ""; |
436 | std::string Replacement = |
437 | (Auto + llvm::StringRef{ReplenishedVariableName}).str(); |
438 | Diag << FixItHint::CreateReplacement(RemoveRange: Range, Code: Replacement) << StarRemovals; |
439 | } |
440 | |
441 | void UseAutoCheck::check(const MatchFinder::MatchResult &Result) { |
442 | if (const auto *Decl = Result.Nodes.getNodeAs<DeclStmt>(ID: IteratorDeclStmtId)) { |
443 | replaceIterators(D: Decl, Context: Result.Context); |
444 | } else if (const auto *Decl = |
445 | Result.Nodes.getNodeAs<DeclStmt>(ID: DeclWithNewId)) { |
446 | replaceExpr( |
447 | D: Decl, Context: Result.Context, GetType: [](const Expr *Expr) { return Expr->getType(); }, |
448 | Message: "use auto when initializing with new to avoid " |
449 | "duplicating the type name"); |
450 | } else if (const auto *Decl = |
451 | Result.Nodes.getNodeAs<DeclStmt>(ID: DeclWithCastId)) { |
452 | replaceExpr( |
453 | D: Decl, Context: Result.Context, |
454 | GetType: [](const Expr *Expr) { |
455 | return cast<ExplicitCastExpr>(Val: Expr)->getTypeAsWritten(); |
456 | }, |
457 | Message: "use auto when initializing with a cast to avoid duplicating the type " |
458 | "name"); |
459 | } else if (const auto *Decl = |
460 | Result.Nodes.getNodeAs<DeclStmt>(ID: DeclWithTemplateCastId)) { |
461 | replaceExpr( |
462 | D: Decl, Context: Result.Context, |
463 | GetType: [](const Expr *Expr) { |
464 | return cast<CallExpr>(Val: Expr->IgnoreImplicit()) |
465 | ->getDirectCallee() |
466 | ->getReturnType(); |
467 | }, |
468 | Message: "use auto when initializing with a template cast to avoid duplicating " |
469 | "the type name"); |
470 | } else { |
471 | llvm_unreachable("Bad Callback. No node provided."); |
472 | } |
473 | } |
474 | |
475 | } // namespace clang::tidy::modernize |
476 |
Definitions
- IteratorDeclStmtId
- DeclWithNewId
- DeclWithCastId
- DeclWithTemplateCastId
- getTypeNameLength
- hasWrittenNonListInitializer
- isSugarFor
- hasStdIteratorName
- hasStdContainerName
- hasExplicitTemplateArgs
- standardIterator
- typedefIterator
- nestedIterator
- iteratorFromUsingDeclaration
- makeIteratorDeclMatcher
- makeDeclWithNewMatcher
- makeDeclWithCastMatcher
- makeDeclWithTemplateCastMatcher
- makeCombinedMatcher
- UseAutoCheck
- storeOptions
- registerMatchers
- replaceIterators
- ignoreTypeLocClasses
- isMultiLevelPointerToTypeLocClasses
- replaceExpr
Learn to use CMake with our Intro Training
Find out more