clang-tools 19.0.0git
SpecialMemberFunctionsCheck.cpp
Go to the documentation of this file.
1//===--- SpecialMemberFunctionsCheck.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
10
11#include "clang/AST/ASTContext.h"
12#include "clang/ASTMatchers/ASTMatchFinder.h"
13#include "llvm/ADT/DenseMapInfo.h"
14#include "llvm/ADT/StringExtras.h"
15
16#define DEBUG_TYPE "clang-tidy"
17
18using namespace clang::ast_matchers;
19
21
23 StringRef Name, ClangTidyContext *Context)
24 : ClangTidyCheck(Name, Context), AllowMissingMoveFunctions(Options.get(
25 "AllowMissingMoveFunctions", false)),
26 AllowSoleDefaultDtor(Options.get("AllowSoleDefaultDtor", false)),
27 AllowMissingMoveFunctionsWhenCopyIsDeleted(
28 Options.get("AllowMissingMoveFunctionsWhenCopyIsDeleted", false)),
29 AllowImplicitlyDeletedCopyOrMove(
30 Options.get("AllowImplicitlyDeletedCopyOrMove", false)) {}
31
34 Options.store(Opts, "AllowMissingMoveFunctions", AllowMissingMoveFunctions);
35 Options.store(Opts, "AllowSoleDefaultDtor", AllowSoleDefaultDtor);
36 Options.store(Opts, "AllowMissingMoveFunctionsWhenCopyIsDeleted",
37 AllowMissingMoveFunctionsWhenCopyIsDeleted);
38 Options.store(Opts, "AllowImplicitlyDeletedCopyOrMove",
39 AllowImplicitlyDeletedCopyOrMove);
40}
41
42std::optional<TraversalKind>
44 return AllowImplicitlyDeletedCopyOrMove ? TK_AsIs
45 : TK_IgnoreUnlessSpelledInSource;
46}
47
49 auto IsNotImplicitOrDeleted = anyOf(unless(isImplicit()), isDeleted());
50
51 Finder->addMatcher(
52 cxxRecordDecl(
53 unless(isImplicit()),
54 eachOf(has(cxxDestructorDecl(unless(isImplicit())).bind("dtor")),
55 has(cxxConstructorDecl(isCopyConstructor(),
56 IsNotImplicitOrDeleted)
57 .bind("copy-ctor")),
58 has(cxxMethodDecl(isCopyAssignmentOperator(),
59 IsNotImplicitOrDeleted)
60 .bind("copy-assign")),
61 has(cxxConstructorDecl(isMoveConstructor(),
62 IsNotImplicitOrDeleted)
63 .bind("move-ctor")),
64 has(cxxMethodDecl(isMoveAssignmentOperator(),
65 IsNotImplicitOrDeleted)
66 .bind("move-assign"))))
67 .bind("class-def"),
68 this);
69}
70
71static llvm::StringRef
73 switch (K) {
75 return "a destructor";
78 return "a default destructor";
81 return "a non-default destructor";
83 return "a copy constructor";
85 return "a copy assignment operator";
87 return "a move constructor";
89 return "a move assignment operator";
90 }
91 llvm_unreachable("Unhandled SpecialMemberFunctionKind");
92}
93
94static std::string
95join(ArrayRef<SpecialMemberFunctionsCheck::SpecialMemberFunctionKind> SMFS,
96 llvm::StringRef AndOr) {
97
98 assert(!SMFS.empty() &&
99 "List of defined or undefined members should never be empty.");
100 std::string Buffer;
101 llvm::raw_string_ostream Stream(Buffer);
102
103 Stream << toString(SMFS[0]);
104 size_t LastIndex = SMFS.size() - 1;
105 for (size_t I = 1; I < LastIndex; ++I) {
106 Stream << ", " << toString(SMFS[I]);
107 }
108 if (LastIndex != 0) {
109 Stream << AndOr << toString(SMFS[LastIndex]);
110 }
111 return Stream.str();
112}
113
115 const MatchFinder::MatchResult &Result) {
116 const auto *MatchedDecl = Result.Nodes.getNodeAs<CXXRecordDecl>("class-def");
117 if (!MatchedDecl)
118 return;
119
120 ClassDefId ID(MatchedDecl->getLocation(), std::string(MatchedDecl->getName()));
121
122 auto StoreMember = [this, &ID](SpecialMemberFunctionData Data) {
124 ClassWithSpecialMembers[ID];
125 if (!llvm::is_contained(Members, Data))
126 Members.push_back(std::move(Data));
127 };
128
129 if (const auto *Dtor = Result.Nodes.getNodeAs<CXXMethodDecl>("dtor")) {
130 SpecialMemberFunctionKind DestructorType =
132 if (Dtor->isDefined()) {
133 DestructorType = Dtor->getDefinition()->isDefaulted()
136 }
137 StoreMember({DestructorType, Dtor->isDeleted()});
138 }
139
140 std::initializer_list<std::pair<std::string, SpecialMemberFunctionKind>>
141 Matchers = {{"copy-ctor", SpecialMemberFunctionKind::CopyConstructor},
145
146 for (const auto &KV : Matchers)
147 if (const auto *MethodDecl =
148 Result.Nodes.getNodeAs<CXXMethodDecl>(KV.first)) {
149 StoreMember(
150 {KV.second, MethodDecl->isDeleted(), MethodDecl->isImplicit()});
151 }
152}
153
155 for (const auto &C : ClassWithSpecialMembers) {
156 checkForMissingMembers(C.first, C.second);
157 }
158}
159
160void SpecialMemberFunctionsCheck::checkForMissingMembers(
161 const ClassDefId &ID,
162 llvm::ArrayRef<SpecialMemberFunctionData> DefinedMembers) {
163 llvm::SmallVector<SpecialMemberFunctionKind, 5> MissingMembers;
164
165 auto HasMember = [&](SpecialMemberFunctionKind Kind) {
166 return llvm::any_of(DefinedMembers, [Kind](const auto &Data) {
167 return Data.FunctionKind == Kind && !Data.IsImplicit;
168 });
169 };
170
171 auto HasImplicitDeletedMember = [&](SpecialMemberFunctionKind Kind) {
172 return llvm::any_of(DefinedMembers, [Kind](const auto &Data) {
173 return Data.FunctionKind == Kind && Data.IsImplicit && Data.IsDeleted;
174 });
175 };
176
177 auto IsDeleted = [&](SpecialMemberFunctionKind Kind) {
178 return llvm::any_of(DefinedMembers, [Kind](const auto &Data) {
179 return Data.FunctionKind == Kind && Data.IsDeleted;
180 });
181 };
182
183 auto RequireMembers = [&](SpecialMemberFunctionKind Kind1,
185 if (AllowImplicitlyDeletedCopyOrMove && HasImplicitDeletedMember(Kind1) &&
186 HasImplicitDeletedMember(Kind2))
187 return;
188
189 if (!HasMember(Kind1))
190 MissingMembers.push_back(Kind1);
191
192 if (!HasMember(Kind2))
193 MissingMembers.push_back(Kind2);
194 };
195
196 bool RequireThree =
198 (!AllowSoleDefaultDtor &&
205
206 bool RequireFive = (!AllowMissingMoveFunctions && RequireThree &&
207 getLangOpts().CPlusPlus11) ||
210
211 if (RequireThree) {
215 MissingMembers.push_back(SpecialMemberFunctionKind::Destructor);
216
219 }
220
221 if (RequireFive &&
222 !(AllowMissingMoveFunctionsWhenCopyIsDeleted &&
225 assert(RequireThree);
228 }
229
230 if (!MissingMembers.empty()) {
231 llvm::SmallVector<SpecialMemberFunctionKind, 5> DefinedMemberKinds;
232 for (const auto &Data : DefinedMembers) {
233 if (!Data.IsImplicit)
234 DefinedMemberKinds.push_back(Data.FunctionKind);
235 }
236 diag(ID.first, "class '%0' defines %1 but does not define %2")
237 << ID.second << cppcoreguidelines::join(DefinedMemberKinds, " and ")
238 << cppcoreguidelines::join(MissingMembers, " or ");
239 }
240}
241
242} // namespace clang::tidy::cppcoreguidelines
BindArgumentKind Kind
llvm::SmallString< 256U > Name
const Criteria C
Kind K
Definition: Rename.cpp:474
void store(ClangTidyOptions::OptionMap &Options, StringRef LocalName, StringRef Value) const
Stores an option with the check-local name LocalName with string value Value to Options.
Base class for all clang-tidy checks.
DiagnosticBuilder diag(SourceLocation Loc, StringRef Description, DiagnosticIDs::Level Level=DiagnosticIDs::Warning)
Add a diagnostic with the check's name.
const LangOptions & getLangOpts() const
Returns the language options from the context.
Every ClangTidyCheck reports errors through a DiagnosticsEngine provided by this context.
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
ClangTidyChecks that register ASTMatchers should do the actual work in here.
void storeOptions(ClangTidyOptions::OptionMap &Opts) override
Should store all options supported by this check with their current values or default values for opti...
std::optional< TraversalKind > getCheckTraversalKind() const override
void registerMatchers(ast_matchers::MatchFinder *Finder) override
Override this to register AST matchers with Finder.
SpecialMemberFunctionsCheck(StringRef Name, ClangTidyContext *Context)
static llvm::StringRef toString(SpecialMemberFunctionsCheck::SpecialMemberFunctionKind K)
static std::string join(ArrayRef< SpecialMemberFunctionsCheck::SpecialMemberFunctionKind > SMFS, llvm::StringRef AndOr)
llvm::StringMap< ClangTidyValue > OptionMap