blob: df21d46ad58254d0b24c379baab330572031e9b1 [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;
Alexander Kornienkoc7c9b752017-03-17 09:47:05 +000027 Finder->addMatcher(
28 cxxConstructorDecl(unless(anyOf(isImplicit(), // Compiler-generated.
29 isDeleted(), isInstantiated())))
30 .bind("ctor"),
31 this);
Alexander Kornienkodd0c0ba2016-12-28 13:48:03 +000032 Finder->addMatcher(
Alexander Kornienko56d08062016-12-30 13:25:03 +000033 cxxConversionDecl(unless(anyOf(isExplicit(), // Already marked explicit.
34 isImplicit(), // Compiler-generated.
Alexander Kornienko7bcf7512017-03-17 08:40:07 +000035 isDeleted(), isInstantiated())))
Alexander Kornienko56d08062016-12-30 13:25:03 +000036
Alexander Kornienkodd0c0ba2016-12-28 13:48:03 +000037 .bind("conversion"),
38 this);
Alexander Kornienko72f1e752014-06-18 09:33:46 +000039}
40
41// Looks for the token matching the predicate and returns the range of the found
42// token including trailing whitespace.
Benjamin Kramer51a9cc92016-06-15 15:46:10 +000043static SourceRange FindToken(const SourceManager &Sources,
44 const LangOptions &LangOpts,
Benjamin Kramere7103712015-03-23 12:49:15 +000045 SourceLocation StartLoc, SourceLocation EndLoc,
46 bool (*Pred)(const Token &)) {
Alexander Kornienko72f1e752014-06-18 09:33:46 +000047 if (StartLoc.isMacroID() || EndLoc.isMacroID())
48 return SourceRange();
49 FileID File = Sources.getFileID(Sources.getSpellingLoc(StartLoc));
50 StringRef Buf = Sources.getBufferData(File);
51 const char *StartChar = Sources.getCharacterData(StartLoc);
52 Lexer Lex(StartLoc, LangOpts, StartChar, StartChar, Buf.end());
53 Lex.SetCommentRetentionState(true);
54 Token Tok;
55 do {
56 Lex.LexFromRawLexer(Tok);
57 if (Pred(Tok)) {
58 Token NextTok;
59 Lex.LexFromRawLexer(NextTok);
60 return SourceRange(Tok.getLocation(), NextTok.getLocation());
61 }
62 } while (Tok.isNot(tok::eof) && Tok.getLocation() < EndLoc);
63
64 return SourceRange();
65}
66
Benjamin Kramere7103712015-03-23 12:49:15 +000067static bool declIsStdInitializerList(const NamedDecl *D) {
Alexander Kornienkodd2dad02015-02-05 12:49:07 +000068 // First use the fast getName() method to avoid unnecessary calls to the
69 // slow getQualifiedNameAsString().
70 return D->getName() == "initializer_list" &&
71 D->getQualifiedNameAsString() == "std::initializer_list";
72}
73
Benjamin Kramere7103712015-03-23 12:49:15 +000074static bool isStdInitializerList(QualType Type) {
Alexander Kornienkodd2dad02015-02-05 12:49:07 +000075 Type = Type.getCanonicalType();
76 if (const auto *TS = Type->getAs<TemplateSpecializationType>()) {
77 if (const TemplateDecl *TD = TS->getTemplateName().getAsTemplateDecl())
78 return declIsStdInitializerList(TD);
79 }
80 if (const auto *RT = Type->getAs<RecordType>()) {
81 if (const auto *Specialization =
82 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl()))
83 return declIsStdInitializerList(Specialization->getSpecializedTemplate());
Alexander Kornienko15c5e6a2014-11-27 11:11:47 +000084 }
85 return false;
86}
87
Alexander Kornienko72f1e752014-06-18 09:33:46 +000088void ExplicitConstructorCheck::check(const MatchFinder::MatchResult &Result) {
Alexander Kornienkobbd85362016-12-23 15:03:12 +000089 constexpr char WarningMessage[] =
90 "%0 must be marked explicit to avoid unintentional implicit conversions";
91
92 if (const auto *Conversion =
93 Result.Nodes.getNodeAs<CXXConversionDecl>("conversion")) {
94 SourceLocation Loc = Conversion->getLocation();
Alexander Kornienko2042f832016-12-30 15:15:14 +000095 // Ignore all macros until we learn to ignore specific ones (e.g. used in
96 // gmock to define matchers).
97 if (Loc.isMacroID())
98 return;
Alexander Kornienkobbd85362016-12-23 15:03:12 +000099 diag(Loc, WarningMessage)
100 << Conversion << FixItHint::CreateInsertion(Loc, "explicit ");
101 return;
102 }
103
Piotr Padlewski08124b12016-12-14 15:29:23 +0000104 const auto *Ctor = Result.Nodes.getNodeAs<CXXConstructorDecl>("ctor");
Alexander Kornienkoc7c9b752017-03-17 09:47:05 +0000105 if (Ctor->isOutOfLine() || Ctor->getNumParams() == 0 ||
106 Ctor->getMinRequiredArguments() > 1)
Alexander Kornienko72f1e752014-06-18 09:33:46 +0000107 return;
108
Alexander Kornienko15c5e6a2014-11-27 11:11:47 +0000109 bool takesInitializerList = isStdInitializerList(
110 Ctor->getParamDecl(0)->getType().getNonReferenceType());
111 if (Ctor->isExplicit() &&
112 (Ctor->isCopyOrMoveConstructor() || takesInitializerList)) {
Alexander Kornienko72f1e752014-06-18 09:33:46 +0000113 auto isKWExplicit = [](const Token &Tok) {
114 return Tok.is(tok::raw_identifier) &&
115 Tok.getRawIdentifier() == "explicit";
116 };
117 SourceRange ExplicitTokenRange =
Gabor Horvathafad84c2016-09-24 02:13:45 +0000118 FindToken(*Result.SourceManager, getLangOpts(),
Alexander Kornienko72f1e752014-06-18 09:33:46 +0000119 Ctor->getOuterLocStart(), Ctor->getLocEnd(), isKWExplicit);
Alexander Kornienko15c5e6a2014-11-27 11:11:47 +0000120 StringRef ConstructorDescription;
121 if (Ctor->isMoveConstructor())
122 ConstructorDescription = "move";
123 else if (Ctor->isCopyConstructor())
124 ConstructorDescription = "copy";
125 else
126 ConstructorDescription = "initializer-list";
127
Alexander Kornienkobbd85362016-12-23 15:03:12 +0000128 auto Diag = diag(Ctor->getLocation(),
129 "%0 constructor should not be declared explicit")
130 << ConstructorDescription;
Alexander Kornienko72f1e752014-06-18 09:33:46 +0000131 if (ExplicitTokenRange.isValid()) {
132 Diag << FixItHint::CreateRemoval(
133 CharSourceRange::getCharRange(ExplicitTokenRange));
134 }
Alexander Kornienko15c5e6a2014-11-27 11:11:47 +0000135 return;
Alexander Kornienko72f1e752014-06-18 09:33:46 +0000136 }
137
138 if (Ctor->isExplicit() || Ctor->isCopyOrMoveConstructor() ||
Alexander Kornienko15c5e6a2014-11-27 11:11:47 +0000139 takesInitializerList)
Alexander Kornienko72f1e752014-06-18 09:33:46 +0000140 return;
141
Alexander Kornienko0b024612015-03-31 16:24:44 +0000142 bool SingleArgument =
143 Ctor->getNumParams() == 1 && !Ctor->getParamDecl(0)->isParameterPack();
Alexander Kornienko72f1e752014-06-18 09:33:46 +0000144 SourceLocation Loc = Ctor->getLocation();
Alexander Kornienkobbd85362016-12-23 15:03:12 +0000145 diag(Loc, WarningMessage)
Alexander Kornienko5eb134c2015-11-28 02:25:02 +0000146 << (SingleArgument
147 ? "single-argument constructors"
148 : "constructors that are callable with a single argument")
Alexander Kornienko72f1e752014-06-18 09:33:46 +0000149 << FixItHint::CreateInsertion(Loc, "explicit ");
150}
151
Alexander Kornienkoed824e02015-03-05 13:46:14 +0000152} // namespace google
Alexander Kornienko72f1e752014-06-18 09:33:46 +0000153} // namespace tidy
154} // namespace clang