blob: 1257d100d3d5257833c1e0e0d09bd67067b35524 [file] [log] [blame]
Alexander Kornienko72f1e752014-06-18 09:33:46 +00001//===--- ExplicitConstructorCheck.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 "ExplicitConstructorCheck.h"
11#include "clang/AST/ASTContext.h"
12#include "clang/ASTMatchers/ASTMatchFinder.h"
13#include "clang/ASTMatchers/ASTMatchers.h"
14#include "clang/Lex/Lexer.h"
15
16using namespace clang::ast_matchers;
17
18namespace clang {
19namespace tidy {
Alexander Kornienkoed824e02015-03-05 13:46:14 +000020namespace google {
Alexander Kornienko72f1e752014-06-18 09:33:46 +000021
22void ExplicitConstructorCheck::registerMatchers(MatchFinder *Finder) {
Aaron Ballmanec3e5d62015-09-02 16:20:42 +000023 // Only register the matchers for C++; the functionality currently does not
24 // provide any benefit to other languages, despite being benign.
Alexander Kornienkobbd85362016-12-23 15:03:12 +000025 if (!getLangOpts().CPlusPlus)
26 return;
27 Finder->addMatcher(cxxConstructorDecl(unless(isInstantiated())).bind("ctor"),
28 this);
Alexander Kornienkodd0c0ba2016-12-28 13:48:03 +000029 Finder->addMatcher(
30 cxxConversionDecl(unless(isExplicit()), // Already marked explicit.
31 unless(isImplicit())) // Compiler-generated.
32 .bind("conversion"),
33 this);
Alexander Kornienko72f1e752014-06-18 09:33:46 +000034}
35
36// Looks for the token matching the predicate and returns the range of the found
37// token including trailing whitespace.
Benjamin Kramer51a9cc92016-06-15 15:46:10 +000038static SourceRange FindToken(const SourceManager &Sources,
39 const LangOptions &LangOpts,
Benjamin Kramere7103712015-03-23 12:49:15 +000040 SourceLocation StartLoc, SourceLocation EndLoc,
41 bool (*Pred)(const Token &)) {
Alexander Kornienko72f1e752014-06-18 09:33:46 +000042 if (StartLoc.isMacroID() || EndLoc.isMacroID())
43 return SourceRange();
44 FileID File = Sources.getFileID(Sources.getSpellingLoc(StartLoc));
45 StringRef Buf = Sources.getBufferData(File);
46 const char *StartChar = Sources.getCharacterData(StartLoc);
47 Lexer Lex(StartLoc, LangOpts, StartChar, StartChar, Buf.end());
48 Lex.SetCommentRetentionState(true);
49 Token Tok;
50 do {
51 Lex.LexFromRawLexer(Tok);
52 if (Pred(Tok)) {
53 Token NextTok;
54 Lex.LexFromRawLexer(NextTok);
55 return SourceRange(Tok.getLocation(), NextTok.getLocation());
56 }
57 } while (Tok.isNot(tok::eof) && Tok.getLocation() < EndLoc);
58
59 return SourceRange();
60}
61
Benjamin Kramere7103712015-03-23 12:49:15 +000062static bool declIsStdInitializerList(const NamedDecl *D) {
Alexander Kornienkodd2dad02015-02-05 12:49:07 +000063 // First use the fast getName() method to avoid unnecessary calls to the
64 // slow getQualifiedNameAsString().
65 return D->getName() == "initializer_list" &&
66 D->getQualifiedNameAsString() == "std::initializer_list";
67}
68
Benjamin Kramere7103712015-03-23 12:49:15 +000069static bool isStdInitializerList(QualType Type) {
Alexander Kornienkodd2dad02015-02-05 12:49:07 +000070 Type = Type.getCanonicalType();
71 if (const auto *TS = Type->getAs<TemplateSpecializationType>()) {
72 if (const TemplateDecl *TD = TS->getTemplateName().getAsTemplateDecl())
73 return declIsStdInitializerList(TD);
74 }
75 if (const auto *RT = Type->getAs<RecordType>()) {
76 if (const auto *Specialization =
77 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl()))
78 return declIsStdInitializerList(Specialization->getSpecializedTemplate());
Alexander Kornienko15c5e6a2014-11-27 11:11:47 +000079 }
80 return false;
81}
82
Alexander Kornienko72f1e752014-06-18 09:33:46 +000083void ExplicitConstructorCheck::check(const MatchFinder::MatchResult &Result) {
Alexander Kornienkobbd85362016-12-23 15:03:12 +000084 constexpr char WarningMessage[] =
85 "%0 must be marked explicit to avoid unintentional implicit conversions";
86
87 if (const auto *Conversion =
88 Result.Nodes.getNodeAs<CXXConversionDecl>("conversion")) {
89 SourceLocation Loc = Conversion->getLocation();
90 diag(Loc, WarningMessage)
91 << Conversion << FixItHint::CreateInsertion(Loc, "explicit ");
92 return;
93 }
94
Piotr Padlewski08124b12016-12-14 15:29:23 +000095 const auto *Ctor = Result.Nodes.getNodeAs<CXXConstructorDecl>("ctor");
Alexander Kornienko72f1e752014-06-18 09:33:46 +000096 // Do not be confused: isExplicit means 'explicit' keyword is present,
97 // isImplicit means that it's a compiler-generated constructor.
Alexander Kornienko15c5e6a2014-11-27 11:11:47 +000098 if (Ctor->isOutOfLine() || Ctor->isImplicit() || Ctor->isDeleted() ||
99 Ctor->getNumParams() == 0 || Ctor->getMinRequiredArguments() > 1)
Alexander Kornienko72f1e752014-06-18 09:33:46 +0000100 return;
101
Alexander Kornienko15c5e6a2014-11-27 11:11:47 +0000102 bool takesInitializerList = isStdInitializerList(
103 Ctor->getParamDecl(0)->getType().getNonReferenceType());
104 if (Ctor->isExplicit() &&
105 (Ctor->isCopyOrMoveConstructor() || takesInitializerList)) {
Alexander Kornienko72f1e752014-06-18 09:33:46 +0000106 auto isKWExplicit = [](const Token &Tok) {
107 return Tok.is(tok::raw_identifier) &&
108 Tok.getRawIdentifier() == "explicit";
109 };
110 SourceRange ExplicitTokenRange =
Gabor Horvathafad84c2016-09-24 02:13:45 +0000111 FindToken(*Result.SourceManager, getLangOpts(),
Alexander Kornienko72f1e752014-06-18 09:33:46 +0000112 Ctor->getOuterLocStart(), Ctor->getLocEnd(), isKWExplicit);
Alexander Kornienko15c5e6a2014-11-27 11:11:47 +0000113 StringRef ConstructorDescription;
114 if (Ctor->isMoveConstructor())
115 ConstructorDescription = "move";
116 else if (Ctor->isCopyConstructor())
117 ConstructorDescription = "copy";
118 else
119 ConstructorDescription = "initializer-list";
120
Alexander Kornienkobbd85362016-12-23 15:03:12 +0000121 auto Diag = diag(Ctor->getLocation(),
122 "%0 constructor should not be declared explicit")
123 << ConstructorDescription;
Alexander Kornienko72f1e752014-06-18 09:33:46 +0000124 if (ExplicitTokenRange.isValid()) {
125 Diag << FixItHint::CreateRemoval(
126 CharSourceRange::getCharRange(ExplicitTokenRange));
127 }
Alexander Kornienko15c5e6a2014-11-27 11:11:47 +0000128 return;
Alexander Kornienko72f1e752014-06-18 09:33:46 +0000129 }
130
131 if (Ctor->isExplicit() || Ctor->isCopyOrMoveConstructor() ||
Alexander Kornienko15c5e6a2014-11-27 11:11:47 +0000132 takesInitializerList)
Alexander Kornienko72f1e752014-06-18 09:33:46 +0000133 return;
134
Alexander Kornienko0b024612015-03-31 16:24:44 +0000135 bool SingleArgument =
136 Ctor->getNumParams() == 1 && !Ctor->getParamDecl(0)->isParameterPack();
Alexander Kornienko72f1e752014-06-18 09:33:46 +0000137 SourceLocation Loc = Ctor->getLocation();
Alexander Kornienkobbd85362016-12-23 15:03:12 +0000138 diag(Loc, WarningMessage)
Alexander Kornienko5eb134c2015-11-28 02:25:02 +0000139 << (SingleArgument
140 ? "single-argument constructors"
141 : "constructors that are callable with a single argument")
Alexander Kornienko72f1e752014-06-18 09:33:46 +0000142 << FixItHint::CreateInsertion(Loc, "explicit ");
143}
144
Alexander Kornienkoed824e02015-03-05 13:46:14 +0000145} // namespace google
Alexander Kornienko72f1e752014-06-18 09:33:46 +0000146} // namespace tidy
147} // namespace clang