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