blob: 1469909a85c381e3e0a226424e517853b0ef2641 [file] [log] [blame]
Angel Garcia Gomez5b9d33a2015-08-21 15:08:51 +00001//===--- 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/ASTMatchers.h"
13#include "clang/ASTMatchers/ASTMatchFinder.h"
14
15using namespace clang;
16using namespace clang::ast_matchers;
17using namespace clang::ast_matchers::internal;
18
19namespace clang {
20namespace tidy {
21namespace modernize {
22namespace {
23
24const char IteratorDeclStmtId[] = "iterator_decl";
25const char DeclWithNewId[] = "decl_new";
26
27/// \brief Matches variable declarations that have explicit initializers that
28/// are not initializer lists.
29///
30/// Given
31/// \code
32/// iterator I = Container.begin();
33/// MyType A(42);
34/// MyType B{2};
35/// MyType C;
36/// \endcode
37///
38/// varDecl(hasWrittenNonListInitializer()) maches \c I and \c A but not \c B
39/// or \c C.
40AST_MATCHER(VarDecl, hasWrittenNonListInitializer) {
41 const Expr *Init = Node.getAnyInitializer();
42 if (!Init)
43 return false;
44
45 // The following test is based on DeclPrinter::VisitVarDecl() to find if an
46 // initializer is implicit or not.
47 if (const auto *Construct = dyn_cast<CXXConstructExpr>(Init)) {
48 return !Construct->isListInitialization() && Construct->getNumArgs() > 0 &&
49 !Construct->getArg(0)->isDefaultArgument();
50 }
51 return Node.getInitStyle() != VarDecl::ListInit;
52}
53
54/// \brief Matches QualTypes that are type sugar for QualTypes that match \c
55/// SugarMatcher.
56///
57/// Given
58/// \code
59/// class C {};
60/// typedef C my_type;
61/// typedef my_type my_other_type;
62/// \endcode
63///
64/// qualType(isSugarFor(recordType(hasDeclaration(namedDecl(hasName("C"))))))
65/// matches \c my_type and \c my_other_type.
66AST_MATCHER_P(QualType, isSugarFor, Matcher<QualType>, SugarMatcher) {
67 QualType QT = Node;
68 while (true) {
69 if (SugarMatcher.matches(QT, Finder, Builder))
70 return true;
71
72 QualType NewQT = QT.getSingleStepDesugaredType(Finder->getASTContext());
73 if (NewQT == QT)
74 return false;
75 QT = NewQT;
76 }
77}
78
79/// \brief Matches named declarations that have one of the standard iterator
80/// names: iterator, reverse_iterator, const_iterator, const_reverse_iterator.
81///
82/// Given
83/// \code
84/// iterator I;
85/// const_iterator CI;
86/// \endcode
87///
88/// namedDecl(hasStdIteratorName()) matches \c I and \c CI.
89AST_MATCHER(NamedDecl, hasStdIteratorName) {
90 static const char *IteratorNames[] = {"iterator", "reverse_iterator",
91 "const_iterator",
92 "const_reverse_iterator"};
93
94 for (const char *Name : IteratorNames) {
95 if (hasName(Name).matches(Node, Finder, Builder))
96 return true;
97 }
98 return false;
99}
100
101/// \brief Matches named declarations that have one of the standard container
102/// names.
103///
104/// Given
105/// \code
106/// class vector {};
107/// class forward_list {};
108/// class my_ver{};
109/// \endcode
110///
111/// recordDecl(hasStdContainerName()) matches \c vector and \c forward_list
112/// but not \c my_vec.
113AST_MATCHER(NamedDecl, hasStdContainerName) {
114 static const char *ContainerNames[] = {"array", "deque",
115 "forward_list", "list",
116 "vector",
117
118 "map", "multimap",
119 "set", "multiset",
120
121 "unordered_map", "unordered_multimap",
122 "unordered_set", "unordered_multiset",
123
124 "queue", "priority_queue",
125 "stack"};
126
127 for (const char *Name : ContainerNames) {
128 if (hasName(Name).matches(Node, Finder, Builder))
129 return true;
130 }
131 return false;
132}
133
134/// Matches declarations whose declaration context is the C++ standard library
135/// namespace std.
136///
137/// Note that inline namespaces are silently ignored during the lookup since
138/// both libstdc++ and libc++ are known to use them for versioning purposes.
139///
140/// Given:
141/// \code
142/// namespace ns {
143/// struct my_type {};
144/// using namespace std;
145/// }
146///
147/// using std::vector;
148/// using ns:my_type;
149/// using ns::list;
150/// \code
151///
152/// usingDecl(hasAnyUsingShadowDecl(hasTargetDecl(isFromStdNamespace())))
153/// matches "using std::vector" and "using ns::list".
154AST_MATCHER(Decl, isFromStdNamespace) {
155 const DeclContext *D = Node.getDeclContext();
156
157 while (D->isInlineNamespace())
158 D = D->getParent();
159
160 if (!D->isNamespace() || !D->getParent()->isTranslationUnit())
161 return false;
162
163 const IdentifierInfo *Info = cast<NamespaceDecl>(D)->getIdentifier();
164
165 return (Info && Info->isStr("std"));
166}
167
168/// \brief Returns a DeclarationMatcher that matches standard iterators nested
169/// inside records with a standard container name.
170DeclarationMatcher standardIterator() {
171 return allOf(
172 namedDecl(hasStdIteratorName()),
173 hasDeclContext(recordDecl(hasStdContainerName(), isFromStdNamespace())));
174}
175
176/// \brief Returns a TypeMatcher that matches typedefs for standard iterators
177/// inside records with a standard container name.
178TypeMatcher typedefIterator() {
179 return typedefType(hasDeclaration(standardIterator()));
180}
181
182/// \brief Returns a TypeMatcher that matches records named for standard
183/// iterators nested inside records named for standard containers.
184TypeMatcher nestedIterator() {
185 return recordType(hasDeclaration(standardIterator()));
186}
187
188/// \brief Returns a TypeMatcher that matches types declared with using
189/// declarations and which name standard iterators for standard containers.
190TypeMatcher iteratorFromUsingDeclaration() {
191 auto HasIteratorDecl = hasDeclaration(namedDecl(hasStdIteratorName()));
192 // Types resulting from using declarations are represented by elaboratedType.
193 return elaboratedType(allOf(
194 // Unwrap the nested name specifier to test for one of the standard
195 // containers.
196 hasQualifier(specifiesType(templateSpecializationType(hasDeclaration(
197 namedDecl(hasStdContainerName(), isFromStdNamespace()))))),
198 // the named type is what comes after the final '::' in the type. It
199 // should name one of the standard iterator names.
200 namesType(
201 anyOf(typedefType(HasIteratorDecl), recordType(HasIteratorDecl)))));
202}
203
204/// \brief This matcher returns declaration statements that contain variable
205/// declarations with written non-list initializer for standard iterators.
206StatementMatcher makeIteratorDeclMatcher() {
207 return declStmt(
208 // At least one varDecl should be a child of the declStmt to ensure
209 // it's a declaration list and avoid matching other declarations,
210 // e.g. using directives.
211 has(varDecl()),
212 unless(has(varDecl(anyOf(
213 unless(hasWrittenNonListInitializer()), hasType(autoType()),
214 unless(hasType(
215 isSugarFor(anyOf(typedefIterator(), nestedIterator(),
216 iteratorFromUsingDeclaration())))))))))
217 .bind(IteratorDeclStmtId);
218}
219
220StatementMatcher makeDeclWithNewMatcher() {
Aaron Ballmanb9ea09c2015-09-17 13:31:25 +0000221 return declStmt(
222 has(varDecl()),
223 unless(has(varDecl(anyOf(
224 unless(hasInitializer(ignoringParenImpCasts(cxxNewExpr()))),
Angel Garcia Gomez2df36482015-10-14 09:29:55 +0000225 // Skip declarations that are already using auto.
226 anyOf(hasType(autoType()),
227 hasType(pointerType(pointee(autoType())))),
Aaron Ballmanb9ea09c2015-09-17 13:31:25 +0000228 // FIXME: TypeLoc information is not reliable where CV
229 // qualifiers are concerned so these types can't be
230 // handled for now.
231 hasType(pointerType(
232 pointee(hasCanonicalType(hasLocalQualifiers())))),
Angel Garcia Gomez5b9d33a2015-08-21 15:08:51 +0000233
Aaron Ballmanb9ea09c2015-09-17 13:31:25 +0000234 // FIXME: Handle function pointers. For now we ignore them
235 // because the replacement replaces the entire type
236 // specifier source range which includes the identifier.
237 hasType(pointsTo(
238 pointsTo(parenType(innerType(functionType()))))))))))
Angel Garcia Gomez5b9d33a2015-08-21 15:08:51 +0000239 .bind(DeclWithNewId);
240}
241
242} // namespace
243
244void UseAutoCheck::registerMatchers(MatchFinder *Finder) {
Aaron Ballman8b0583e2015-08-28 17:58:10 +0000245 // Only register the matchers for C++; the functionality currently does not
246 // provide any benefit to other languages, despite being benign.
247 if (getLangOpts().CPlusPlus) {
248 Finder->addMatcher(makeIteratorDeclMatcher(), this);
249 Finder->addMatcher(makeDeclWithNewMatcher(), this);
250 }
Angel Garcia Gomez5b9d33a2015-08-21 15:08:51 +0000251}
252
253void UseAutoCheck::replaceIterators(const DeclStmt *D, ASTContext *Context) {
254 for (const auto *Dec : D->decls()) {
255 const auto *V = cast<VarDecl>(Dec);
256 const Expr *ExprInit = V->getInit();
257
258 // Skip expressions with cleanups from the intializer expression.
259 if (const auto *E = dyn_cast<ExprWithCleanups>(ExprInit))
260 ExprInit = E->getSubExpr();
261
262 const auto *Construct = dyn_cast<CXXConstructExpr>(ExprInit);
263 if (!Construct)
264 continue;
265
266 // Ensure that the constructor receives a single argument.
267 if (Construct->getNumArgs() != 1)
268 return;
269
270 // Drill down to the as-written initializer.
271 const Expr *E = (*Construct->arg_begin())->IgnoreParenImpCasts();
272 if (E != E->IgnoreConversionOperator()) {
273 // We hit a conversion operator. Early-out now as they imply an implicit
274 // conversion from a different type. Could also mean an explicit
275 // conversion from the same type but that's pretty rare.
276 return;
277 }
278
279 if (const auto *NestedConstruct = dyn_cast<CXXConstructExpr>(E)) {
280 // If we ran into an implicit conversion contructor, can't convert.
281 //
282 // FIXME: The following only checks if the constructor can be used
283 // implicitly, not if it actually was. Cases where the converting
284 // constructor was used explicitly won't get converted.
285 if (NestedConstruct->getConstructor()->isConvertingConstructor(false))
286 return;
287 }
288 if (!Context->hasSameType(V->getType(), E->getType()))
289 return;
290 }
291
292 // Get the type location using the first declaration.
293 const auto *V = cast<VarDecl>(*D->decl_begin());
294
295 // WARNING: TypeLoc::getSourceRange() will include the identifier for things
296 // like function pointers. Not a concern since this action only works with
297 // iterators but something to keep in mind in the future.
298
299 SourceRange Range(V->getTypeSourceInfo()->getTypeLoc().getSourceRange());
300 diag(Range.getBegin(), "use auto when declaring iterators")
301 << FixItHint::CreateReplacement(Range, "auto");
302}
303
304void UseAutoCheck::replaceNew(const DeclStmt *D, ASTContext *Context) {
Angel Garcia Gomeze6035de2015-09-02 10:20:00 +0000305 const auto *FirstDecl = dyn_cast<VarDecl>(*D->decl_begin());
Angel Garcia Gomez5b9d33a2015-08-21 15:08:51 +0000306 // Ensure that there is at least one VarDecl within the DeclStmt.
307 if (!FirstDecl)
308 return;
309
310 const QualType FirstDeclType = FirstDecl->getType().getCanonicalType();
311
312 std::vector<SourceLocation> StarLocations;
313 for (const auto *Dec : D->decls()) {
314 const auto *V = cast<VarDecl>(Dec);
315 // Ensure that every DeclStmt child is a VarDecl.
316 if (!V)
317 return;
318
319 const auto *NewExpr = cast<CXXNewExpr>(V->getInit()->IgnoreParenImpCasts());
320 // Ensure that every VarDecl has a CXXNewExpr initializer.
321 if (!NewExpr)
322 return;
323
324 // If VarDecl and Initializer have mismatching unqualified types.
325 if (!Context->hasSameUnqualifiedType(V->getType(), NewExpr->getType()))
326 return;
327
328 // Remove explicitly written '*' from declarations where there's more than
329 // one declaration in the declaration list.
330 if (Dec == *D->decl_begin())
331 continue;
332
333 // All subsequent declarations should match the same non-decorated type.
334 if (FirstDeclType != V->getType().getCanonicalType())
335 return;
336
337 auto Q = V->getTypeSourceInfo()->getTypeLoc().getAs<PointerTypeLoc>();
338 while (!Q.isNull()) {
339 StarLocations.push_back(Q.getStarLoc());
340 Q = Q.getNextTypeLoc().getAs<PointerTypeLoc>();
341 }
342 }
343
344 // FIXME: There is, however, one case we can address: when the VarDecl pointee
345 // is the same as the initializer, just more CV-qualified. However, TypeLoc
346 // information is not reliable where CV qualifiers are concerned so we can't
347 // do anything about this case for now.
348 SourceRange Range(
349 FirstDecl->getTypeSourceInfo()->getTypeLoc().getSourceRange());
350 auto Diag = diag(Range.getBegin(), "use auto when initializing with new"
351 " to avoid duplicating the type name");
352
353 // Space after 'auto' to handle cases where the '*' in the pointer type is
354 // next to the identifier. This avoids changing 'int *p' into 'autop'.
355 Diag << FixItHint::CreateReplacement(Range, "auto ");
356
357 // Remove '*' from declarations using the saved star locations.
358 for (const auto &Loc : StarLocations) {
359 Diag << FixItHint::CreateReplacement(Loc, "");
360 }
361}
362
363void UseAutoCheck::check(const MatchFinder::MatchResult &Result) {
364 if (const auto *Decl = Result.Nodes.getNodeAs<DeclStmt>(IteratorDeclStmtId)) {
365 replaceIterators(Decl, Result.Context);
366 } else if (const auto *Decl =
367 Result.Nodes.getNodeAs<DeclStmt>(DeclWithNewId)) {
368 replaceNew(Decl, Result.Context);
369 } else {
370 llvm_unreachable("Bad Callback. No node provided.");
371 }
372}
373
374} // namespace modernize
375} // namespace tidy
376} // namespace clang