-
Notifications
You must be signed in to change notification settings - Fork 10.4k
/
Copy pathTypeCheckDecl.cpp
3393 lines (2888 loc) · 116 KB
/
TypeCheckDecl.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
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//===--- TypeCheckDecl.cpp - Type Checking for Declarations ---------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2018 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
//
//===----------------------------------------------------------------------===//
//
// This file implements semantic analysis for declarations.
//
//===----------------------------------------------------------------------===//
#include "TypeCheckDecl.h"
#include "CodeSynthesis.h"
#include "DerivedConformances.h"
#include "MiscDiagnostics.h"
#include "TypeCheckAccess.h"
#include "TypeCheckAvailability.h"
#include "TypeCheckBitwise.h"
#include "TypeCheckConcurrency.h"
#include "TypeCheckInvertible.h"
#include "TypeCheckObjC.h"
#include "TypeCheckType.h"
#include "TypeChecker.h"
#include "swift/AST/ASTMangler.h"
#include "swift/AST/ASTPrinter.h"
#include "swift/AST/ASTVisitor.h"
#include "swift/AST/ASTWalker.h"
#include "swift/AST/AccessScope.h"
#include "swift/AST/Attr.h"
#include "swift/AST/AvailabilityInference.h"
#include "swift/AST/ClangModuleLoader.h"
#include "swift/AST/ConformanceLookup.h"
#include "swift/AST/Decl.h"
#include "swift/AST/DiagnosticsParse.h"
#include "swift/AST/ExistentialLayout.h"
#include "swift/AST/Expr.h"
#include "swift/AST/ForeignErrorConvention.h"
#include "swift/AST/GenericEnvironment.h"
#include "swift/AST/Initializer.h"
#include "swift/AST/NameLookup.h"
#include "swift/AST/NameLookupRequests.h"
#include "swift/AST/OperatorNameLookup.h"
#include "swift/AST/PrettyStackTrace.h"
#include "swift/AST/PropertyWrappers.h"
#include "swift/AST/ProtocolConformance.h"
#include "swift/AST/SourceFile.h"
#include "swift/AST/Type.h"
#include "swift/AST/TypeCheckRequests.h"
#include "swift/AST/TypeWalker.h"
#include "swift/Basic/Assertions.h"
#include "swift/Basic/Defer.h"
#include "swift/Bridging/ASTGen.h"
#include "swift/ClangImporter/ClangModule.h"
#include "swift/Sema/IDETypeChecking.h"
#include "swift/Serialization/SerializedModuleLoader.h"
#include "swift/Strings.h"
#include "swift/Subsystems.h"
#include "llvm/ADT/APFloat.h"
#include "llvm/ADT/APInt.h"
#include "llvm/ADT/APSInt.h"
#include "llvm/ADT/DenseSet.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/ADT/Twine.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/DJB.h"
using namespace swift;
#define DEBUG_TYPE "TypeCheckDecl"
namespace {
/// Used during enum raw value checking to identify duplicate raw values.
/// Character, string, float, and integer literals are all keyed by value.
/// Float and integer literals are additionally keyed by numeric equivalence.
struct RawValueKey {
enum class Kind : uint8_t {
String, Float, Int, Bool, Tombstone, Empty
} kind;
struct IntValueTy {
uint64_t v0;
uint64_t v1;
IntValueTy(const APInt &bits) {
APInt bits128 = bits.sextOrTrunc(128);
assert(bits128.getBitWidth() <= 128);
const uint64_t *data = bits128.getRawData();
v0 = data[0];
v1 = data[1];
}
};
struct FloatValueTy {
uint64_t v0;
uint64_t v1;
};
// FIXME: doesn't accommodate >64-bit or signed raw integer or float values.
union {
StringRef stringValue;
IntValueTy intValue;
FloatValueTy floatValue;
bool boolValue;
};
explicit RawValueKey(LiteralExpr *expr) {
switch (expr->getKind()) {
case ExprKind::IntegerLiteral:
kind = Kind::Int;
intValue = IntValueTy(cast<IntegerLiteralExpr>(expr)->getValue());
return;
case ExprKind::FloatLiteral: {
APFloat value = cast<FloatLiteralExpr>(expr)->getValue();
llvm::APSInt asInt(127, /*isUnsigned=*/false);
bool isExact = false;
APFloat::opStatus status =
value.convertToInteger(asInt, APFloat::rmTowardZero, &isExact);
if (asInt.getBitWidth() <= 128 && status == APFloat::opOK && isExact) {
kind = Kind::Int;
intValue = IntValueTy(asInt);
return;
}
APInt bits = value.bitcastToAPInt();
const uint64_t *data = bits.getRawData();
if (bits.getBitWidth() == 80) {
kind = Kind::Float;
floatValue = FloatValueTy{ data[0], data[1] };
} else {
assert(bits.getBitWidth() == 64);
kind = Kind::Float;
floatValue = FloatValueTy{ data[0], 0 };
}
return;
}
case ExprKind::StringLiteral:
kind = Kind::String;
stringValue = cast<StringLiteralExpr>(expr)->getValue();
return;
case ExprKind::BooleanLiteral:
kind = Kind::Bool;
boolValue = cast<BooleanLiteralExpr>(expr)->getValue();
return;
default:
llvm_unreachable("not a valid literal expr for raw value");
}
}
explicit RawValueKey(Kind k) : kind(k) {
assert((k == Kind::Tombstone || k == Kind::Empty)
&& "this ctor is only for creating DenseMap special values");
}
};
/// Used during enum raw value checking to identify the source of a raw value,
/// which may have been derived by auto-incrementing, for diagnostic purposes.
struct RawValueSource {
/// The decl that has the raw value.
EnumElementDecl *sourceElt;
/// If the sourceDecl didn't explicitly name a raw value, this is the most
/// recent preceding decl with an explicit raw value. This is used to
/// diagnose 'autoincrementing from' messages.
EnumElementDecl *lastExplicitValueElt;
};
} // end anonymous namespace
namespace llvm {
template<>
class DenseMapInfo<RawValueKey> {
public:
static RawValueKey getEmptyKey() {
return RawValueKey(RawValueKey::Kind::Empty);
}
static RawValueKey getTombstoneKey() {
return RawValueKey(RawValueKey::Kind::Tombstone);
}
static unsigned getHashValue(RawValueKey k) {
switch (k.kind) {
case RawValueKey::Kind::Float:
// Hash as bits. We want to treat distinct but IEEE-equal values as not
// equal.
return DenseMapInfo<uint64_t>::getHashValue(k.floatValue.v0) ^
DenseMapInfo<uint64_t>::getHashValue(k.floatValue.v1);
case RawValueKey::Kind::Int:
return DenseMapInfo<uint64_t>::getHashValue(k.intValue.v0) &
DenseMapInfo<uint64_t>::getHashValue(k.intValue.v1);
case RawValueKey::Kind::String:
return DenseMapInfo<StringRef>::getHashValue(k.stringValue);
case RawValueKey::Kind::Bool:
return DenseMapInfo<uint64_t>::getHashValue(k.boolValue);
case RawValueKey::Kind::Empty:
case RawValueKey::Kind::Tombstone:
return 0;
}
llvm_unreachable("Unhandled RawValueKey in switch.");
}
static bool isEqual(RawValueKey a, RawValueKey b) {
if (a.kind != b.kind)
return false;
switch (a.kind) {
case RawValueKey::Kind::Float:
// Hash as bits. We want to treat distinct but IEEE-equal values as not
// equal.
return a.floatValue.v0 == b.floatValue.v0 &&
a.floatValue.v1 == b.floatValue.v1;
case RawValueKey::Kind::Int:
return a.intValue.v0 == b.intValue.v0 &&
a.intValue.v1 == b.intValue.v1;
case RawValueKey::Kind::String:
return a.stringValue == b.stringValue;
case RawValueKey::Kind::Bool:
return a.boolValue == b.boolValue;
case RawValueKey::Kind::Empty:
case RawValueKey::Kind::Tombstone:
return true;
}
llvm_unreachable("Unhandled RawValueKey in switch.");
}
};
} // namespace llvm
static bool canSkipCircularityCheck(NominalTypeDecl *decl) {
// Don't bother checking imported or deserialized decls.
return decl->hasClangNode() || decl->wasDeserialized();
}
bool
HasCircularInheritedProtocolsRequest::evaluate(Evaluator &evaluator,
ProtocolDecl *decl) const {
if (canSkipCircularityCheck(decl))
return false;
InvertibleProtocolSet inverses;
bool anyObject = false;
auto inherited = getDirectlyInheritedNominalTypeDecls(decl, inverses, anyObject);
for (auto &found : inherited) {
auto *protoDecl = dyn_cast<ProtocolDecl>(found.Item);
if (!protoDecl)
continue;
// If we have a cycle, handle it and return true.
auto result = evaluateOrDefault(evaluator,
HasCircularInheritedProtocolsRequest{protoDecl},
true);
if (result)
return true;
}
return false;
}
bool
HasCircularRawValueRequest::evaluate(Evaluator &evaluator,
EnumDecl *decl) const {
if (canSkipCircularityCheck(decl) || !decl->hasRawType())
return false;
auto *inherited = decl->getRawType()->getEnumOrBoundGenericEnum();
if (!inherited)
return false;
// If we have a cycle, handle it and return true.
return evaluateOrDefault(evaluator, HasCircularRawValueRequest{inherited}, true);
}
namespace {
// The raw values of this enum must be kept in sync with
// diag::implicitly_final_cannot_be_open.
enum class ImplicitlyFinalReason : unsigned {
/// A property was declared with 'let'.
Let,
/// The containing class is final.
FinalClass,
/// A member was declared as 'static'.
Static
};
}
static bool inferFinalAndDiagnoseIfNeeded(ValueDecl *D, ClassDecl *cls,
FinalAttr *explicitFinalAttr,
StaticSpellingKind staticSpelling) {
// Are there any reasons to infer 'final'? Prefer 'static' over the class
// being final for the purposes of diagnostics.
std::optional<ImplicitlyFinalReason> reason;
if (staticSpelling == StaticSpellingKind::KeywordStatic) {
reason = ImplicitlyFinalReason::Static;
if (explicitFinalAttr) {
auto finalRange = explicitFinalAttr->getRange();
if (finalRange.isValid()) {
auto &context = D->getASTContext();
context.Diags.diagnose(finalRange.Start, diag::static_decl_already_final)
.fixItRemove(finalRange);
}
}
} else if (cls->isFinal()) {
reason = ImplicitlyFinalReason::FinalClass;
}
if (!reason)
return false;
if (D->getFormalAccess() == AccessLevel::Open) {
auto &context = D->getASTContext();
auto diagID = diag::implicitly_final_cannot_be_open;
if (!context.isSwiftVersionAtLeast(5))
diagID = diag::implicitly_final_cannot_be_open_swift4;
auto inFlightDiag = context.Diags.diagnose(D, diagID,
static_cast<unsigned>(reason.value()));
fixItAccess(inFlightDiag, D, AccessLevel::Public);
}
return true;
}
/// Runtime-replaceable accessors are dynamic when their storage declaration
/// is dynamic and they were explicitly defined or they are implicitly defined
/// getter/setter because no accessor was defined.
static bool doesAccessorNeedDynamicAttribute(AccessorDecl *accessor) {
auto kind = accessor->getAccessorKind();
auto storage = accessor->getStorage();
bool isObjC = storage->isObjC();
switch (kind) {
case AccessorKind::Get: {
auto readImpl = storage->getReadImpl();
if (!isObjC &&
(readImpl == ReadImplKind::Read || readImpl == ReadImplKind::Read2 ||
readImpl == ReadImplKind::Address))
return false;
return storage->isDynamic();
}
case AccessorKind::DistributedGet: {
return false;
}
case AccessorKind::Set: {
auto writeImpl = storage->getWriteImpl();
if (!isObjC && (writeImpl == WriteImplKind::Modify ||
writeImpl == WriteImplKind::Modify2 ||
writeImpl == WriteImplKind::MutableAddress ||
writeImpl == WriteImplKind::StoredWithObservers))
return false;
return storage->isDynamic();
}
case AccessorKind::Read:
if (!isObjC && storage->getReadImpl() == ReadImplKind::Read)
return storage->isDynamic();
return false;
case AccessorKind::Read2:
if (!isObjC && storage->getReadImpl() == ReadImplKind::Read2)
return storage->isDynamic();
return false;
case AccessorKind::Modify: {
if (!isObjC && storage->getWriteImpl() == WriteImplKind::Modify)
return storage->isDynamic();
return false;
}
case AccessorKind::Modify2: {
if (!isObjC && storage->getWriteImpl() == WriteImplKind::Modify2)
return storage->isDynamic();
return false;
}
case AccessorKind::MutableAddress: {
if (!isObjC && storage->getWriteImpl() == WriteImplKind::MutableAddress)
return storage->isDynamic();
return false;
}
case AccessorKind::Address: {
if (!isObjC && storage->getReadImpl() == ReadImplKind::Address)
return storage->isDynamic();
return false;
}
case AccessorKind::DidSet:
case AccessorKind::WillSet:
if (!isObjC &&
storage->getWriteImpl() == WriteImplKind::StoredWithObservers)
return storage->isDynamic();
return false;
case AccessorKind::Init:
return false;
}
llvm_unreachable("covered switch");
}
CtorInitializerKind
InitKindRequest::evaluate(Evaluator &evaluator, ConstructorDecl *decl) const {
auto &diags = decl->getASTContext().Diags;
auto dc = decl->getDeclContext();
if (auto nominal = dc->getSelfNominalTypeDecl()) {
// Convenience inits are only allowed on classes and in extensions thereof.
if (auto convenAttr = decl->getAttrs().getAttribute<ConvenienceAttr>()) {
if (auto classDecl = dyn_cast<ClassDecl>(nominal)) {
if (classDecl->isAnyActor()) {
// For an actor "convenience" is not required, but we'll honor it.
diags.diagnose(decl->getLoc(),
diag::no_convenience_keyword_init, "actors")
.fixItRemove(convenAttr->getLocation())
.warnInSwiftInterface(dc)
.warnUntilSwiftVersion(6);
} else { // not an actor
// Forbid convenience inits on Foreign CF types, as Swift does not yet
// support user-defined factory inits.
if (classDecl->getForeignClassKind() == ClassDecl::ForeignKind::CFType)
diags.diagnose(decl->getLoc(), diag::cfclass_convenience_init);
}
} else { // not a ClassDecl
auto ConvenienceLoc = convenAttr->getLocation();
// Produce a tailored diagnostic for structs and enums. They should
// not have `convenience`.
bool isStruct = dyn_cast<StructDecl>(nominal) != nullptr;
if (isStruct || dyn_cast<EnumDecl>(nominal)) {
diags.diagnose(decl->getLoc(), diag::no_convenience_keyword_init,
isStruct ? "structs" : "enums")
.fixItRemove(ConvenienceLoc);
} else {
diags.diagnose(decl->getLoc(), diag::no_convenience_keyword_init,
nominal->getName().str())
.fixItRemove(ConvenienceLoc);
}
return CtorInitializerKind::Designated;
}
return CtorInitializerKind::Convenience;
}
// if there's no `convenience` attribute...
if (auto classDcl = dyn_cast<ClassDecl>(nominal)) {
// actors infer whether they are `convenience` from their body kind.
if (classDcl->isAnyActor()) {
auto kind = decl->getDelegatingOrChainedInitKind();
switch (kind.initKind) {
case BodyInitKind::ImplicitChained:
case BodyInitKind::Chained:
case BodyInitKind::None:
break; // it's designated, we need more checks.
case BodyInitKind::Delegating:
return CtorInitializerKind::Convenience;
}
}
// A designated init for a class must be written within the class itself.
//
// This is because designated initializers of classes get a vtable entry,
// and extensions cannot add vtable entries to the extended type.
//
// If we implement the ability for extensions defined in the same module
// (or the same file) to add vtable entries, we can re-evaluate this
// restriction.
if (!decl->isSynthesized() &&
isa<ExtensionDecl>(dc->getImplementedObjCContext()) &&
!(decl->getAttrs().hasAttribute<DynamicReplacementAttr>())) {
if (classDcl->getForeignClassKind() == ClassDecl::ForeignKind::CFType) {
diags.diagnose(decl->getLoc(),
diag::designated_init_in_extension_no_convenience_tip,
nominal);
// despite having reported it as an error, say that it is designated.
return CtorInitializerKind::Designated;
} else if (classDcl->isAnyActor()) {
// tailor the diagnostic to not mention `convenience`
diags.diagnose(decl->getLoc(),
diag::designated_init_in_extension_no_convenience_tip,
nominal);
} else {
diags.diagnose(decl->getLoc(),
diag::designated_init_in_extension, nominal)
.fixItInsert(decl->getLoc(), "convenience ");
}
return CtorInitializerKind::Convenience;
}
} // end of Class context
} // end of Nominal context
// initializers in protocol extensions must be convenience inits
if (dc->getExtendedProtocolDecl()) {
return CtorInitializerKind::Convenience;
}
return CtorInitializerKind::Designated;
}
BodyInitKindAndExpr
BodyInitKindRequest::evaluate(Evaluator &evaluator,
ConstructorDecl *decl) const {
struct FindReferenceToInitializer : ASTWalker {
const ConstructorDecl *Decl;
BodyInitKind Kind = BodyInitKind::None;
ApplyExpr *InitExpr = nullptr;
ASTContext &ctx;
FindReferenceToInitializer(const ConstructorDecl *decl,
ASTContext &ctx)
: Decl(decl), ctx(ctx) { }
MacroWalking getMacroWalkingBehavior() const override {
return MacroWalking::Expansion;
}
PreWalkAction walkToDeclPre(class Decl *D) override {
// Don't walk into further nominal decls.
return Action::SkipNodeIf(isa<NominalTypeDecl>(D));
}
PreWalkResult<Expr *> walkToExprPre(Expr *E) override {
// Don't walk into closures.
if (isa<ClosureExpr>(E))
return Action::SkipNode(E);
// Look for calls of a constructor on self or super.
auto apply = dyn_cast<ApplyExpr>(E);
if (!apply)
return Action::Continue(E);
auto *argList = apply->getArgs();
auto Callee = apply->getSemanticFn();
Expr *arg;
if (isa<OtherConstructorDeclRefExpr>(Callee)) {
arg = argList->getUnaryExpr();
assert(arg);
} else if (auto *CRE = dyn_cast<ConstructorRefCallExpr>(Callee)) {
arg = CRE->getBase();
} else if (auto *dotExpr = dyn_cast<UnresolvedDotExpr>(Callee)) {
if (!dotExpr->getName().getBaseName().isConstructor())
return Action::Continue(E);
arg = dotExpr->getBase();
} else {
// Not a constructor call.
return Action::Continue(E);
}
// Look for a base of 'self' or 'super'.
arg = arg->getSemanticsProvidingExpr();
auto myKind = BodyInitKind::None;
if (arg->isSuperExpr())
myKind = BodyInitKind::Chained;
else if (arg->isSelfExprOf(Decl, /*sameBase*/true))
myKind = BodyInitKind::Delegating;
else if (auto *declRef = dyn_cast<UnresolvedDeclRefExpr>(arg)) {
// FIXME: We can see UnresolvedDeclRefExprs here because we have
// not yet run preCheckTarget() on the entire function body
// yet.
//
// We could consider pre-checking more eagerly.
auto name = declRef->getName();
auto loc = declRef->getLoc();
if (name.isSimpleName(ctx.Id_self)) {
auto *otherSelfDecl =
ASTScope::lookupSingleLocalDecl(Decl->getParentSourceFile(),
name.getFullName(), loc);
if (otherSelfDecl == Decl->getImplicitSelfDecl())
myKind = BodyInitKind::Delegating;
}
}
if (myKind == BodyInitKind::None)
return Action::Continue(E);
if (Kind == BodyInitKind::None) {
Kind = myKind;
InitExpr = apply;
return Action::Continue(E);
}
// If the kind changed, complain.
if (Kind != myKind) {
// The kind changed. Complain.
ctx.Diags.diagnose(E->getLoc(), diag::init_delegates_and_chains);
ctx.Diags.diagnose(InitExpr->getLoc(), diag::init_delegation_or_chain,
Kind == BodyInitKind::Chained);
}
return Action::Continue(E);
}
};
auto &ctx = decl->getASTContext();
FindReferenceToInitializer finder(decl, ctx);
if (auto *body = decl->getBody())
body->walk(finder);
// get the kind out of the finder.
auto Kind = finder.Kind;
auto *NTD = decl->getDeclContext()->getSelfNominalTypeDecl();
// Protocol extension and enum initializers are always delegating.
if (Kind == BodyInitKind::None) {
if (isa<ProtocolDecl>(NTD) || isa<EnumDecl>(NTD)) {
Kind = BodyInitKind::Delegating;
}
}
// Struct initializers that cannot see the layout of the struct type are
// always delegating. This occurs if the struct type is not fixed layout,
// and the constructor is either inlinable or defined in another module.
if (Kind == BodyInitKind::None && isa<StructDecl>(NTD)) {
// Note: This is specifically not using isFormallyResilient. We relax this
// rule for structs in non-resilient modules so that they can have inlinable
// constructors, as long as those constructors don't reference private
// declarations.
if (NTD->isResilient() &&
decl->getResilienceExpansion() == ResilienceExpansion::Minimal) {
Kind = BodyInitKind::Delegating;
} else if (isa<ExtensionDecl>(decl->getDeclContext())) {
// Prior to Swift 5, cross-module initializers were permitted to be
// non-delegating. However, if the struct isn't fixed-layout, we have to
// be delegating because, well, we don't know the layout.
// A dynamic replacement is permitted to be non-delegating.
if (NTD->isResilient() ||
(ctx.isSwiftVersionAtLeast(5) &&
!decl->getAttrs().getAttribute<DynamicReplacementAttr>())) {
if (decl->getParentModule() != NTD->getParentModule())
Kind = BodyInitKind::Delegating;
}
}
}
// If we didn't find any delegating or chained initializers, check whether
// the initializer was explicitly marked 'convenience'.
if (Kind == BodyInitKind::None &&
decl->getAttrs().hasAttribute<ConvenienceAttr>())
Kind = BodyInitKind::Delegating;
// If we still don't know, check whether we have a class with a superclass: it
// gets an implicit chained initializer.
if (Kind == BodyInitKind::None) {
if (auto classDecl = decl->getDeclContext()->getSelfClassDecl()) {
if (classDecl->hasSuperclass())
Kind = BodyInitKind::ImplicitChained;
}
}
return BodyInitKindAndExpr(Kind, finder.InitExpr);
}
bool
ProtocolRequiresClassRequest::evaluate(Evaluator &evaluator,
ProtocolDecl *decl) const {
// Quick check: @objc protocols require a class.
if (decl->isObjC())
return true;
// Determine the set of nominal types that this protocol inherits.
InvertibleProtocolSet inverses;
bool anyObject = false;
auto allInheritedNominals =
getDirectlyInheritedNominalTypeDecls(decl, inverses, anyObject);
// Quick check: do we inherit AnyObject?
if (anyObject)
return true;
// Look through all of the inherited nominals for a superclass or a
// class-bound protocol.
for (const auto &found : allInheritedNominals) {
// Superclass bound.
if (isa<ClassDecl>(found.Item))
return true;
// A protocol that might be class-constrained.
if (auto proto = dyn_cast<ProtocolDecl>(found.Item)) {
if (proto->requiresClass())
return true;
}
}
return false;
}
bool
ExistentialConformsToSelfRequest::evaluate(Evaluator &evaluator,
ProtocolDecl *decl) const {
// Marker protocols always self-conform.
if (decl->isMarkerProtocol()) {
// Except for BitwiseCopyable an existential of which is not bitwise
// copyable.
if (decl->getKnownProtocolKind() == KnownProtocolKind::BitwiseCopyable) {
return false;
}
return true;
}
// Otherwise, if it's not @objc, it conforms to itself only if it has a
// self-conformance witness table.
if (!decl->isObjC())
return decl->requiresSelfConformanceWitnessTable();
// Check whether this protocol conforms to itself.
for (auto member : decl->getMembers()) {
if (member->isInvalid()) continue;
if (auto vd = dyn_cast<ValueDecl>(member)) {
// A protocol cannot conform to itself if it has static members.
if (!vd->isInstanceMember())
return false;
}
}
// Check whether any of the inherited protocols fail to conform to themselves.
for (auto proto : decl->getInheritedProtocols()) {
if (!proto->existentialConformsToSelf())
return false;
}
return true;
}
ArrayRef<AssociatedTypeDecl *>
PrimaryAssociatedTypesRequest::evaluate(Evaluator &evaluator,
ProtocolDecl *decl) const {
SmallVector<AssociatedTypeDecl *, 2> assocTypes;
if (decl->hasLazyPrimaryAssociatedTypes()) {
auto &ctx = decl->getASTContext();
auto contextData = static_cast<LazyProtocolData *>(
ctx.getOrCreateLazyContextData(decl, nullptr));
contextData->loader->loadPrimaryAssociatedTypes(
decl, contextData->primaryAssociatedTypesData, assocTypes);
return decl->getASTContext().AllocateCopy(assocTypes);
}
llvm::SmallDenseSet<Identifier, 2> assocTypeNames;
for (auto pair : decl->getPrimaryAssociatedTypeNames()) {
if (!assocTypeNames.insert(pair.first).second) {
auto &ctx = decl->getASTContext();
ctx.Diags.diagnose(pair.second,
diag::protocol_declares_duplicate_primary_assoc_type,
pair.first);
continue;
}
SmallVector<ValueDecl *, 2> result;
decl->lookupQualified(ArrayRef<NominalTypeDecl *>(decl),
DeclNameRef(pair.first), decl->getLoc(),
NL_QualifiedDefault | NL_OnlyTypes,
result);
AssociatedTypeDecl *bestAssocType = nullptr;
for (auto *decl : result) {
if (auto *assocType = dyn_cast<AssociatedTypeDecl>(decl)) {
if (bestAssocType == nullptr ||
TypeDecl::compare(assocType, bestAssocType) < 0) {
bestAssocType = assocType;
}
}
}
if (bestAssocType == nullptr) {
auto &ctx = decl->getASTContext();
ctx.Diags.diagnose(pair.second,
diag::protocol_declares_unknown_primary_assoc_type,
pair.first, decl->getDeclaredInterfaceType());
continue;
}
assocTypes.push_back(bestAssocType);
}
return decl->getASTContext().AllocateCopy(assocTypes);
}
bool
IsFinalRequest::evaluate(Evaluator &evaluator, ValueDecl *decl) const {
auto explicitFinalAttr = decl->getAttrs().getAttribute<FinalAttr>();
if (isa<ClassDecl>(decl))
return explicitFinalAttr;
auto cls = decl->getDeclContext()->getSelfClassDecl();
if (!cls)
return false;
switch (decl->getKind()) {
case DeclKind::Var: {
// Properties are final if they are declared 'static' or a 'let'
auto *VD = cast<VarDecl>(decl);
// Backing storage for 'lazy' or property wrappers is always final.
if (VD->isLazyStorageProperty() ||
VD->getOriginalWrappedProperty(PropertyWrapperSynthesizedPropertyKind::Backing))
return true;
// Property wrapper storage wrappers are final if the original property
// is final.
if (auto *original = VD->getOriginalWrappedProperty(
PropertyWrapperSynthesizedPropertyKind::Projection)) {
if (original->isFinal())
return true;
}
if (VD->getDeclContext()->getSelfClassDecl()) {
// If this variable is a class member, mark it final if the
// class is final, or if it was declared with 'let'.
auto *PBD = VD->getParentPatternBinding();
if (PBD && inferFinalAndDiagnoseIfNeeded(decl, cls, explicitFinalAttr,
PBD->getStaticSpelling()))
return true;
if (VD->isLet()) {
// If this `let` is in an `@_objcImplementation extension`, don't
// infer `final` unless it is written explicitly.
auto ed = dyn_cast<ExtensionDecl>(VD->getDeclContext());
if (!explicitFinalAttr && ed && ed->isObjCImplementation())
return false;
if (VD->getFormalAccess() == AccessLevel::Open) {
auto &context = decl->getASTContext();
auto diagID = diag::implicitly_final_cannot_be_open;
if (!context.isSwiftVersionAtLeast(5))
diagID = diag::implicitly_final_cannot_be_open_swift4;
auto inFlightDiag =
context.Diags.diagnose(decl, diagID,
static_cast<unsigned>(ImplicitlyFinalReason::Let));
fixItAccess(inFlightDiag, decl, AccessLevel::Public);
}
return true;
}
}
break;
}
case DeclKind::Func: {
// Methods declared 'static' are final.
auto staticSpelling = cast<FuncDecl>(decl)->getStaticSpelling();
if (inferFinalAndDiagnoseIfNeeded(decl, cls, explicitFinalAttr,
staticSpelling))
return true;
break;
}
case DeclKind::Accessor:
if (auto accessor = dyn_cast<AccessorDecl>(decl)) {
switch (accessor->getAccessorKind()) {
case AccessorKind::DidSet:
case AccessorKind::WillSet:
// Observing accessors are marked final if in a class.
return true;
case AccessorKind::Read:
case AccessorKind::Modify:
case AccessorKind::Get:
case AccessorKind::DistributedGet:
case AccessorKind::Set: {
// Coroutines and accessors are final if their storage is.
auto storage = accessor->getStorage();
if (storage->isFinal())
return true;
break;
}
default:
break;
}
}
break;
case DeclKind::Subscript: {
// Member subscripts.
auto staticSpelling = cast<SubscriptDecl>(decl)->getStaticSpelling();
if (inferFinalAndDiagnoseIfNeeded(decl, cls, explicitFinalAttr,
staticSpelling))
return true;
break;
}
default:
break;
}
return explicitFinalAttr;
}
bool
IsStaticRequest::evaluate(Evaluator &evaluator, FuncDecl *decl) const {
if (auto *accessor = dyn_cast<AccessorDecl>(decl))
return accessor->getStorage()->isStatic();
bool result = (decl->getStaticLoc().isValid() ||
decl->getStaticSpelling() != StaticSpellingKind::None);
auto *dc = decl->getDeclContext();
if (!result &&
decl->isOperator() &&
dc->isTypeContext()) {
const auto operatorName = decl->getBaseIdentifier();
if (auto ED = dyn_cast<ExtensionDecl>(dc->getAsDecl())) {
decl->diagnose(diag::nonstatic_operator_in_extension, operatorName,
ED->getExtendedTypeRepr() != nullptr,
ED->getExtendedTypeRepr())
.fixItInsert(decl->getAttributeInsertionLoc(/*forModifier=*/true),
"static ");
} else {
auto *NTD = cast<NominalTypeDecl>(dc->getAsDecl());
decl->diagnose(diag::nonstatic_operator_in_nominal, operatorName, NTD)
.fixItInsert(decl->getAttributeInsertionLoc(/*forModifier=*/true),
"static ");
}
result = true;
}
return result;
}
bool
IsDynamicRequest::evaluate(Evaluator &evaluator, ValueDecl *decl) const {
// If we can't infer dynamic here, don't.
if (!DeclAttribute::canAttributeAppearOnDecl(DeclAttrKind::Dynamic, decl))
return false;
// Add dynamic if -enable-implicit-dynamic was requested.
TypeChecker::addImplicitDynamicAttribute(decl);
// If 'dynamic' was explicitly specified, check it.
if (decl->getAttrs().hasAttribute<DynamicAttr>()) {
return true;
}
if (auto accessor = dyn_cast<AccessorDecl>(decl)) {
// Runtime-replaceable accessors are dynamic when their storage declaration
// is dynamic and they were explicitly defined or they are implicitly defined
// getter/setter because no accessor was defined.
return doesAccessorNeedDynamicAttribute(accessor);
}
// The 'NSManaged' attribute implies 'dynamic'.
// FIXME: Use a semantic check for NSManaged rather than looking for the
// attribute (which could be ill-formed).
if (decl->getAttrs().hasAttribute<NSManagedAttr>())
return true;
// The presence of 'final' blocks the inference of 'dynamic'.
if (decl->isSemanticallyFinal())
return false;
// Types are never 'dynamic'.
if (isa<TypeDecl>(decl))
return false;
// A non-@objc entity is never 'dynamic'.
if (!decl->isObjC())
return false;
// @objc declarations in class extensions are implicitly dynamic.
// This is intended to enable overriding the declarations.
auto dc = decl->getDeclContext();
if (isa<ExtensionDecl>(dc) && dc->getSelfClassDecl())
return true;
// If any of the declarations overridden by this declaration are dynamic
// or were imported from Objective-C, this declaration is dynamic.
// Don't do this if the declaration is not exposed to Objective-C; that's
// currently the (only) manner in which one can make an override of a
// dynamic declaration non-dynamic.
auto overriddenDecls = evaluateOrDefault(evaluator,
OverriddenDeclsRequest{decl}, {});
for (auto overridden : overriddenDecls) {
if (overridden->isDynamic() || overridden->hasClangNode())
return true;
}
return false;
}
Type
DefaultDefinitionTypeRequest::evaluate(Evaluator &evaluator,