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 "../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 diag(Loc, NoExpressionWarningMessage)
51 << Conversion << FixItHint::CreateInsertion(Loc, "explicit ");
52 return;
53 }
54
55 const auto *Ctor = Result.Nodes.getNodeAs<CXXConstructorDecl>("ctor");
56 if (Ctor->isOutOfLine() || Ctor->getNumParams() == 0 ||
57 Ctor->getMinRequiredArguments() > 1)
58 return;
59
60 const ExplicitSpecifier ExplicitSpec = Ctor->getExplicitSpecifier();
61
62 const bool TakesInitializerList = utils::type_traits::isStdInitializerList(
63 Ctor->getParamDecl(0)->getType().getNonReferenceType());
64 if (ExplicitSpec.isExplicit() &&
65 (Ctor->isCopyOrMoveConstructor() || TakesInitializerList)) {
66 auto IsKwExplicit = [](const Token &Tok) {
67 return Tok.is(tok::raw_identifier) &&
68 Tok.getRawIdentifier() == "explicit";
69 };
70 const CharSourceRange ConstructorRange = CharSourceRange::getTokenRange(
71 Ctor->getOuterLocStart(), Ctor->getEndLoc());
72 const CharSourceRange ExplicitTokenRange =
74 *Result.SourceManager, getLangOpts(),
75 IsKwExplicit);
76 StringRef ConstructorDescription;
77 if (Ctor->isMoveConstructor())
78 ConstructorDescription = "move";
79 else if (Ctor->isCopyConstructor())
80 ConstructorDescription = "copy";
81 else
82 ConstructorDescription = "initializer-list";
83
84 auto Diag = diag(Ctor->getLocation(),
85 "%0 constructor should not be declared explicit")
86 << ConstructorDescription;
87 if (ExplicitTokenRange.isValid())
88 Diag << FixItHint::CreateRemoval(ExplicitTokenRange);
89 return;
90 }
91
92 if (ExplicitSpec.isExplicit() || Ctor->isCopyOrMoveConstructor() ||
93 TakesInitializerList)
94 return;
95
96 // Don't complain about explicit(false) or dependent expressions
97 const Expr *ExplicitExpr = ExplicitSpec.getExpr();
98 if (ExplicitExpr) {
99 ExplicitExpr = ExplicitExpr->IgnoreImplicit();
100 if (isa<CXXBoolLiteralExpr>(ExplicitExpr) ||
101 ExplicitExpr->isInstantiationDependent())
102 return;
103 }
104
105 const bool SingleArgument =
106 Ctor->getNumParams() == 1 && !Ctor->getParamDecl(0)->isParameterPack();
107 const SourceLocation Loc = Ctor->getLocation();
108 auto Diag =
109 diag(Loc, ExplicitExpr ? WithExpressionWarningMessage
110 : NoExpressionWarningMessage)
111 << (SingleArgument
112 ? "single-argument constructors"
113 : "constructors that are callable with a single argument");
114
115 if (!ExplicitExpr)
116 Diag << FixItHint::CreateInsertion(Loc, "explicit ");
117}
118
119} // 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.