blob: 220d31c360e456fa846130034285d76f15e2c2ce [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(
Alexander Kornienko56d08062016-12-30 13:25:03 +000030 cxxConversionDecl(unless(anyOf(isExplicit(), // Already marked explicit.
31 isImplicit(), // Compiler-generated.
32 isInstantiated())))
33
Alexander Kornienkodd0c0ba2016-12-28 13:48:03 +000034 .bind("conversion"),
35 this);
Alexander Kornienko72f1e752014-06-18 09:33:46 +000036}
37
38// Looks for the token matching the predicate and returns the range of the found
39// token including trailing whitespace.
Benjamin Kramer51a9cc92016-06-15 15:46:10 +000040static SourceRange FindToken(const SourceManager &Sources,
41 const LangOptions &LangOpts,
Benjamin Kramere7103712015-03-23 12:49:15 +000042 SourceLocation StartLoc, SourceLocation EndLoc,
43 bool (*Pred)(const Token &)) {
Alexander Kornienko72f1e752014-06-18 09:33:46 +000044 if (StartLoc.isMacroID() || EndLoc.isMacroID())
45 return SourceRange();
46 FileID File = Sources.getFileID(Sources.getSpellingLoc(StartLoc));
47 StringRef Buf = Sources.getBufferData(File);
48 const char *StartChar = Sources.getCharacterData(StartLoc);
49 Lexer Lex(StartLoc, LangOpts, StartChar, StartChar, Buf.end());
50 Lex.SetCommentRetentionState(true);
51 Token Tok;
52 do {
53 Lex.LexFromRawLexer(Tok);
54 if (Pred(Tok)) {
55 Token NextTok;
56 Lex.LexFromRawLexer(NextTok);
57 return SourceRange(Tok.getLocation(), NextTok.getLocation());
58 }
59 } while (Tok.isNot(tok::eof) && Tok.getLocation() < EndLoc);
60
61 return SourceRange();
62}
63
Benjamin Kramere7103712015-03-23 12:49:15 +000064static bool declIsStdInitializerList(const NamedDecl *D) {
Alexander Kornienkodd2dad02015-02-05 12:49:07 +000065 // First use the fast getName() method to avoid unnecessary calls to the
66 // slow getQualifiedNameAsString().
67 return D->getName() == "initializer_list" &&
68 D->getQualifiedNameAsString() == "std::initializer_list";
69}
70
Benjamin Kramere7103712015-03-23 12:49:15 +000071static bool isStdInitializerList(QualType Type) {
Alexander Kornienkodd2dad02015-02-05 12:49:07 +000072 Type = Type.getCanonicalType();
73 if (const auto *TS = Type->getAs<TemplateSpecializationType>()) {
74 if (const TemplateDecl *TD = TS->getTemplateName().getAsTemplateDecl())
75 return declIsStdInitializerList(TD);
76 }
77 if (const auto *RT = Type->getAs<RecordType>()) {
78 if (const auto *Specialization =
79 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl()))
80 return declIsStdInitializerList(Specialization->getSpecializedTemplate());
Alexander Kornienko15c5e6a2014-11-27 11:11:47 +000081 }
82 return false;
83}
84
Alexander Kornienko72f1e752014-06-18 09:33:46 +000085void ExplicitConstructorCheck::check(const MatchFinder::MatchResult &Result) {
Alexander Kornienkobbd85362016-12-23 15:03:12 +000086 constexpr char WarningMessage[] =
87 "%0 must be marked explicit to avoid unintentional implicit conversions";
88
89 if (const auto *Conversion =
90 Result.Nodes.getNodeAs<CXXConversionDecl>("conversion")) {
91 SourceLocation Loc = Conversion->getLocation();
Alexander Kornienko2042f832016-12-30 15:15:14 +000092 // Ignore all macros until we learn to ignore specific ones (e.g. used in
93 // gmock to define matchers).
94 if (Loc.isMacroID())
95 return;
Alexander Kornienkobbd85362016-12-23 15:03:12 +000096 diag(Loc, WarningMessage)
97 << Conversion << FixItHint::CreateInsertion(Loc, "explicit ");
98 return;
99 }
100
Piotr Padlewski08124b12016-12-14 15:29:23 +0000101 const auto *Ctor = Result.Nodes.getNodeAs<CXXConstructorDecl>("ctor");
Alexander Kornienko72f1e752014-06-18 09:33:46 +0000102 // Do not be confused: isExplicit means 'explicit' keyword is present,
103 // isImplicit means that it's a compiler-generated constructor.
Alexander Kornienko15c5e6a2014-11-27 11:11:47 +0000104 if (Ctor->isOutOfLine() || Ctor->isImplicit() || Ctor->isDeleted() ||
105 Ctor->getNumParams() == 0 || Ctor->getMinRequiredArguments() > 1)
Alexander Kornienko72f1e752014-06-18 09:33:46 +0000106 return;
107
Alexander Kornienko15c5e6a2014-11-27 11:11:47 +0000108 bool takesInitializerList = isStdInitializerList(
109 Ctor->getParamDecl(0)->getType().getNonReferenceType());
110 if (Ctor->isExplicit() &&
111 (Ctor->isCopyOrMoveConstructor() || takesInitializerList)) {
Alexander Kornienko72f1e752014-06-18 09:33:46 +0000112 auto isKWExplicit = [](const Token &Tok) {
113 return Tok.is(tok::raw_identifier) &&
114 Tok.getRawIdentifier() == "explicit";
115 };
116 SourceRange ExplicitTokenRange =
Gabor Horvathafad84c2016-09-24 02:13:45 +0000117 FindToken(*Result.SourceManager, getLangOpts(),
Alexander Kornienko72f1e752014-06-18 09:33:46 +0000118 Ctor->getOuterLocStart(), Ctor->getLocEnd(), isKWExplicit);
Alexander Kornienko15c5e6a2014-11-27 11:11:47 +0000119 StringRef ConstructorDescription;
120 if (Ctor->isMoveConstructor())
121 ConstructorDescription = "move";
122 else if (Ctor->isCopyConstructor())
123 ConstructorDescription = "copy";
124 else
125 ConstructorDescription = "initializer-list";
126
Alexander Kornienkobbd85362016-12-23 15:03:12 +0000127 auto Diag = diag(Ctor->getLocation(),
128 "%0 constructor should not be declared explicit")
129 << ConstructorDescription;
Alexander Kornienko72f1e752014-06-18 09:33:46 +0000130 if (ExplicitTokenRange.isValid()) {
131 Diag << FixItHint::CreateRemoval(
132 CharSourceRange::getCharRange(ExplicitTokenRange));
133 }
Alexander Kornienko15c5e6a2014-11-27 11:11:47 +0000134 return;
Alexander Kornienko72f1e752014-06-18 09:33:46 +0000135 }
136
137 if (Ctor->isExplicit() || Ctor->isCopyOrMoveConstructor() ||
Alexander Kornienko15c5e6a2014-11-27 11:11:47 +0000138 takesInitializerList)
Alexander Kornienko72f1e752014-06-18 09:33:46 +0000139 return;
140
Alexander Kornienko0b024612015-03-31 16:24:44 +0000141 bool SingleArgument =
142 Ctor->getNumParams() == 1 && !Ctor->getParamDecl(0)->isParameterPack();
Alexander Kornienko72f1e752014-06-18 09:33:46 +0000143 SourceLocation Loc = Ctor->getLocation();
Alexander Kornienkobbd85362016-12-23 15:03:12 +0000144 diag(Loc, WarningMessage)
Alexander Kornienko5eb134c2015-11-28 02:25:02 +0000145 << (SingleArgument
146 ? "single-argument constructors"
147 : "constructors that are callable with a single argument")
Alexander Kornienko72f1e752014-06-18 09:33:46 +0000148 << FixItHint::CreateInsertion(Loc, "explicit ");
149}
150
Alexander Kornienkoed824e02015-03-05 13:46:14 +0000151} // namespace google
Alexander Kornienko72f1e752014-06-18 09:33:46 +0000152} // namespace tidy
153} // namespace clang