clang-tools 23.0.0git
ExplicitConstructorCheck.cpp
Go to the documentation of this file.
1//===----------------------------------------------------------------------===//
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
10#include "../utils/LexerUtils.h"
11#include "clang/AST/ASTContext.h"
12#include "clang/ASTMatchers/ASTMatchFinder.h"
13#include "clang/ASTMatchers/ASTMatchers.h"
14
15using namespace clang::ast_matchers;
16
17namespace clang::tidy::google {
18
20 Finder->addMatcher(
21 cxxConstructorDecl(unless(anyOf(isImplicit(), // Compiler-generated.
22 isDeleted(), isInstantiated())))
23 .bind("ctor"),
24 this);
25 Finder->addMatcher(
26 cxxConversionDecl(unless(anyOf(isExplicit(), // Already marked explicit.
27 isImplicit(), // Compiler-generated.
28 isDeleted(), isInstantiated())))
29
30 .bind("conversion"),
31 this);
32}
33
34static bool declIsStdInitializerList(const NamedDecl *D) {
35 // First use the fast getName() method to avoid unnecessary calls to the
36 // slow getQualifiedNameAsString().
37 return D->getName() == "initializer_list" &&
38 D->getQualifiedNameAsString() == "std::initializer_list";
39}
40
41static bool isStdInitializerList(QualType Type) {
42 Type = Type.getCanonicalType();
43 if (const auto *TS = Type->getAs<TemplateSpecializationType>()) {
44 if (const TemplateDecl *TD = TS->getTemplateName().getAsTemplateDecl())
45 return declIsStdInitializerList(TD);
46 }
47 if (const auto *RT = Type->getAs<RecordType>()) {
48 if (const auto *Specialization =
49 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl()))
50 return declIsStdInitializerList(Specialization->getSpecializedTemplate());
51 }
52 return false;
53}
54
55void ExplicitConstructorCheck::check(const MatchFinder::MatchResult &Result) {
56 constexpr char NoExpressionWarningMessage[] =
57 "%0 must be marked explicit to avoid unintentional implicit conversions";
58 constexpr char WithExpressionWarningMessage[] =
59 "%0 explicit expression evaluates to 'false'";
60
61 if (const auto *Conversion =
62 Result.Nodes.getNodeAs<CXXConversionDecl>("conversion")) {
63 if (Conversion->isOutOfLine())
64 return;
65 const SourceLocation Loc = Conversion->getLocation();
66 // Ignore all macros until we learn to ignore specific ones (e.g. used in
67 // gmock to define matchers).
68 if (Loc.isMacroID())
69 return;
70 diag(Loc, NoExpressionWarningMessage)
71 << Conversion << FixItHint::CreateInsertion(Loc, "explicit ");
72 return;
73 }
74
75 const auto *Ctor = Result.Nodes.getNodeAs<CXXConstructorDecl>("ctor");
76 if (Ctor->isOutOfLine() || Ctor->getNumParams() == 0 ||
77 Ctor->getMinRequiredArguments() > 1)
78 return;
79
80 const ExplicitSpecifier ExplicitSpec = Ctor->getExplicitSpecifier();
81
82 const bool TakesInitializerList = isStdInitializerList(
83 Ctor->getParamDecl(0)->getType().getNonReferenceType());
84 if (ExplicitSpec.isExplicit() &&
85 (Ctor->isCopyOrMoveConstructor() || TakesInitializerList)) {
86 auto IsKwExplicit = [](const Token &Tok) {
87 return Tok.is(tok::raw_identifier) &&
88 Tok.getRawIdentifier() == "explicit";
89 };
90 const CharSourceRange ConstructorRange = CharSourceRange::getTokenRange(
91 Ctor->getOuterLocStart(), Ctor->getEndLoc());
92 const CharSourceRange ExplicitTokenRange =
94 *Result.SourceManager, getLangOpts(),
95 IsKwExplicit);
96 StringRef ConstructorDescription;
97 if (Ctor->isMoveConstructor())
98 ConstructorDescription = "move";
99 else if (Ctor->isCopyConstructor())
100 ConstructorDescription = "copy";
101 else
102 ConstructorDescription = "initializer-list";
103
104 auto Diag = diag(Ctor->getLocation(),
105 "%0 constructor should not be declared explicit")
106 << ConstructorDescription;
107 if (ExplicitTokenRange.isValid())
108 Diag << FixItHint::CreateRemoval(ExplicitTokenRange);
109 return;
110 }
111
112 if (ExplicitSpec.isExplicit() || Ctor->isCopyOrMoveConstructor() ||
113 TakesInitializerList)
114 return;
115
116 // Don't complain about explicit(false) or dependent expressions
117 const Expr *ExplicitExpr = ExplicitSpec.getExpr();
118 if (ExplicitExpr) {
119 ExplicitExpr = ExplicitExpr->IgnoreImplicit();
120 if (isa<CXXBoolLiteralExpr>(ExplicitExpr) ||
121 ExplicitExpr->isInstantiationDependent())
122 return;
123 }
124
125 const bool SingleArgument =
126 Ctor->getNumParams() == 1 && !Ctor->getParamDecl(0)->isParameterPack();
127 const SourceLocation Loc = Ctor->getLocation();
128 auto Diag =
129 diag(Loc, ExplicitExpr ? WithExpressionWarningMessage
130 : NoExpressionWarningMessage)
131 << (SingleArgument
132 ? "single-argument constructors"
133 : "constructors that are callable with a single argument");
134
135 if (!ExplicitExpr)
136 Diag << FixItHint::CreateInsertion(Loc, "explicit ");
137}
138
139} // namespace clang::tidy::google
void registerMatchers(ast_matchers::MatchFinder *Finder) override
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
static bool isStdInitializerList(QualType Type)
static bool declIsStdInitializerList(const NamedDecl *D)
CharSourceRange findTokenTextInRange(CharSourceRange Range, const SourceManager &SM, const LangOptions &LangOpts, llvm::function_ref< bool(const Token &)> Pred)
Returns source range of the first token in Range matching Pred. The returned char range starts at the...