1 //===--- 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 16 using namespace clang::ast_matchers; 17 18 namespace clang { 19 namespace tidy { 20 namespace google { 21 22 void ExplicitConstructorCheck::registerMatchers(MatchFinder *Finder) { 23 // Only register the matchers for C++; the functionality currently does not 24 // provide any benefit to other languages, despite being benign. 25 if (getLangOpts().CPlusPlus) 26 Finder->addMatcher( 27 cxxConstructorDecl(unless(isInstantiated())).bind("ctor"), this); 28 } 29 30 // Looks for the token matching the predicate and returns the range of the found 31 // token including trailing whitespace. 32 static SourceRange FindToken(const SourceManager &Sources, 33 const LangOptions &LangOpts, 34 SourceLocation StartLoc, SourceLocation EndLoc, 35 bool (*Pred)(const Token &)) { 36 if (StartLoc.isMacroID() || EndLoc.isMacroID()) 37 return SourceRange(); 38 FileID File = Sources.getFileID(Sources.getSpellingLoc(StartLoc)); 39 StringRef Buf = Sources.getBufferData(File); 40 const char *StartChar = Sources.getCharacterData(StartLoc); 41 Lexer Lex(StartLoc, LangOpts, StartChar, StartChar, Buf.end()); 42 Lex.SetCommentRetentionState(true); 43 Token Tok; 44 do { 45 Lex.LexFromRawLexer(Tok); 46 if (Pred(Tok)) { 47 Token NextTok; 48 Lex.LexFromRawLexer(NextTok); 49 return SourceRange(Tok.getLocation(), NextTok.getLocation()); 50 } 51 } while (Tok.isNot(tok::eof) && Tok.getLocation() < EndLoc); 52 53 return SourceRange(); 54 } 55 56 static bool declIsStdInitializerList(const NamedDecl *D) { 57 // First use the fast getName() method to avoid unnecessary calls to the 58 // slow getQualifiedNameAsString(). 59 return D->getName() == "initializer_list" && 60 D->getQualifiedNameAsString() == "std::initializer_list"; 61 } 62 63 static bool isStdInitializerList(QualType Type) { 64 Type = Type.getCanonicalType(); 65 if (const auto *TS = Type->getAs<TemplateSpecializationType>()) { 66 if (const TemplateDecl *TD = TS->getTemplateName().getAsTemplateDecl()) 67 return declIsStdInitializerList(TD); 68 } 69 if (const auto *RT = Type->getAs<RecordType>()) { 70 if (const auto *Specialization = 71 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl())) 72 return declIsStdInitializerList(Specialization->getSpecializedTemplate()); 73 } 74 return false; 75 } 76 77 void ExplicitConstructorCheck::check(const MatchFinder::MatchResult &Result) { 78 const CXXConstructorDecl *Ctor = 79 Result.Nodes.getNodeAs<CXXConstructorDecl>("ctor"); 80 // Do not be confused: isExplicit means 'explicit' keyword is present, 81 // isImplicit means that it's a compiler-generated constructor. 82 if (Ctor->isOutOfLine() || Ctor->isImplicit() || Ctor->isDeleted() || 83 Ctor->getNumParams() == 0 || Ctor->getMinRequiredArguments() > 1) 84 return; 85 86 bool takesInitializerList = isStdInitializerList( 87 Ctor->getParamDecl(0)->getType().getNonReferenceType()); 88 if (Ctor->isExplicit() && 89 (Ctor->isCopyOrMoveConstructor() || takesInitializerList)) { 90 auto isKWExplicit = [](const Token &Tok) { 91 return Tok.is(tok::raw_identifier) && 92 Tok.getRawIdentifier() == "explicit"; 93 }; 94 SourceRange ExplicitTokenRange = 95 FindToken(*Result.SourceManager, Result.Context->getLangOpts(), 96 Ctor->getOuterLocStart(), Ctor->getLocEnd(), isKWExplicit); 97 StringRef ConstructorDescription; 98 if (Ctor->isMoveConstructor()) 99 ConstructorDescription = "move"; 100 else if (Ctor->isCopyConstructor()) 101 ConstructorDescription = "copy"; 102 else 103 ConstructorDescription = "initializer-list"; 104 105 DiagnosticBuilder Diag = 106 diag(Ctor->getLocation(), 107 "%0 constructor should not be declared explicit") 108 << ConstructorDescription; 109 if (ExplicitTokenRange.isValid()) { 110 Diag << FixItHint::CreateRemoval( 111 CharSourceRange::getCharRange(ExplicitTokenRange)); 112 } 113 return; 114 } 115 116 if (Ctor->isExplicit() || Ctor->isCopyOrMoveConstructor() || 117 takesInitializerList) 118 return; 119 120 bool SingleArgument = 121 Ctor->getNumParams() == 1 && !Ctor->getParamDecl(0)->isParameterPack(); 122 SourceLocation Loc = Ctor->getLocation(); 123 diag(Loc, 124 "%0 must be marked explicit to avoid unintentional implicit conversions") 125 << (SingleArgument 126 ? "single-argument constructors" 127 : "constructors that are callable with a single argument") 128 << FixItHint::CreateInsertion(Loc, "explicit "); 129 } 130 131 } // namespace google 132 } // namespace tidy 133 } // namespace clang 134