/
TypeCheckDecl.cpp
5693 lines (4820 loc) · 198 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 "CodeSynthesis.h"
#include "ConstraintSystem.h"
#include "DerivedConformances.h"
#include "TypeChecker.h"
#include "TypeCheckAccess.h"
#include "TypeCheckType.h"
#include "MiscDiagnostics.h"
#include "swift/AST/AccessScope.h"
#include "swift/AST/ASTPrinter.h"
#include "swift/AST/ASTVisitor.h"
#include "swift/AST/ASTWalker.h"
#include "swift/AST/ExistentialLayout.h"
#include "swift/AST/Expr.h"
#include "swift/AST/ForeignErrorConvention.h"
#include "swift/AST/GenericEnvironment.h"
#include "swift/AST/GenericSignatureBuilder.h"
#include "swift/AST/NameLookup.h"
#include "swift/AST/PrettyStackTrace.h"
#include "swift/AST/ProtocolConformance.h"
#include "swift/AST/ReferencedNameTracker.h"
#include "swift/AST/TypeWalker.h"
#include "swift/Basic/Statistic.h"
#include "swift/Parse/Lexer.h"
#include "swift/Parse/Parser.h"
#include "swift/Serialization/SerializedModuleLoader.h"
#include "swift/Strings.h"
#include "swift/AST/TypeCheckRequests.h"
#include "swift/Basic/Defer.h"
#include "llvm/ADT/APFloat.h"
#include "llvm/ADT/APInt.h"
#include "llvm/ADT/APSInt.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, 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;
uint32_t charValue;
IntValueTy intValue;
FloatValueTy floatValue;
};
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;
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:
// FIXME: DJB seed=0, audit whether the default seed could be used.
return llvm::djbHash(k.stringValue, 0);
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.equals(b.stringValue);
case RawValueKey::Kind::Empty:
case RawValueKey::Kind::Tombstone:
return true;
}
llvm_unreachable("Unhandled RawValueKey in switch.");
}
};
} // namespace llvm
/// Check that the declaration attributes are ok.
static void validateAttributes(TypeChecker &TC, Decl *D);
/// Check the inheritance clause of a type declaration or extension thereof.
///
/// This routine performs detailed checking of the inheritance clause of the
/// given type or extension. It need only be called within the primary source
/// file.
static void checkInheritanceClause(
llvm::PointerUnion<TypeDecl *, ExtensionDecl *> declUnion) {
TypeResolutionOptions options = None;
DeclContext *DC;
MutableArrayRef<TypeLoc> inheritedClause;
ExtensionDecl *ext = nullptr;
TypeDecl *typeDecl = nullptr;
Decl *decl;
if ((ext = declUnion.dyn_cast<ExtensionDecl *>())) {
decl = ext;
DC = ext;
options |= TypeResolutionFlags::AllowUnavailableProtocol;
inheritedClause = ext->getInherited();
// Protocol extensions cannot have inheritance clauses.
if (auto proto = ext->getExtendedProtocolDecl()) {
if (!inheritedClause.empty()) {
ext->diagnose(diag::extension_protocol_inheritance,
proto->getName())
.highlight(SourceRange(inheritedClause.front().getSourceRange().Start,
inheritedClause.back().getSourceRange().End));
return;
}
}
} else {
typeDecl = declUnion.get<TypeDecl *>();
decl = typeDecl;
if (auto nominal = dyn_cast<NominalTypeDecl>(typeDecl)) {
DC = nominal;
options |= TypeResolutionFlags::AllowUnavailableProtocol;
} else {
DC = typeDecl->getDeclContext();
}
inheritedClause = typeDecl->getInherited();
}
ASTContext &ctx = decl->getASTContext();
auto &diags = ctx.Diags;
// Retrieve the location of the start of the inheritance clause.
auto getStartLocOfInheritanceClause = [&] {
if (ext)
return ext->getSourceRange().End;
if (auto genericTypeDecl = dyn_cast<GenericTypeDecl>(typeDecl)) {
if (auto genericParams = genericTypeDecl->getGenericParams())
return genericParams->getSourceRange().End;
return genericTypeDecl->getNameLoc();
}
return typeDecl->getNameLoc();
};
// Compute the source range to be used when removing something from an
// inheritance clause.
auto getRemovalRange = [&](unsigned i) {
// If there is just one entry, remove the entire inheritance clause.
if (inheritedClause.size() == 1) {
SourceLoc start = getStartLocOfInheritanceClause();
SourceLoc end = inheritedClause[i].getSourceRange().End;
return SourceRange(Lexer::getLocForEndOfToken(ctx.SourceMgr, start),
Lexer::getLocForEndOfToken(ctx.SourceMgr, end));
}
// If we're at the first entry, remove from the start of this entry to the
// start of the next entry.
if (i == 0) {
return SourceRange(inheritedClause[i].getSourceRange().Start,
inheritedClause[i+1].getSourceRange().Start);
}
// Otherwise, remove from the end of the previous entry to the end of this
// entry.
SourceLoc afterPriorLoc =
Lexer::getLocForEndOfToken(ctx.SourceMgr,
inheritedClause[i-1].getSourceRange().End);
SourceLoc afterMyEndLoc =
Lexer::getLocForEndOfToken(ctx.SourceMgr,
inheritedClause[i].getSourceRange().End);
return SourceRange(afterPriorLoc, afterMyEndLoc);
};
// Check all of the types listed in the inheritance clause.
Type superclassTy;
SourceRange superclassRange;
Optional<std::pair<unsigned, SourceRange>> inheritedAnyObject;
for (unsigned i = 0, n = inheritedClause.size(); i != n; ++i) {
auto &inherited = inheritedClause[i];
// Validate the type.
InheritedTypeRequest request{declUnion, i, TypeResolutionStage::Interface};
Type inheritedTy = evaluateOrDefault(ctx.evaluator, request, Type());
// If we couldn't resolve an the inherited type, or it contains an error,
// ignore it.
if (!inheritedTy || inheritedTy->hasError())
continue;
// Check whether we inherited from 'AnyObject' twice.
// Other redundant-inheritance scenarios are checked below, the
// GenericSignatureBuilder (for protocol inheritance) or the
// ConformanceLookupTable (for protocol conformance).
if (inheritedTy->isAnyObject()) {
if (inheritedAnyObject) {
// If the first occurrence was written as 'class', downgrade the error
// to a warning in such case for backward compatibility with
// Swift <= 4.
auto knownIndex = inheritedAnyObject->first;
auto knownRange = inheritedAnyObject->second;
SourceRange removeRange = getRemovalRange(knownIndex);
if (!ctx.LangOpts.isSwiftVersionAtLeast(5) &&
(isa<ProtocolDecl>(decl) || isa<AbstractTypeParamDecl>(decl)) &&
Lexer::getTokenAtLocation(ctx.SourceMgr, knownRange.Start)
.is(tok::kw_class)) {
SourceLoc classLoc = knownRange.Start;
diags.diagnose(classLoc, diag::duplicate_anyobject_class_inheritance)
.fixItRemoveChars(removeRange.Start, removeRange.End);
} else {
diags.diagnose(inherited.getSourceRange().Start,
diag::duplicate_inheritance, inheritedTy)
.fixItRemoveChars(removeRange.Start, removeRange.End);
}
continue;
}
// Note that we saw inheritance from 'AnyObject'.
inheritedAnyObject = { i, inherited.getSourceRange() };
}
if (inheritedTy->isExistentialType()) {
auto layout = inheritedTy->getExistentialLayout();
// @objc protocols cannot have superclass constraints.
if (layout.explicitSuperclass) {
if (auto *protoDecl = dyn_cast<ProtocolDecl>(decl)) {
if (protoDecl->isObjC()) {
protoDecl->diagnose(diag::objc_protocol_with_superclass,
protoDecl->getName());
continue;
}
}
}
// Protocols, generic parameters and associated types can inherit
// from subclass existentials, which are "exploded" into their
// corresponding requirements.
//
// Extensions, structs and enums can only inherit from protocol
// compositions that do not contain AnyObject or class members.
if (isa<ProtocolDecl>(decl) ||
isa<AbstractTypeParamDecl>(decl) ||
(!layout.hasExplicitAnyObject &&
!layout.explicitSuperclass)) {
continue;
}
// Classes can inherit from subclass existentials as long as they
// do not contain an explicit AnyObject member.
if (isa<ClassDecl>(decl) &&
!layout.hasExplicitAnyObject) {
// Superclass inheritance is handled below.
inheritedTy = layout.explicitSuperclass;
if (!inheritedTy)
continue;
}
}
// If this is an enum inheritance clause, check for a raw type.
if (isa<EnumDecl>(decl)) {
// Check if we already had a raw type.
if (superclassTy) {
if (superclassTy->isEqual(inheritedTy)) {
auto removeRange = getRemovalRange(i);
diags.diagnose(inherited.getSourceRange().Start,
diag::duplicate_inheritance, inheritedTy)
.fixItRemoveChars(removeRange.Start, removeRange.End);
} else {
diags.diagnose(inherited.getSourceRange().Start,
diag::multiple_enum_raw_types, superclassTy,
inheritedTy)
.highlight(superclassRange);
}
continue;
}
// If this is not the first entry in the inheritance clause, complain.
if (i > 0) {
auto removeRange = getRemovalRange(i);
diags.diagnose(inherited.getSourceRange().Start,
diag::raw_type_not_first, inheritedTy)
.fixItRemoveChars(removeRange.Start, removeRange.End)
.fixItInsert(inheritedClause[0].getSourceRange().Start,
inheritedTy.getString() + ", ");
// Fall through to record the raw type.
}
// Record the raw type.
superclassTy = inheritedTy;
superclassRange = inherited.getSourceRange();
continue;
}
// If this is a class type, it may be the superclass.
if (inheritedTy->getClassOrBoundGenericClass()) {
// First, check if we already had a superclass.
if (superclassTy) {
// FIXME: Check for shadowed protocol names, i.e., NSObject?
if (superclassTy->isEqual(inheritedTy)) {
// Duplicate superclass.
auto removeRange = getRemovalRange(i);
diags.diagnose(inherited.getSourceRange().Start,
diag::duplicate_inheritance, inheritedTy)
.fixItRemoveChars(removeRange.Start, removeRange.End);
} else {
// Complain about multiple inheritance.
// Don't emit a Fix-It here. The user has to think harder about this.
diags.diagnose(inherited.getSourceRange().Start,
diag::multiple_inheritance, superclassTy, inheritedTy)
.highlight(superclassRange);
}
continue;
}
// @objc protocols cannot have superclass constraints.
if (auto *protoDecl = dyn_cast<ProtocolDecl>(decl)) {
if (protoDecl->isObjC()) {
protoDecl->diagnose(diag::objc_protocol_with_superclass,
protoDecl->getName());
continue;
}
}
// If the declaration we're looking at doesn't allow a superclass,
// complain.
if (isa<StructDecl>(decl) || isa<ExtensionDecl>(decl)) {
decl->diagnose(isa<ExtensionDecl>(decl)
? diag::extension_class_inheritance
: diag::non_class_inheritance,
isa<ExtensionDecl>(decl)
? cast<ExtensionDecl>(decl)->getDeclaredInterfaceType()
: cast<TypeDecl>(decl)->getDeclaredInterfaceType(),
inheritedTy)
.highlight(inherited.getSourceRange());
continue;
}
// If this is not the first entry in the inheritance clause, complain.
if (isa<ClassDecl>(decl) && i > 0) {
auto removeRange = getRemovalRange(i);
diags.diagnose(inherited.getSourceRange().Start,
diag::superclass_not_first, inheritedTy)
.fixItRemoveChars(removeRange.Start, removeRange.End)
.fixItInsert(inheritedClause[0].getSourceRange().Start,
inheritedTy.getString() + ", ");
// Fall through to record the superclass.
}
// Record the superclass.
superclassTy = inheritedTy;
superclassRange = inherited.getSourceRange();
continue;
}
// The GenericSignatureBuilder diagnoses problems with generic type
// parameters.
if (isa<GenericTypeParamDecl>(decl))
continue;
// We can't inherit from a non-class, non-protocol type.
decl->diagnose((isa<StructDecl>(decl) || isa<ExtensionDecl>(decl))
? diag::inheritance_from_non_protocol
: diag::inheritance_from_non_protocol_or_class,
inheritedTy);
// FIXME: Note pointing to the declaration 'inheritedTy' references?
}
}
/// Check the inheritance clauses generic parameters along with any
/// requirements stored within the generic parameter list.
static void checkGenericParams(GenericParamList *genericParams,
DeclContext *owningDC) {
if (!genericParams)
return;
for (auto gp : *genericParams) {
checkInheritanceClause(gp);
}
// Force visitation of each of the requirements here.
RequirementRequest::visitRequirements(WhereClauseOwner(owningDC,
genericParams),
TypeResolutionStage::Interface,
[](Requirement, RequirementRepr *) {
return false;
});
}
/// Retrieve the set of protocols the given protocol inherits.
static llvm::TinyPtrVector<ProtocolDecl *>
getInheritedForCycleCheck(TypeChecker &tc,
ProtocolDecl *proto,
ProtocolDecl **scratch) {
TinyPtrVector<ProtocolDecl *> result;
bool anyObject = false;
for (const auto &found :
getDirectlyInheritedNominalTypeDecls(proto, anyObject)) {
if (auto protoDecl = dyn_cast<ProtocolDecl>(found.second))
result.push_back(protoDecl);
}
return result;
}
/// Retrieve the superclass of the given class.
static ArrayRef<ClassDecl *> getInheritedForCycleCheck(TypeChecker &tc,
ClassDecl *classDecl,
ClassDecl **scratch) {
if (classDecl->hasSuperclass()) {
*scratch = classDecl->getSuperclassDecl();
return *scratch;
}
return { };
}
/// Retrieve the raw type of the given enum.
static ArrayRef<EnumDecl *> getInheritedForCycleCheck(TypeChecker &tc,
EnumDecl *enumDecl,
EnumDecl **scratch) {
if (enumDecl->hasRawType()) {
*scratch = enumDecl->getRawType()->getEnumOrBoundGenericEnum();
return *scratch ? ArrayRef<EnumDecl*>(*scratch) : ArrayRef<EnumDecl*>{};
}
return { };
}
/// Check for circular inheritance.
template<typename T>
static void checkCircularity(TypeChecker &tc, T *decl,
Diag<Identifier> circularDiag,
DescriptiveDeclKind declKind,
SmallVectorImpl<T *> &path) {
switch (decl->getCircularityCheck()) {
case CircularityCheck::Checked:
return;
case CircularityCheck::Checking: {
// We're already checking this type, which means we have a cycle.
// The beginning of the path might not be part of the cycle, so find
// where the cycle starts.
assert(!path.empty());
auto cycleStart = path.end() - 1;
while (*cycleStart != decl) {
assert(cycleStart != path.begin() && "Missing cycle start?");
--cycleStart;
}
// If the path length is 1 the type directly references itself.
if (path.end() - cycleStart == 1) {
tc.diagnose(path.back()->getLoc(),
circularDiag,
path.back()->getName());
break;
}
// Diagnose the cycle.
tc.diagnose(decl->getLoc(), circularDiag,
(*cycleStart)->getName());
for (auto i = cycleStart + 1, iEnd = path.end(); i != iEnd; ++i) {
tc.diagnose(*i, diag::kind_identifier_declared_here,
declKind, (*i)->getName());
}
break;
}
case CircularityCheck::Unchecked: {
// Walk to the inherited class or protocols.
path.push_back(decl);
decl->setCircularityCheck(CircularityCheck::Checking);
T *scratch = nullptr;
for (auto inherited : getInheritedForCycleCheck(tc, decl, &scratch)) {
checkCircularity(tc, inherited, circularDiag, declKind, path);
}
decl->setCircularityCheck(CircularityCheck::Checked);
path.pop_back();
break;
}
}
}
/// Set each bound variable in the pattern to have an error type.
static void setBoundVarsTypeError(Pattern *pattern, ASTContext &ctx) {
pattern->forEachVariable([&](VarDecl *var) {
// Don't change the type of a variable that we've been able to
// compute a type for.
if (var->hasType() && !var->getType()->hasError())
return;
var->markInvalid();
});
}
/// Expose TypeChecker's handling of GenericParamList to SIL parsing.
GenericEnvironment *
TypeChecker::handleSILGenericParams(GenericParamList *genericParams,
DeclContext *DC) {
SmallVector<GenericParamList *, 2> nestedList;
for (; genericParams; genericParams = genericParams->getOuterParameters()) {
nestedList.push_back(genericParams);
}
// Since the innermost GenericParamList is in the beginning of the vector,
// we process in reverse order to handle the outermost list first.
GenericSignature *parentSig = nullptr;
GenericEnvironment *parentEnv = nullptr;
for (unsigned i = 0, e = nestedList.size(); i < e; i++) {
auto genericParams = nestedList.rbegin()[i];
prepareGenericParamList(genericParams, DC);
parentEnv = checkGenericEnvironment(genericParams, DC, parentSig,
/*allowConcreteGenericParams=*/true,
/*ext=*/nullptr);
parentSig = parentEnv->getGenericSignature();
}
return parentEnv;
}
/// Build a default initializer for the given type.
static Expr *buildDefaultInitializer(TypeChecker &tc, Type type) {
// Default-initialize optional types and weak values to 'nil'.
if (type->getReferenceStorageReferent()->getOptionalObjectType())
return new (tc.Context) NilLiteralExpr(SourceLoc(), /*Implicit=*/true);
// Build tuple literals for tuple types.
if (auto tupleType = type->getAs<TupleType>()) {
SmallVector<Expr *, 2> inits;
for (const auto &elt : tupleType->getElements()) {
if (elt.isVararg())
return nullptr;
auto eltInit = buildDefaultInitializer(tc, elt.getType());
if (!eltInit)
return nullptr;
inits.push_back(eltInit);
}
return TupleExpr::createImplicit(tc.Context, inits, { });
}
// We don't default-initialize anything else.
return nullptr;
}
/// Check whether \c current is a redeclaration.
static void checkRedeclaration(TypeChecker &tc, ValueDecl *current) {
// If we've already checked this declaration, don't do it again.
if (current->alreadyCheckedRedeclaration())
return;
// If there's no type yet, come back to it later.
if (!current->hasInterfaceType())
return;
// Make sure we don't do this checking again.
current->setCheckedRedeclaration(true);
// Ignore invalid and anonymous declarations.
if (current->isInvalid() || !current->hasName())
return;
// If this declaration isn't from a source file, don't check it.
// FIXME: Should restrict this to the source file we care about.
DeclContext *currentDC = current->getDeclContext();
SourceFile *currentFile = currentDC->getParentSourceFile();
if (!currentFile || currentDC->isLocalContext())
return;
ReferencedNameTracker *tracker = currentFile->getReferencedNameTracker();
bool isCascading = (current->getFormalAccess() > AccessLevel::FilePrivate);
// Find other potential definitions.
SmallVector<ValueDecl *, 4> otherDefinitions;
if (currentDC->isTypeContext()) {
// Look within a type context.
if (auto nominal = currentDC->getSelfNominalTypeDecl()) {
auto found = nominal->lookupDirect(current->getBaseName());
otherDefinitions.append(found.begin(), found.end());
if (tracker)
tracker->addUsedMember({nominal, current->getBaseName()}, isCascading);
}
} else {
// Look within a module context.
currentFile->getParentModule()->lookupValue({ }, current->getBaseName(),
NLKind::QualifiedLookup,
otherDefinitions);
if (tracker)
tracker->addTopLevelName(current->getBaseName(), isCascading);
}
// Compare this signature against the signature of other
// declarations with the same name.
OverloadSignature currentSig = current->getOverloadSignature();
CanType currentSigType = current->getOverloadSignatureType();
ModuleDecl *currentModule = current->getModuleContext();
for (auto other : otherDefinitions) {
// Skip invalid declarations and ourselves.
if (current == other || other->isInvalid())
continue;
// Skip declarations in other modules.
if (currentModule != other->getModuleContext())
continue;
// Don't compare methods vs. non-methods (which only happens with
// operators).
if (currentDC->isTypeContext() != other->getDeclContext()->isTypeContext())
continue;
// Check whether the overload signatures conflict (ignoring the type for
// now).
auto otherSig = other->getOverloadSignature();
if (!conflicting(currentSig, otherSig))
continue;
// Validate the declaration but only if it came from a different context.
if (other->getDeclContext() != current->getDeclContext())
tc.validateDecl(other);
// Skip invalid or not yet seen declarations.
if (other->isInvalid() || !other->hasInterfaceType())
continue;
// Skip declarations in other files.
// In practice, this means we will warn on a private declaration that
// shadows a non-private one, but only in the file where the shadowing
// happens. We will warn on conflicting non-private declarations in both
// files.
if (!other->isAccessibleFrom(currentDC))
continue;
const auto markInvalid = [¤t]() {
current->setInvalid();
if (auto *varDecl = dyn_cast<VarDecl>(current))
if (varDecl->hasType())
varDecl->setType(ErrorType::get(varDecl->getType()));
if (current->hasInterfaceType())
current->setInterfaceType(ErrorType::get(current->getInterfaceType()));
};
// Thwart attempts to override the same declaration more than once.
const auto *currentOverride = current->getOverriddenDecl();
const auto *otherOverride = other->getOverriddenDecl();
if (currentOverride && currentOverride == otherOverride) {
tc.diagnose(current, diag::multiple_override, current->getFullName());
tc.diagnose(other, diag::multiple_override_prev, other->getFullName());
markInvalid();
break;
}
// Get the overload signature type.
CanType otherSigType = other->getOverloadSignatureType();
bool wouldBeSwift5Redeclaration = false;
auto isRedeclaration = conflicting(tc.Context, currentSig, currentSigType,
otherSig, otherSigType,
&wouldBeSwift5Redeclaration);
// If there is another conflict, complain.
if (isRedeclaration || wouldBeSwift5Redeclaration) {
// If the two declarations occur in the same source file, make sure
// we get the diagnostic ordering to be sensible.
if (auto otherFile = other->getDeclContext()->getParentSourceFile()) {
if (currentFile == otherFile &&
current->getLoc().isValid() &&
other->getLoc().isValid() &&
tc.Context.SourceMgr.isBeforeInBuffer(current->getLoc(),
other->getLoc())) {
std::swap(current, other);
}
}
// If we're currently looking at a .sil and the conflicting declaration
// comes from a .sib, don't error since we won't be considering the sil
// from the .sib. So it's fine for the .sil to shadow it, since that's the
// one we want.
if (currentFile->Kind == SourceFileKind::SIL) {
auto *otherFile = dyn_cast<SerializedASTFile>(
other->getDeclContext()->getModuleScopeContext());
if (otherFile && otherFile->isSIB())
continue;
}
// If the conflicting declarations have non-overlapping availability and,
// we allow the redeclaration to proceed if...
//
// - they are initializers with different failability,
bool isAcceptableVersionBasedChange = false;
{
const auto *currentInit = dyn_cast<ConstructorDecl>(current);
const auto *otherInit = dyn_cast<ConstructorDecl>(other);
if (currentInit && otherInit &&
((currentInit->getFailability() == OTK_None) !=
(otherInit->getFailability() == OTK_None))) {
isAcceptableVersionBasedChange = true;
}
}
// - one throws and the other does not,
{
const auto *currentAFD = dyn_cast<AbstractFunctionDecl>(current);
const auto *otherAFD = dyn_cast<AbstractFunctionDecl>(other);
if (currentAFD && otherAFD &&
currentAFD->hasThrows() != otherAFD->hasThrows()) {
isAcceptableVersionBasedChange = true;
}
}
// - or they are computed properties of different types,
{
const auto *currentVD = dyn_cast<VarDecl>(current);
const auto *otherVD = dyn_cast<VarDecl>(other);
if (currentVD && otherVD &&
!currentVD->hasStorage() &&
!otherVD->hasStorage() &&
!currentVD->getInterfaceType()->isEqual(
otherVD->getInterfaceType())) {
isAcceptableVersionBasedChange = true;
}
}
if (isAcceptableVersionBasedChange) {
class AvailabilityRange {
Optional<llvm::VersionTuple> introduced;
Optional<llvm::VersionTuple> obsoleted;
public:
static AvailabilityRange from(const ValueDecl *VD) {
AvailabilityRange result;
for (auto *attr : VD->getAttrs().getAttributes<AvailableAttr>()) {
if (attr->PlatformAgnostic ==
PlatformAgnosticAvailabilityKind::SwiftVersionSpecific) {
if (attr->Introduced)
result.introduced = attr->Introduced;
if (attr->Obsoleted)
result.obsoleted = attr->Obsoleted;
}
}
return result;
}
bool fullyPrecedes(const AvailabilityRange &other) const {
if (!obsoleted.hasValue())
return false;
if (!other.introduced.hasValue())
return false;
return *obsoleted <= *other.introduced;
}
bool overlaps(const AvailabilityRange &other) const {
return !fullyPrecedes(other) && !other.fullyPrecedes(*this);
}
};
auto currentAvail = AvailabilityRange::from(current);
auto otherAvail = AvailabilityRange::from(other);
if (!currentAvail.overlaps(otherAvail))
continue;
}
// If both are VarDecls, and both have exactly the same type, then
// matching the Swift 4 behaviour (i.e. just emitting the future-compat
// warning) will result in SILGen crashes due to both properties mangling
// the same, so it's better to just follow the Swift 5 behaviour and emit
// the actual error.
if (wouldBeSwift5Redeclaration && isa<VarDecl>(current) &&
isa<VarDecl>(other) &&
current->getInterfaceType()->isEqual(other->getInterfaceType())) {
wouldBeSwift5Redeclaration = false;
}
// If this isn't a redeclaration in the current version of Swift, but
// would be in Swift 5 mode, emit a warning instead of an error.
if (wouldBeSwift5Redeclaration) {
tc.diagnose(current, diag::invalid_redecl_swift5_warning,
current->getFullName());
tc.diagnose(other, diag::invalid_redecl_prev, other->getFullName());
} else {
tc.diagnose(current, diag::invalid_redecl, current->getFullName());
tc.diagnose(other, diag::invalid_redecl_prev, other->getFullName());
markInvalid();
}
// Make sure we don't do this checking again for the same decl. We also
// set this at the beginning of the function, but we might have swapped
// the decls for diagnostics; so ensure we also set this for the actual
// decl we diagnosed on.
current->setCheckedRedeclaration(true);
break;
}
}
}
/// Does the context allow pattern bindings that don't bind any variables?
static bool contextAllowsPatternBindingWithoutVariables(DeclContext *dc) {
// Property decls in type context must bind variables.
if (dc->isTypeContext())
return false;
// Global variable decls must bind variables, except in scripts.
if (dc->isModuleScopeContext()) {
if (dc->getParentSourceFile()
&& dc->getParentSourceFile()->isScriptMode())
return true;
return false;
}
return true;
}
/// Validate the \c entryNumber'th entry in \c binding.
static void validatePatternBindingEntry(TypeChecker &tc,
PatternBindingDecl *binding,
unsigned entryNumber) {
// If the pattern already has a type, we're done.
if (binding->getPattern(entryNumber)->hasType())
return;
// Resolve the pattern.
auto *pattern = tc.resolvePattern(binding->getPattern(entryNumber),
binding->getDeclContext(),
/*isStmtCondition*/true);
if (!pattern) {
binding->setInvalid();
binding->getPattern(entryNumber)->setType(ErrorType::get(tc.Context));
return;
}
binding->setPattern(entryNumber, pattern,
binding->getPatternList()[entryNumber].getInitContext());
// Validate 'static'/'class' on properties in nominal type decls.
auto StaticSpelling = binding->getStaticSpelling();
if (StaticSpelling != StaticSpellingKind::None &&
isa<ExtensionDecl>(binding->getDeclContext())) {
if (auto *NTD = binding->getDeclContext()->getSelfNominalTypeDecl()) {
if (!isa<ClassDecl>(NTD)) {
if (StaticSpelling == StaticSpellingKind::KeywordClass) {
tc.diagnose(binding, diag::class_var_not_in_class, false)
.fixItReplace(binding->getStaticLoc(), "static");
tc.diagnose(NTD, diag::extended_type_declared_here);
}
}
}
}
// Check the pattern. We treat type-checking a PatternBindingDecl like
// type-checking an expression because that's how the initial binding is
// checked, and they have the same effect on the file's dependencies.
//
// In particular, it's /not/ correct to check the PBD's DeclContext because
// top-level variables in a script file are accessible from other files,
// even though the PBD is inside a TopLevelCodeDecl.
TypeResolutionOptions options(TypeResolverContext::PatternBindingDecl);
if (binding->getInit(entryNumber)) {
// If we have an initializer, we can also have unknown types.
options |= TypeResolutionFlags::AllowUnspecifiedTypes;
options |= TypeResolutionFlags::AllowUnboundGenerics;
}