-
Notifications
You must be signed in to change notification settings - Fork 10.4k
/
Copy pathTypeCheckDeclPrimary.cpp
4432 lines (3775 loc) · 160 KB
/
TypeCheckDeclPrimary.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
//===--- TypeCheckDeclPrimary.cpp - Type Checking for Primary Files -------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2020 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 type checking for primary files, that is, files whose
// declarations we're planning to emit. This exhaustively triggers diagnostics
// and type checking of all delayed bodies in those files.
//
//===----------------------------------------------------------------------===//
#include "CodeSynthesis.h"
#include "DerivedConformances.h"
#include "MiscDiagnostics.h"
#include "TypeCheckAccess.h"
#include "TypeCheckAvailability.h"
#include "TypeCheckConcurrency.h"
#include "TypeCheckDecl.h"
#include "TypeCheckMacros.h"
#include "TypeCheckObjC.h"
#include "TypeCheckType.h"
#include "TypeCheckUnsafe.h"
#include "TypeChecker.h"
#include "swift/AST/ASTPrinter.h"
#include "swift/AST/ASTVisitor.h"
#include "swift/AST/ASTWalker.h"
#include "swift/AST/AccessNotes.h"
#include "swift/AST/AccessScope.h"
#include "swift/AST/Attr.h"
#include "swift/AST/AvailabilityInference.h"
#include "swift/AST/ConformanceLookup.h"
#include "swift/AST/Decl.h"
#include "swift/AST/DeclContext.h"
#include "swift/AST/DiagnosticsParse.h"
#include "swift/AST/DiagnosticsSema.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/KnownProtocols.h"
#include "swift/AST/MacroDefinition.h"
#include "swift/AST/NameLookup.h"
#include "swift/AST/NameLookupRequests.h"
#include "swift/AST/PrettyStackTrace.h"
#include "swift/AST/PropertyWrappers.h"
#include "swift/AST/ProtocolConformance.h"
#include "swift/AST/SourceFile.h"
#include "swift/AST/TypeCheckRequests.h"
#include "swift/AST/TypeDifferenceVisitor.h"
#include "swift/AST/TypeWalker.h"
#include "swift/AST/UnsafeUse.h"
#include "swift/Basic/Assertions.h"
#include "swift/Basic/Defer.h"
#include "swift/Basic/Statistic.h"
#include "swift/Bridging/MacroEvaluation.h"
#include "swift/Parse/Lexer.h"
#include "swift/Serialization/SerializedModuleLoader.h"
#include "swift/Strings.h"
#include "clang/Basic/Module.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 "TypeCheckDeclPrimary"
static Type containsParameterizedProtocolType(Type inheritedTy) {
if (inheritedTy->is<ParameterizedProtocolType>()) {
return inheritedTy;
}
if (auto *compositionTy = inheritedTy->getAs<ProtocolCompositionType>()) {
for (auto memberTy : compositionTy->getMembers()) {
if (auto paramTy = containsParameterizedProtocolType(memberTy))
return paramTy;
}
}
return Type();
}
class CheckRepressions {
llvm::PointerUnion<const TypeDecl *, const ExtensionDecl *> declUnion;
ASTContext &ctx;
llvm::DenseSet<RepressibleProtocolKind> seen;
public:
CheckRepressions(
llvm::PointerUnion<const TypeDecl *, const ExtensionDecl *> declUnion,
ASTContext &ctx)
: declUnion(declUnion), ctx(ctx) {}
template <typename... ArgTypes>
InFlightDiagnostic diagnoseInvalid(TypeRepr &repr, ArgTypes &&...Args) {
auto &diags = ctx.Diags;
repr.setInvalid();
return diags.diagnose(std::forward<ArgTypes>(Args)...);
}
/// Record the repressed kind indicated by the provided
/// InheritedTypeResult.Suppressed (i.e. \p ty and \p repr) if it is in fact
/// repressed or return the inverted type.
Type add(Type ty, InverseTypeRepr &repr,
llvm::PointerUnion<const TypeDecl *, const ExtensionDecl *> decl) {
if (!ty || ty->hasError())
return Type();
assert(!ty->is<ExistentialMetatypeType>());
auto kp = ty->getKnownProtocol();
if (!kp) {
diagnoseInvalid(repr, repr.getLoc(), diag::inverse_type_not_invertible,
ty);
return Type();
}
auto ipk = getInvertibleProtocolKind(*kp);
if (ipk) {
return ProtocolCompositionType::getInverseOf(ctx, *ipk);
}
auto rpk = getRepressibleProtocolKind(*kp);
if (!rpk) {
diagnoseInvalid(repr, repr.getLoc(),
diag::suppress_nonsuppressable_protocol,
ctx.getProtocol(*kp));
return Type();
}
if (auto *extension = dyn_cast<const ExtensionDecl *>(decl)) {
diagnoseInvalid(repr, extension,
diag::suppress_inferrable_protocol_extension,
ctx.getProtocol(*kp));
return Type();
}
if (!seen.insert(*rpk).second) {
diagnoseInvalid(repr, repr.getLoc(),
diag::suppress_already_suppressed_protocol,
ctx.getProtocol(getKnownProtocolKind(*rpk)));
}
return Type();
}
};
/// If the extension adds a conformance to an invertible protocol, ensure that
/// it does not add a conformance to any other protocol. So these are illegal:
///
/// extension S: Copyable & P {}
/// extension S: Q, Copyable {}
///
/// This policy is in place because extensions adding a conformance to an
/// invertible protocol do _not_ add default requirements on generic parameters,
/// so it would be confusing to mix them together in the same extension.
static void checkExtensionAddsSoloInvertibleProtocol(const ExtensionDecl *ext) {
auto localConfs = ext->getLocalConformances();
if (localConfs.size() <= 1)
return;
for (auto *conf : localConfs) {
if (auto ip = conf->getProtocol()->getInvertibleProtocolKind()) {
ext->diagnose(diag::extension_conforms_to_invertible_and_others,
getInvertibleProtocolKindName(*ip));
}
}
}
/// 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<const TypeDecl *, const ExtensionDecl *> declUnion) {
auto inheritedTypes = InheritedTypes(declUnion);
auto inheritedClause = inheritedTypes.getEntries();
const ExtensionDecl *ext = nullptr;
const TypeDecl *typeDecl = nullptr;
const Decl *decl;
if ((ext = declUnion.dyn_cast<const ExtensionDecl *>())) {
decl = ext;
// 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<const TypeDecl *>();
decl = typeDecl;
}
// Can this declaration's inheritance clause contain a class or
// subclass existential?
bool canHaveSuperclass = (isa<ClassDecl>(decl) ||
(isa<ProtocolDecl>(decl) &&
!cast<ProtocolDecl>(decl)->isObjC()));
ASTContext &ctx = decl->getASTContext();
auto &diags = ctx.Diags;
CheckRepressions checkRepressions(declUnion, ctx);
// Check all of the types listed in the inheritance clause.
Type superclassTy;
SourceRange superclassRange;
std::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};
auto result = evaluateOrDefault(ctx.evaluator, request,
InheritedTypeResult::forDefault());
Type inheritedTy;
switch (result) {
case InheritedTypeResult::Inherited:
inheritedTy = result.getInheritedType();
break;
case InheritedTypeResult::Suppressed: {
auto pair = result.getSuppressed();
auto inverted = checkRepressions.add(pair.first, *pair.second, declUnion);
if (!inverted)
continue;
inheritedTy = inverted;
break;
}
case InheritedTypeResult::Default:
continue;
}
// If we couldn't resolve an the inherited type, or it contains an error,
// ignore it.
if (!inheritedTy || inheritedTy->hasError())
continue;
// For generic parameters and associated types, the GSB checks constraints;
// however, we still want to fire off the requests to produce diagnostics
// in some circular validation cases.
if (isa<GenericTypeParamDecl>(decl) ||
isa<AssociatedTypeDecl>(decl))
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()) {
// Warn inherited AnyObject written as 'class' as deprecated
// for Swift >= 5.
auto sourceRange = inherited.getSourceRange();
bool isWrittenAsClass =
isa<ProtocolDecl>(decl) &&
Lexer::getTokenAtLocation(ctx.SourceMgr, sourceRange.Start)
.is(tok::kw_class);
if (ctx.LangOpts.isSwiftVersionAtLeast(5) && isWrittenAsClass) {
diags
.diagnose(sourceRange.Start,
diag::anyobject_class_inheritance_deprecated)
.fixItReplace(sourceRange, "AnyObject");
}
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 = inheritedTypes.getRemovalRange(knownIndex);
if (!ctx.LangOpts.isSwiftVersionAtLeast(5) &&
isa<ProtocolDecl>(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 (auto paramTy = containsParameterizedProtocolType(inheritedTy)) {
if (!isa<ProtocolDecl>(decl)) {
decl->diagnose(diag::inheritance_from_parameterized_protocol,
paramTy);
}
continue;
}
if (inheritedTy->isConstraintType()) {
auto layout = inheritedTy->getExistentialLayout();
// An inverse on an extension is an error.
if (isa<ExtensionDecl>(decl)) {
auto canInheritedTy = inheritedTy->getCanonicalType();
if (auto pct = canInheritedTy->getAs<ProtocolCompositionType>()) {
for (auto inverse : pct->getInverses()) {
decl->diagnose(diag::inverse_extension,
getProtocolName(getKnownProtocolKind(inverse)));
}
}
}
// Subclass existentials are not allowed except on classes and
// non-@objc protocols.
if (layout.explicitSuperclass &&
!canHaveSuperclass) {
decl->diagnose(diag::inheritance_from_protocol_with_superclass,
inheritedTy);
continue;
}
// Classes and protocols can inherit from subclass existentials.
// For classes, we check for a duplicate superclass below.
// For protocols, the requirement machine emits a requirement
// conflict instead.
if (isa<ProtocolDecl>(decl))
continue;
// AnyObject is not allowed except on protocols.
if (layout.hasExplicitAnyObject && !isa<ClassDecl>(decl)) {
decl->diagnose(diag::inheritance_from_anyobject);
continue;
}
// If the existential did not have a class constraint, we're done.
if (!layout.explicitSuperclass)
continue;
assert(isa<ClassDecl>(decl));
assert(canHaveSuperclass);
inheritedTy = layout.explicitSuperclass;
}
// If this is an enum inheritance clause, check for a raw type.
if (auto enumDecl = dyn_cast<EnumDecl>(decl)) {
// Check if we already had a raw type.
if (superclassTy) {
if (superclassTy->isEqual(inheritedTy)) {
auto removeRange = inheritedTypes.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;
}
// Noncopyable types cannot have a raw type until there is support for
// generics, since the raw type here is only useful if we'll generate
// a conformance to RawRepresentable, which is currently disabled.
if (!enumDecl->canBeCopyable()) {
// TODO: getRemovalRange is not yet aware of ~Copyable entries so it
// will accidentally delete commas or colons that are needed.
diags.diagnose(inherited.getSourceRange().Start,
diag::enum_raw_type_nonconforming_and_noncopyable,
enumDecl->getDeclaredInterfaceType(), inheritedTy)
.highlight(inherited.getSourceRange());
}
// If this is not the first entry in the inheritance clause, complain.
if (i > 0) {
auto removeRange = inheritedTypes.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() + ", ");
}
// Save the raw type locally.
superclassTy = inheritedTy;
superclassRange = inherited.getSourceRange();
continue;
}
// If this is a class type, it may be the superclass. We end up here when
// the inherited type is either itself a class, or when it is a subclass
// existential via the existential type path above.
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 = inheritedTypes.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;
}
// If this is not the first entry in the inheritance clause, complain.
if (isa<ClassDecl>(decl) && i > 0) {
auto removeRange = inheritedTypes.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.
}
if (canHaveSuperclass) {
// Record the superclass.
superclassTy = inheritedTy;
superclassRange = inherited.getSourceRange();
continue;
}
}
// We can't inherit from a non-class, non-protocol type.
decl->diagnose(canHaveSuperclass
? diag::inheritance_from_non_protocol_or_class
: diag::inheritance_from_non_protocol,
inheritedTy);
// FIXME: Note pointing to the declaration 'inheritedTy' references?
}
}
static void installCodingKeysIfNecessary(NominalTypeDecl *NTD) {
auto req =
ResolveImplicitMemberRequest{NTD, ImplicitMemberAction::ResolveCodingKeys};
(void)evaluateOrDefault(NTD->getASTContext().evaluator, req, {});
}
// TODO(distributed): same ugly hack as Codable does...
static void installDistributedActorIfNecessary(NominalTypeDecl *NTD) {
auto req =
ResolveImplicitMemberRequest{NTD, ImplicitMemberAction::ResolveDistributedActor};
(void)evaluateOrDefault(NTD->getASTContext().evaluator, req, {});
}
// Check for static properties that produce empty option sets
// using a rawValue initializer with a value of '0'
static void checkForEmptyOptionSet(const VarDecl *VD) {
// Check if property is a 'static let'
if (!VD->isStatic() || !VD->isLet())
return;
auto DC = VD->getDeclContext();
// Make sure property is of same type as the type it is declared in
if (!VD->getInterfaceType()->isEqual(DC->getSelfInterfaceType()))
return;
// Make sure this type conforms to OptionSet
bool conformsToOptionSet =
(bool)TypeChecker::conformsToKnownProtocol(DC->getSelfTypeInContext(),
KnownProtocolKind::OptionSet);
if (!conformsToOptionSet)
return;
auto PBD = VD->getParentPatternBinding();
if (!PBD)
return;
auto initIndex = PBD->getPatternEntryIndexForVarDecl(VD);
auto init = PBD->getInit(initIndex);
// Make sure property is being set with a constructor
auto ctor = dyn_cast_or_null<CallExpr>(init);
if (!ctor)
return;
auto ctorCalledVal = ctor->getCalledValue();
if (!ctorCalledVal)
return;
if (!isa<ConstructorDecl>(ctorCalledVal))
return;
// Make sure it is calling the rawValue constructor
auto *args = ctor->getArgs();
if (!args->isUnary())
return;
if (args->getLabel(0) != VD->getASTContext().Id_rawValue)
return;
// Make sure the rawValue parameter is a '0' integer literal
auto intArg = dyn_cast<IntegerLiteralExpr>(args->getExpr(0));
if (!intArg)
return;
if (intArg->getValue() != 0)
return;
VD->diagnose(diag::option_set_zero_constant, VD->getName());
VD->diagnose(diag::option_set_empty_set_init)
.fixItReplace(args->getSourceRange(), "([])");
}
template<typename T>
static void diagnoseDuplicateDecls(T &&decls) {
llvm::SmallDenseMap<DeclBaseName, const ValueDecl *> names;
for (auto *current : decls) {
if (!current->hasName() || current->isImplicit())
continue;
auto found = names.insert(std::make_pair(current->getBaseName(), current));
if (!found.second) {
auto *other = found.first->second;
current->getASTContext().Diags.diagnoseWithNotes(
current->diagnose(diag::invalid_redecl, current), [&]() {
other->diagnose(diag::invalid_redecl_prev, other);
});
// Mark the decl as invalid. This is needed to avoid emitting a
// duplicate diagnostic when running redeclaration checking in
// the case where the VarDecl is part of the enclosing context,
// e.g `let (x, x) = (0, 0)`.
if (!isa<GenericTypeParamDecl>(current))
current->setInvalid();
}
}
}
/// Check the inheritance clauses generic parameters along with any
/// requirements stored within the generic parameter list.
static void checkGenericParams(GenericContext *ownerCtx) {
const auto genericParams = ownerCtx->getGenericParams();
if (!genericParams)
return;
auto *decl = ownerCtx->getAsDecl();
auto &ctx = ownerCtx->getASTContext();
bool hasPack = false;
for (auto gp : *genericParams) {
// Diagnose generic types with a parameter packs if VariadicGenerics
// is not enabled.
if (gp->isParameterPack()) {
// Variadic nominal types require runtime support.
//
// Embedded doesn't require runtime support for this feature.
if (isa<NominalTypeDecl>(decl) &&
!ctx.LangOpts.hasFeature(Feature::Embedded)) {
TypeChecker::checkAvailability(
gp->getSourceRange(),
ctx.getVariadicGenericTypeAvailability(),
diag::availability_variadic_type_only_version_newer,
ownerCtx);
}
// Variadic nominal and type alias types can only have a single
// parameter pack.
if (hasPack && isa<GenericTypeDecl>(decl)) {
gp->diagnose(diag::more_than_one_pack_in_type);
}
hasPack = true;
}
if (gp->isValue()) {
// Value generic nominal types require runtime support.
//
// Embedded doesn't require runtime support for this feature.
if (isa<NominalTypeDecl>(decl) &&
!ctx.LangOpts.hasFeature(Feature::Embedded)) {
TypeChecker::checkAvailability(
gp->getSourceRange(),
ctx.getValueGenericTypeAvailability(),
diag::availability_value_generic_type_only_version_newer,
ownerCtx);
}
}
TypeChecker::checkDeclAttributes(gp);
checkInheritanceClause(gp);
}
// Force resolution of interface types written in requirements here.
WhereClauseOwner(ownerCtx)
.visitRequirements(TypeResolutionStage::Interface,
[](Requirement, RequirementRepr *) { return false; });
// Check for duplicate generic parameter names.
TypeChecker::checkShadowedGenericParams(ownerCtx);
}
/// Returns \c true if \p current and \p other are in the same source file
/// \em and \c current appears before \p other in that file.
static bool isBeforeInSameFile(Decl *current, Decl *other) {
if (current->getDeclContext()->getParentSourceFile() !=
other->getDeclContext()->getParentSourceFile())
return false;
if (!current->getLoc().isValid())
return false;
return current->getASTContext().SourceMgr
.isBeforeInBuffer(current->getLoc(), other->getLoc());
}
template <typename T>
static void checkOperatorOrPrecedenceGroupRedeclaration(
T *decl, Diag<> diagID, Diag<> noteID,
llvm::function_ref<TinyPtrVector<T *>(OperatorLookupDescriptor)>
lookupOthers) {
if (decl->isInvalid())
return;
auto *currentFile = decl->getDeclContext()->getParentSourceFile();
assert(currentFile);
auto *module = currentFile->getParentModule();
auto &ctx = module->getASTContext();
auto desc = OperatorLookupDescriptor::forModule(module, decl->getName());
auto otherDecls = lookupOthers(desc);
for (auto *other : otherDecls) {
if (other == decl || other->isInvalid())
continue;
bool shouldDiagnose = true;
if (currentFile != other->getDeclContext()->getParentSourceFile()) {
// If the declarations are in different files, only diagnose if we've
// enabled the new operator lookup behaviour where decls in the current
// module are now favored over imports.
shouldDiagnose = ctx.LangOpts.EnableNewOperatorLookup;
}
if (shouldDiagnose) {
// For a same-file redeclaration, make sure we get the diagnostic ordering
// to be sensible.
if (isBeforeInSameFile(decl, other)) {
std::swap(decl, other);
}
ctx.Diags.diagnose(decl, diagID);
ctx.Diags.diagnose(other, noteID);
decl->setInvalid();
return;
}
}
}
static void checkRedeclaration(OperatorDecl *op) {
checkOperatorOrPrecedenceGroupRedeclaration<OperatorDecl>(
op, diag::operator_redeclared, diag::previous_operator_decl,
[&](OperatorLookupDescriptor desc) {
DirectOperatorLookupRequest req{desc, op->getFixity()};
return evaluateOrDefault(op->getASTContext().evaluator, req, {});
});
}
static void checkRedeclaration(PrecedenceGroupDecl *group) {
checkOperatorOrPrecedenceGroupRedeclaration<PrecedenceGroupDecl>(
group, diag::precedence_group_redeclared,
diag::previous_precedence_group_decl, [&](OperatorLookupDescriptor desc) {
DirectPrecedenceGroupLookupRequest req{desc};
return evaluateOrDefault(group->getASTContext().evaluator, req, {});
});
}
/// Check whether \c current is a redeclaration.
evaluator::SideEffect
CheckRedeclarationRequest::evaluate(Evaluator &eval, ValueDecl *current,
NominalTypeDecl *SelfNominalType) const {
// Ignore invalid and anonymous declarations.
if (current->isInvalid() || !current->hasName())
return std::make_tuple<>();
// 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)
return std::make_tuple<>();
if (auto func = dyn_cast<AbstractFunctionDecl>(current)) {
if (func->isDistributedThunk()) {
return std::make_tuple<>();
}
}
auto &ctx = current->getASTContext();
bool currentIsABIOnly = !ABIRoleInfo(current).providesAPI();
// If true, two conflicting decls may not be in scope at the same time, so
// we might only detect a redeclaration from one and not the other.
bool partialScopes = currentDC->isLocalContext() && isa<VarDecl>(current);
// Find other potential definitions.
SmallVector<ValueDecl *, 4> otherDefinitions;
if (currentDC->isTypeContext()) {
// Look within a type context.
if (auto nominal = currentDC->getSelfNominalTypeDecl()) {
OptionSet<NominalTypeDecl::LookupDirectFlags> flags;
if (currentIsABIOnly)
flags |= NominalTypeDecl::LookupDirectFlags::ABIProviding;
auto found = nominal->lookupDirect(current->getBaseName(), SourceLoc(),
flags);
otherDefinitions.append(found.begin(), found.end());
}
} else if (currentDC->isLocalContext()) {
if (!current->isImplicit()) {
ABIRole roleFilter;
if (partialScopes)
// We don't know if conflicts will be detected when the other decl is
// `current`, so if this decl has `ABIRole::Both`, we need this lookup
// to include both ProvidesABI *and* ProvidesAPI decls.
roleFilter = ABIRoleInfo(current).getRole();
else
roleFilter = currentIsABIOnly ? ABIRole::ProvidesABI
: ABIRole::ProvidesAPI;
ASTScope::lookupLocalDecls(currentFile, current->getBaseName(),
current->getLoc(),
/*stopAfterInnermostBraceStmt=*/true,
roleFilter, otherDefinitions);
}
} else {
assert(currentDC->isModuleScopeContext());
// Look within a module context.
OptionSet<ModuleLookupFlags> flags;
if (currentIsABIOnly)
flags |= ModuleLookupFlags::ABIProviding;
currentFile->getParentModule()->lookupValue(current->getBaseName(),
NLKind::QualifiedLookup,
flags, otherDefinitions);
}
// 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.
//
// FIXME: Breaking a cycle here with hasInterfaceType() is bogus.
if (current == other || (other->hasInterfaceType() && other->isInvalid()))
continue;
auto *otherDC = other->getDeclContext();
// Skip declarations in other modules.
if (currentModule != otherDC->getParentModule())
continue;
bool otherIsABIOnly = !ABIRoleInfo(other).providesAPI();
if (currentIsABIOnly == otherIsABIOnly || partialScopes) {
// If both declarations are in the same file, only diagnose the second one
if (isBeforeInSameFile(current, other))
continue;
}
else if (!currentIsABIOnly && otherIsABIOnly)
// Don't diagnose a non-ABI-only decl as conflicting with an ABI-only
// decl. (We'll diagnose it in the other direction instead.)
continue;
// Don't compare methods vs. non-methods (which only happens with
// operators).
if (currentDC->isTypeContext() != otherDC->isTypeContext())
continue;
// In local context, only consider exact name matches.
if (currentDC->isLocalContext() &&
current->getName() != other->getName())
continue;
// Check whether the overload signatures conflict (ignoring the type for
// now).
auto otherSig = other->getOverloadSignature();
if (!conflicting(currentSig, otherSig))
continue;
// Skip inaccessible 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 (!currentDC->isLocalContext() &&
!other->isAccessibleFrom(currentDC))
continue;
// Skip invalid declarations.
if (other->isInvalid())
continue;
// Allow redeclarations of typealiases in different constrained
// extensions.
if (isa<TypeAliasDecl>(current) &&
isa<TypeAliasDecl>(other) &&
currentDC != otherDC &&
currentDC->getGenericSignatureOfContext().getCanonicalSignature() !=
otherDC->getGenericSignatureOfContext().getCanonicalSignature())
continue;
// Thwart attempts to override the same declaration more than once.
const auto *currentOverride = current->getOverriddenDecl();
const auto *otherOverride = other->getOverriddenDecl();
const auto *otherInit = dyn_cast<ConstructorDecl>(other);
if (currentOverride && currentOverride == otherOverride &&
!(otherInit && otherInit->isImplicit())) {
current->diagnose(diag::multiple_override, current->getName());
other->diagnose(diag::multiple_override_prev, other->getName());
current->setInvalid();
break;
}
// Get the overload signature type.
CanType otherSigType = other->getOverloadSignatureType();
bool wouldBeSwift5Redeclaration = false;
auto isRedeclaration = conflicting(ctx, currentSig, currentSigType,
otherSig, otherSigType,
&wouldBeSwift5Redeclaration);
// If there is another conflict, complain.
if (isRedeclaration || wouldBeSwift5Redeclaration) {
// 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;
}
// Signatures are the same, but interface types are not. We must
// have a type that we've massaged as part of signature
// interface type generation.
if (current->getInterfaceType()->isEqual(other->getInterfaceType())) {
if (currentDC->isTypeContext() == other->getDeclContext()->isTypeContext()) {
auto currFnTy = current->getInterfaceType()->getAs<AnyFunctionType>();
auto otherFnTy = other->getInterfaceType()->getAs<AnyFunctionType>();
if (currFnTy && otherFnTy && currentDC->isTypeContext()) {
currFnTy = currFnTy->getResult()->getAs<AnyFunctionType>();
otherFnTy = otherFnTy->getResult()->getAs<AnyFunctionType>();
}
if (currFnTy && otherFnTy) {
ArrayRef<AnyFunctionType::Param> currParams = currFnTy->getParams();
ArrayRef<AnyFunctionType::Param> otherParams = otherFnTy->getParams();
if (currParams.size() == otherParams.size()) {
auto diagnosed = false;
for (unsigned i : indices(currParams)) {
bool currIsIUO = false;
bool otherIsIUO = false;
bool optionalRedecl = false;
if (currParams[i].getPlainType()->getOptionalObjectType()) {
optionalRedecl = true;
auto *param = swift::getParameterAt(current, i);
assert(param);
if (param->isImplicitlyUnwrappedOptional())
currIsIUO = true;
}
if (otherParams[i].getPlainType()->getOptionalObjectType()) {
auto *param = swift::getParameterAt(other, i);
assert(param);
if (param->isImplicitlyUnwrappedOptional())
otherIsIUO = true;
}
else {
optionalRedecl = false;
}
if (optionalRedecl && currIsIUO != otherIsIUO) {
ctx.Diags.diagnoseWithNotes(
current->diagnose(diag::invalid_redecl, current), [&]() {
other->diagnose(diag::invalid_redecl_prev, other);
});
current->diagnose(diag::invalid_redecl_by_optionality_note,
otherIsIUO, currIsIUO);
current->setInvalid();
diagnosed = true;
break;
}
}
if (diagnosed)
break;
}
}
}
}
// 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->isFailable() !=
otherInit->isFailable())) {
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 {
std::optional<llvm::VersionTuple> introduced;
std::optional<llvm::VersionTuple> obsoleted;
public:
static AvailabilityRange from(const ValueDecl *VD) {
AvailabilityRange result;
for (auto attr : VD->getSemanticAvailableAttrs()) {
if (attr.isSwiftLanguageModeSpecific()) {
if (auto introduced = attr.getIntroduced())
result.introduced = introduced;
if (auto obsoleted = attr.getObsoleted())
result.obsoleted = obsoleted;
}
}
return result;
}
bool fullyPrecedes(const AvailabilityRange &other) const {
if (!obsoleted.has_value())
return false;
if (!other.introduced.has_value())
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.