1 //===--- ExplicitConstructorCheck.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 "ExplicitConstructorCheck.h"
10 #include "clang/AST/ASTContext.h"
11 #include "clang/ASTMatchers/ASTMatchFinder.h"
12 #include "clang/ASTMatchers/ASTMatchers.h"
13 #include "clang/Lex/Lexer.h"
14 
15 using namespace clang::ast_matchers;
16 
17 namespace clang {
18 namespace tidy {
19 namespace google {
20 
registerMatchers(MatchFinder * Finder)21 void ExplicitConstructorCheck::registerMatchers(MatchFinder *Finder) {
22   Finder->addMatcher(
23       cxxConstructorDecl(unless(anyOf(isImplicit(), // Compiler-generated.
24                                       isDeleted(), isInstantiated())))
25           .bind("ctor"),
26       this);
27   Finder->addMatcher(
28       cxxConversionDecl(unless(anyOf(isExplicit(), // Already marked explicit.
29                                      isImplicit(), // Compiler-generated.
30                                      isDeleted(), isInstantiated())))
31 
32           .bind("conversion"),
33       this);
34 }
35 
36 // Looks for the token matching the predicate and returns the range of the found
37 // token including trailing whitespace.
findToken(const SourceManager & Sources,const LangOptions & LangOpts,SourceLocation StartLoc,SourceLocation EndLoc,bool (* Pred)(const Token &))38 static SourceRange findToken(const SourceManager &Sources,
39                              const LangOptions &LangOpts,
40                              SourceLocation StartLoc, SourceLocation EndLoc,
41                              bool (*Pred)(const Token &)) {
42   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 
declIsStdInitializerList(const NamedDecl * D)62 static bool declIsStdInitializerList(const NamedDecl *D) {
63   // 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 
isStdInitializerList(QualType Type)69 static bool isStdInitializerList(QualType Type) {
70   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());
79   }
80   return false;
81 }
82 
check(const MatchFinder::MatchResult & Result)83 void ExplicitConstructorCheck::check(const MatchFinder::MatchResult &Result) {
84   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     if (Conversion->isOutOfLine())
90       return;
91     SourceLocation Loc = Conversion->getLocation();
92     // 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;
96     diag(Loc, WarningMessage)
97         << Conversion << FixItHint::CreateInsertion(Loc, "explicit ");
98     return;
99   }
100 
101   const auto *Ctor = Result.Nodes.getNodeAs<CXXConstructorDecl>("ctor");
102   if (Ctor->isOutOfLine() || Ctor->getNumParams() == 0 ||
103       Ctor->getMinRequiredArguments() > 1)
104     return;
105 
106   bool TakesInitializerList = isStdInitializerList(
107       Ctor->getParamDecl(0)->getType().getNonReferenceType());
108   if (Ctor->isExplicit() &&
109       (Ctor->isCopyOrMoveConstructor() || TakesInitializerList)) {
110     auto IsKwExplicit = [](const Token &Tok) {
111       return Tok.is(tok::raw_identifier) &&
112              Tok.getRawIdentifier() == "explicit";
113     };
114     SourceRange ExplicitTokenRange =
115         findToken(*Result.SourceManager, getLangOpts(),
116                   Ctor->getOuterLocStart(), Ctor->getEndLoc(), IsKwExplicit);
117     StringRef ConstructorDescription;
118     if (Ctor->isMoveConstructor())
119       ConstructorDescription = "move";
120     else if (Ctor->isCopyConstructor())
121       ConstructorDescription = "copy";
122     else
123       ConstructorDescription = "initializer-list";
124 
125     auto Diag = diag(Ctor->getLocation(),
126                      "%0 constructor should not be declared explicit")
127                 << ConstructorDescription;
128     if (ExplicitTokenRange.isValid()) {
129       Diag << FixItHint::CreateRemoval(
130           CharSourceRange::getCharRange(ExplicitTokenRange));
131     }
132     return;
133   }
134 
135   if (Ctor->isExplicit() || Ctor->isCopyOrMoveConstructor() ||
136       TakesInitializerList)
137     return;
138 
139   bool SingleArgument =
140       Ctor->getNumParams() == 1 && !Ctor->getParamDecl(0)->isParameterPack();
141   SourceLocation Loc = Ctor->getLocation();
142   diag(Loc, WarningMessage)
143       << (SingleArgument
144               ? "single-argument constructors"
145               : "constructors that are callable with a single argument")
146       << FixItHint::CreateInsertion(Loc, "explicit ");
147 }
148 
149 } // namespace google
150 } // namespace tidy
151 } // namespace clang
152