-
Notifications
You must be signed in to change notification settings - Fork 10.4k
/
Copy pathTypeCheckBitwise.cpp
431 lines (364 loc) · 13.8 KB
/
TypeCheckBitwise.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
//===------ TypeCheckBitwise.cpp - Type checking bitwise protocols -------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2024 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// Semantic analysis for BitwiseCopyable.
//
//===----------------------------------------------------------------------===//
#include "TypeCheckBitwise.h"
#include "TypeCheckInvertible.h" // StorageVisitor
#include "TypeChecker.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/Builtins.h"
#include "swift/AST/ConformanceLookup.h"
#include "swift/AST/Decl.h"
#include "swift/AST/DiagnosticEngine.h"
#include "swift/AST/Ownership.h"
#include "swift/AST/TypeCheckRequests.h"
#include "swift/AST/Types.h"
#include "swift/Basic/Assertions.h"
#include "swift/Basic/Defer.h"
using namespace swift;
namespace {
enum class BitwiseCopyableCheck {
/// For a user-written conformance. Diagnostics must be emitted.
Explicit,
/// For a synthesized conformance. Diagnostics must be suppressed.
Implicit,
};
bool isImplicit(BitwiseCopyableCheck check) {
switch (check) {
case BitwiseCopyableCheck::Explicit:
return false;
case BitwiseCopyableCheck::Implicit:
return true;
}
}
/// The implicit check kind appropriate to \p nominal, if any.
///
/// For public, non-frozen types, this is ::None.
std::optional<BitwiseCopyableCheck>
getImplicitCheckForNominal(NominalTypeDecl *nominal) {
assert(nominal);
if (!nominal
->getFormalAccessScope(
/*useDC=*/nullptr, /*treatUsableFromInlineAsPublic=*/true)
.isPublicOrPackage())
return {BitwiseCopyableCheck::Implicit};
if (nominal->hasClangNode() ||
nominal->getAttrs().hasAttribute<FixedLayoutAttr>() ||
nominal->getAttrs().hasAttribute<FrozenAttr>())
return {BitwiseCopyableCheck::Implicit};
return std::nullopt;
}
/// Checks that \p nominal conforms to BitwiseCopyable and emits the relevant
/// diagnostics if not.
class BitwiseCopyableStorageVisitor : public StorageVisitor {
public:
bool invalid = false;
private:
NominalTypeDecl *const nominal;
BitwiseCopyableCheck const check;
DeclContext *const dc;
ModuleDecl *const module;
ProtocolDecl *const protocol;
public:
BitwiseCopyableStorageVisitor(NominalTypeDecl *nominal, DeclContext *dc,
BitwiseCopyableCheck check)
: StorageVisitor(), nominal(nominal), check(check), dc(dc),
module(dc->getParentModule()),
protocol(module->getASTContext().getProtocol(
KnownProtocolKind::BitwiseCopyable)) {
assert(protocol);
}
private:
ValueDecl *storage = nullptr;
/// Handle a stored property.
bool operator()(VarDecl *property, Type propertyType) override {
return visitMemberDecl(property, propertyType);
}
/// Handle an enum associated value.
bool operator()(EnumElementDecl *element, Type elementType) override {
return visitMemberDecl(element, elementType);
}
bool visitMemberDecl(ValueDecl *storage, Type ty);
bool visitMemberType(Type type, SourceLoc loc);
bool visitNonconformingMemberType(Type type, SourceLoc loc);
void emitNonconformingMemberTypeDiagnostic(Type ty, SourceLoc loc);
};
bool BitwiseCopyableStorageVisitor::visitMemberDecl(ValueDecl *decl, Type ty) {
storage = decl;
SWIFT_DEFER { storage = nullptr; };
auto *element = dyn_cast<EnumElementDecl>(decl);
if (element && element->isIndirect()) {
if (!isImplicit(check)) {
nominal->diagnose(diag::non_bitwise_copyable_type_indirect_enum_element);
element->diagnose(diag::note_non_bitwise_copyable_type_indirect_enum_element);
}
invalid = true;
return true;
}
// Fields with unowned(unsafe) ownership are bitwise-copyable.
auto *roa = decl->getAttrs().getAttribute<ReferenceOwnershipAttr>();
if (roa && roa->get() == ReferenceOwnership::Unmanaged) {
return false;
}
visitMemberType(ty, storage->getLoc());
if (invalid) {
assert(isImplicit(check));
return true;
}
return false;
}
bool BitwiseCopyableStorageVisitor::visitMemberType(Type ty, SourceLoc loc) {
auto conformance = checkConformance(ty, protocol);
if (conformance.isInvalid() || conformance.hasUnavailableConformance()) {
return visitNonconformingMemberType(ty, loc);
}
// Walk the conformance, diagnosing any missing BitwiseCopyable conformances.
bool anyMissing = false;
conformance.forEachMissingConformance(
[&](BuiltinProtocolConformance *missing) {
if (visitNonconformingMemberType(missing->getType(), loc)) {
anyMissing = true;
}
return false;
});
return anyMissing;
}
bool BitwiseCopyableStorageVisitor::visitNonconformingMemberType(
Type ty, SourceLoc loc) {
if (ty->hasError())
return false;
if (isImplicit(check)) {
invalid = true;
return true;
}
emitNonconformingMemberTypeDiagnostic(ty, loc);
return false;
}
void addBitwiseCopyableFixIt(const TypeDecl *genericArgument,
InFlightDiagnostic &diag) {
if (genericArgument->getInherited().empty()) {
auto fixItLoc = genericArgument->getLoc();
diag.fixItInsertAfter(fixItLoc, ": BitwiseCopyable");
} else {
auto fixItLoc = genericArgument->getInherited().getEndLoc();
diag.fixItInsertAfter(fixItLoc, ", BitwiseCopyable");
}
}
void BitwiseCopyableStorageVisitor::emitNonconformingMemberTypeDiagnostic(
Type ty, SourceLoc loc) {
auto module = dc->getParentModule();
auto memberTypeDecl = ty->getAnyNominal();
auto &ctx = module->getASTContext();
storage->diagnose(diag::non_bitwise_copyable_type_member, ty,
isa<EnumElementDecl>(storage), storage->getName(), nominal);
if (ty->is<FunctionType>()) {
ctx.Diags.diagnose(loc, diag::non_bitwise_copyable_function_type);
} else if (memberTypeDecl && memberTypeDecl->getParentModule() == module) {
// If the nominal type is in the current module, suggest adding
// `BitwiseCopyable` if it might make sense. Otherwise, just complain.
if (isa<StructDecl>(memberTypeDecl) || isa<EnumDecl>(memberTypeDecl)) {
auto note = memberTypeDecl->diagnose(
diag::add_nominal_bitwise_copyable_conformance, memberTypeDecl);
addBitwiseCopyableFixIt(memberTypeDecl, note);
} else {
memberTypeDecl->diagnose(diag::non_bitwise_copyable_nominal,
memberTypeDecl);
}
} else if (memberTypeDecl) {
// Note which nominal type does not conform to `BitwiseCopyable`.
memberTypeDecl->diagnose(diag::non_bitwise_copyable_nominal,
memberTypeDecl);
} else if (auto genericArchetype = ty->getAs<ArchetypeType>()) {
auto interfaceType = genericArchetype->getInterfaceType();
if (auto genericParamType = interfaceType->getAs<GenericTypeParamType>()) {
auto *genericParamTypeDecl = genericParamType->getDecl();
if (genericParamTypeDecl &&
genericParamTypeDecl->getModuleContext() == module) {
auto diag = genericParamTypeDecl->diagnose(
diag::add_generic_parameter_non_bitwise_copyable_conformance, ty);
addBitwiseCopyableFixIt(genericParamTypeDecl, diag);
}
}
}
}
static bool checkBitwiseCopyableInstanceStorage(NominalTypeDecl *nominal,
DeclContext *dc,
BitwiseCopyableCheck check) {
auto *conformanceDecl = dc->getAsDecl() ? dc->getAsDecl() : nominal;
if (nominal->suppressesConformance(KnownProtocolKind::BitwiseCopyable)) {
if (!isImplicit(check)) {
conformanceDecl->diagnose(diag::non_bitwise_copyable_type_suppressed);
}
return true;
}
auto &attrs = nominal->getAttrs();
if (attrs.hasAttribute<SensitiveAttr>()) {
if (!isImplicit(check)) {
conformanceDecl->diagnose(diag::non_bitwise_copyable_type_sensitive);
}
return true;
}
if (dc->mapTypeIntoContext(nominal->getDeclaredInterfaceType())
->isNoncopyable()) {
// Already separately diagnosed when explicit.
return true;
}
assert(dc->getParentModule()->getASTContext().getProtocol(
KnownProtocolKind::BitwiseCopyable));
if (isa<ClassDecl>(nominal)) {
if (!isImplicit(check)) {
nominal->diagnose(diag::non_bitwise_copyable_type_class);
}
return true;
}
auto *ed = dyn_cast<EnumDecl>(nominal);
if (ed && ed->isIndirect()) {
if (!isImplicit(check)) {
nominal->diagnose(diag::non_bitwise_copyable_type_indirect_enum);
}
return true;
}
auto *sd = dyn_cast<StructDecl>(nominal);
if (sd && sd->isCxxNonTrivial()) {
if (!isImplicit(check)) {
nominal->diagnose(diag::non_bitwise_copyable_type_cxx_nontrivial);
}
return true;
}
if (sd && sd->hasUnreferenceableStorage()) {
if (!isImplicit(check)) {
sd->diagnose(diag::non_bitwise_copyable_c_type_nontrivial);
sd->diagnose(diag::note_non_bitwise_copyable_c_type_add_attr);
}
return true;
}
BitwiseCopyableStorageVisitor visitor(nominal, dc, check);
return visitor.visit(nominal, dc) || visitor.invalid;
}
struct DeriveImplicitBitwiseCopyableConformance {
ASTContext &context;
ProtocolDecl *const protocol;
NominalTypeDecl *nominal;
BitwiseCopyableCheck const check;
DeriveImplicitBitwiseCopyableConformance(NominalTypeDecl *nominal,
BitwiseCopyableCheck check)
: context(nominal->getASTContext()),
protocol(context.getProtocol(KnownProtocolKind::BitwiseCopyable)),
nominal(nominal), check(check) {}
ProtocolConformance *derive();
private:
NormalProtocolConformance *synthesizeConformance(DeclContext *dc);
bool allowedForFile();
};
ProtocolConformance *DeriveImplicitBitwiseCopyableConformance::derive() {
assert(isImplicit(check));
if (!allowedForFile())
return nullptr;
// If `nominal` could be conformed explicitly to BitwiseCopyable, synthesize
// an implicit conformance.
if (checkBitwiseCopyableInstanceStorage(nominal, nominal, check))
return nullptr;
return synthesizeConformance(nominal);
}
/// Whether the FileUnitKind and SourceFileKind where `nominal` appears permit
/// a conformance to be derived.
bool DeriveImplicitBitwiseCopyableConformance::allowedForFile() {
auto *file = dyn_cast<FileUnit>(nominal->getModuleScopeContext());
if (!file)
return false;
switch (file->getKind()) {
case FileUnitKind::Source: {
auto sourceFile = nominal->getParentSourceFile();
if (!sourceFile)
return true;
switch (sourceFile->Kind) {
case SourceFileKind::Interface:
// Other native modules' types' conformances were inferred (or defined
// explicitly) during their modules' compilation.
return false;
case SourceFileKind::Library:
case SourceFileKind::MacroExpansion:
case SourceFileKind::DefaultArgument:
case SourceFileKind::Main:
case SourceFileKind::SIL:
return true;
}
llvm_unreachable("covered switch");
}
case FileUnitKind::Builtin:
// Conformances were explicitly added to builtin types in
// getBuiltinBuiltinTypeConformance.
return false;
case FileUnitKind::SerializedAST:
// Conformance is serialized along with the type; if it's absent, do not
// infer it retroactively.
return false;
case FileUnitKind::Synthesized:
// Infer conformance for types in the synthesized file.
return true;
case FileUnitKind::ClangModule:
case FileUnitKind::DWARFModule:
// Infer conformance for imported foreign modules.
return true;
}
}
NormalProtocolConformance *
DeriveImplicitBitwiseCopyableConformance::synthesizeConformance(
DeclContext *dc) {
auto conformance = context.getNormalConformance(
nominal->getDeclaredInterfaceType(), protocol, nominal->getLoc(), dc,
ProtocolConformanceState::Complete,
ProtocolConformanceOptions());
conformance->setSourceKindAndImplyingConformance(
ConformanceEntryKind::Synthesized, nullptr);
nominal->registerProtocolConformance(conformance, /*synthesized=*/true);
return conformance;
}
} // end anonymous namespace
ProtocolConformance *
swift::deriveImplicitBitwiseCopyableConformance(NominalTypeDecl *nominal) {
assert(
nominal->getASTContext().getProtocol(KnownProtocolKind::BitwiseCopyable));
auto check = getImplicitCheckForNominal(nominal);
if (!check)
return nullptr;
return DeriveImplicitBitwiseCopyableConformance(nominal, *check).derive();
}
bool swift::checkBitwiseCopyableConformance(ProtocolConformance *conformance,
bool isImplicit) {
assert(conformance->getProtocol() ==
conformance->getDeclContext()
->getParentModule()
->getASTContext()
.getProtocol(KnownProtocolKind::BitwiseCopyable));
auto conformanceDC = conformance->getDeclContext();
auto nominal = conformance->getType()->getAnyNominal();
if (!nominal)
return false;
// If this is an always-unavailable conformance, there's nothing to check.
if (auto ext = dyn_cast<ExtensionDecl>(conformanceDC)) {
if (ext->isUnavailable())
return false;
}
// BitwiseCopyable must be added in the same module or its overlay.
auto conformanceDecl = conformanceDC->getAsDecl();
if (!conformanceDecl->getModuleContext()->isSameModuleLookingThroughOverlays(
nominal->getModuleContext())) {
conformanceDecl->diagnose(diag::bitwise_copyable_outside_module, nominal);
return true;
}
auto check = isImplicit ? BitwiseCopyableCheck::Implicit
: BitwiseCopyableCheck::Explicit;
return checkBitwiseCopyableInstanceStorage(nominal, conformanceDC, check);
}