-
Notifications
You must be signed in to change notification settings - Fork 10.4k
/
Copy pathGenericSignature.cpp
1434 lines (1194 loc) · 48.1 KB
/
GenericSignature.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
//===--- GenericSignature.cpp - Generic Signature AST ---------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 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 the GenericSignature class.
//
//===----------------------------------------------------------------------===//
#include "swift/AST/GenericSignature.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/Decl.h"
#include "swift/AST/GenericEnvironment.h"
#include "swift/AST/Module.h"
#include "swift/AST/PrettyStackTrace.h"
#include "swift/AST/TypeCheckRequests.h"
#include "swift/AST/Types.h"
#include "swift/Basic/Assertions.h"
#include "swift/Basic/SourceManager.h"
#include "swift/Basic/STLExtras.h"
#include "RequirementMachine/RequirementMachine.h"
#include <functional>
using namespace swift;
void ConformancePath::print(raw_ostream &out) const {
llvm::interleave(
begin(), end(),
[&](const Entry &entry) {
entry.first.print(out);
out << ": " << entry.second->getName();
},
[&] { out << " -> "; });
}
void ConformancePath::dump() const {
print(llvm::errs());
llvm::errs() << "\n";
}
GenericSignatureImpl::GenericSignatureImpl(
ArrayRef<GenericTypeParamType *> params,
ArrayRef<Requirement> requirements, bool isKnownCanonical)
: NumGenericParams(params.size()), NumRequirements(requirements.size()),
CanonicalSignatureOrASTContext() {
std::uninitialized_copy(params.begin(), params.end(),
getTrailingObjects<GenericTypeParamType *>());
std::uninitialized_copy(requirements.begin(), requirements.end(),
getTrailingObjects<Requirement>());
#ifndef NDEBUG
// Make sure generic parameters are in the right order, and
// none are missing.
unsigned depth = 0;
unsigned count = 0;
for (auto param : params) {
if (param->getDepth() != depth) {
assert(param->getDepth() > depth && "Generic parameter depth mismatch");
depth = param->getDepth();
count = 0;
}
assert(param->getIndex() == count && "Generic parameter index mismatch");
++count;
}
#endif
if (isKnownCanonical)
CanonicalSignatureOrASTContext =
&GenericSignature::getASTContext(params, requirements);
}
ArrayRef<GenericTypeParamType *>
GenericSignatureImpl::getInnermostGenericParams() const {
const auto params = getGenericParams();
const unsigned maxDepth = getMaxDepth();
if (params.front()->getDepth() == maxDepth)
return params;
// There is a depth change. Count the number of elements
// to slice off the front.
unsigned sliceCount = params.size() - 1;
while (true) {
if (params[sliceCount - 1]->getDepth() != maxDepth)
break;
--sliceCount;
}
return params.slice(sliceCount);
}
unsigned GenericSignatureImpl::getMaxDepth() const {
return getGenericParams().back()->getDepth();
}
unsigned GenericSignature::getNextDepth() const {
if (!getPointer())
return 0;
return getPointer()->getMaxDepth() + 1;
}
void GenericSignatureImpl::forEachParam(
llvm::function_ref<void(GenericTypeParamType *, bool)> callback) const {
// Figure out which generic parameters are concrete or same-typed to another
// type parameter.
auto genericParams = getGenericParams();
auto genericParamsAreCanonical =
SmallVector<bool, 4>(genericParams.size(), true);
for (auto req : getRequirements()) {
GenericTypeParamType *gp;
bool isCanonical = false;
switch (req.getKind()) {
case RequirementKind::SameType: {
if (req.getSecondType()->isParameterPack() !=
req.getFirstType()->isParameterPack()) {
// This is a same-element requirement, which does not make
// type parameters non-canonical.
isCanonical = true;
}
if (auto secondGP = req.getSecondType()->getAs<GenericTypeParamType>()) {
// If two generic parameters are same-typed, then the right-hand one
// is non-canonical.
assert(req.getFirstType()->is<GenericTypeParamType>());
gp = secondGP;
} else {
// Otherwise, the right-hand side is an associated type or concrete
// type, and the left-hand one is non-canonical.
gp = req.getFirstType()->getAs<GenericTypeParamType>();
if (!gp)
continue;
// If an associated type is same-typed, it doesn't constrain the generic
// parameter itself. That is, if T == U.Foo, then T is canonical,
// whereas U.Foo is not.
if (req.getSecondType()->isTypeParameter())
continue;
}
break;
}
case RequirementKind::Superclass:
case RequirementKind::Conformance:
case RequirementKind::Layout:
case RequirementKind::SameShape:
continue;
}
unsigned index = GenericParamKey(gp).findIndexIn(genericParams);
genericParamsAreCanonical[index] = isCanonical;
}
// Call the callback with each parameter and the result of the above analysis.
for (auto index : indices(genericParams))
callback(genericParams[index], genericParamsAreCanonical[index]);
}
bool GenericSignatureImpl::areAllParamsConcrete() const {
unsigned numConcreteGenericParams = 0;
for (const auto &req : getRequirements()) {
switch (req.getKind()) {
case RequirementKind::SameType:
if (!req.getFirstType()->is<GenericTypeParamType>())
continue;
if (req.getSecondType()->isTypeParameter())
continue;
++numConcreteGenericParams;
break;
case RequirementKind::Conformance:
case RequirementKind::Superclass:
case RequirementKind::Layout:
case RequirementKind::SameShape:
continue;
}
}
return numConcreteGenericParams == getGenericParams().size();
}
bool GenericSignatureImpl::hasParameterPack() const {
for (auto *paramTy : getGenericParams()) {
if (paramTy->isParameterPack())
return true;
}
return false;
}
ASTContext &GenericSignature::getASTContext(
ArrayRef<GenericTypeParamType *> params,
ArrayRef<swift::Requirement> requirements) {
// The params and requirements cannot both be empty.
if (!params.empty())
return params.front()->getASTContext();
else
return requirements.front().getFirstType()->getASTContext();
}
/// Retrieve the generic parameters.
ArrayRef<GenericTypeParamType *> GenericSignature::getGenericParams() const {
return isNull()
? ArrayRef<GenericTypeParamType *>()
: getPointer()->getGenericParams();
}
/// Retrieve the innermost generic parameters.
///
/// Given a generic signature for a nested generic type, produce an
/// array of the generic parameters for the innermost generic type.
ArrayRef<GenericTypeParamType *> GenericSignature::getInnermostGenericParams() const {
return isNull()
? ArrayRef<GenericTypeParamType *>()
: getPointer()->getInnermostGenericParams();
}
/// Retrieve the requirements.
ArrayRef<Requirement> GenericSignature::getRequirements() const {
return isNull()
? ArrayRef<Requirement>{}
: getPointer()->getRequirements();
}
rewriting::RequirementMachine *
GenericSignatureImpl::getRequirementMachine() const {
if (Machine)
return Machine;
const_cast<GenericSignatureImpl *>(this)->Machine
= getASTContext().getRewriteContext().getRequirementMachine(
getCanonicalSignature());
return Machine;
}
bool GenericSignatureImpl::isEqual(GenericSignature Other) const {
return getCanonicalSignature() == Other.getCanonicalSignature();
}
bool GenericSignatureImpl::isCanonical() const {
if (CanonicalSignatureOrASTContext.is<ASTContext *>())
return true;
return getCanonicalSignature().getPointer() == this;
}
CanGenericSignature
CanGenericSignature::getCanonical(ArrayRef<GenericTypeParamType *> params,
ArrayRef<Requirement> requirements) {
// Canonicalize the parameters and requirements.
SmallVector<GenericTypeParamType*, 8> canonicalParams;
canonicalParams.reserve(params.size());
for (auto param : params) {
canonicalParams.push_back(cast<GenericTypeParamType>(param->getCanonicalType()));
}
SmallVector<Requirement, 8> canonicalRequirements;
canonicalRequirements.reserve(requirements.size());
for (auto &reqt : requirements)
canonicalRequirements.push_back(reqt.getCanonical());
auto canSig = get(canonicalParams, canonicalRequirements,
/*isKnownCanonical=*/true);
return CanGenericSignature(canSig);
}
CanGenericSignature GenericSignature::getCanonicalSignature() const {
// If the underlying pointer is null, return `CanGenericSignature()`.
if (isNull())
return CanGenericSignature();
// Otherwise, return the canonical signature of the underlying pointer.
return getPointer()->getCanonicalSignature();
}
CanGenericSignature GenericSignatureImpl::getCanonicalSignature() const {
// If we haven't computed the canonical signature yet, do so now.
if (CanonicalSignatureOrASTContext.isNull()) {
// Compute the canonical signature.
auto canSig = CanGenericSignature::getCanonical(getGenericParams(),
getRequirements());
// Record either the canonical signature or an indication that
// this is the canonical signature.
if (canSig.getPointer() != this)
CanonicalSignatureOrASTContext = canSig.getPointer();
else
CanonicalSignatureOrASTContext = &getGenericParams()[0]->getASTContext();
// Return the canonical signature.
return canSig;
}
// A stored ASTContext indicates that this is the canonical
// signature.
if (CanonicalSignatureOrASTContext.is<ASTContext *>())
return CanGenericSignature(this);
// Otherwise, return the stored canonical signature.
return CanGenericSignature(
CanonicalSignatureOrASTContext.get<const GenericSignatureImpl *>());
}
GenericEnvironment *GenericSignature::getGenericEnvironment() const {
if (isNull())
return nullptr;
return getPointer()->getGenericEnvironment();
}
GenericEnvironment *GenericSignatureImpl::getGenericEnvironment() const {
if (GenericEnv == nullptr) {
const auto impl = const_cast<GenericSignatureImpl *>(this);
impl->GenericEnv = GenericEnvironment::forPrimary(this);
}
return GenericEnv;
}
GenericSignature::LocalRequirements
GenericSignatureImpl::getLocalRequirements(Type depType) const {
assert(depType->isTypeParameter() && "Expected a type parameter here");
return getRequirementMachine()->getLocalRequirements(depType);
}
ASTContext &GenericSignatureImpl::getASTContext() const {
// Canonical signatures store the ASTContext directly.
if (auto ctx = CanonicalSignatureOrASTContext.dyn_cast<ASTContext *>())
return *ctx;
// For everything else, just get it from the generic parameter.
return GenericSignature::getASTContext(getGenericParams(), getRequirements());
}
bool GenericSignatureImpl::requiresClass(Type type) const {
assert(type->isTypeParameter() &&
"Only type parameters can have superclass requirements");
return getRequirementMachine()->requiresClass(type);
}
/// Determine the superclass bound on the given dependent type.
Type GenericSignatureImpl::getSuperclassBound(Type type) const {
assert(type->isTypeParameter() &&
"Only type parameters can have superclass requirements");
return getRequirementMachine()->getSuperclassBound(
type, getGenericParams());
}
/// Determine the set of protocols to which the given type parameter is
/// required to conform.
GenericSignature::RequiredProtocols
GenericSignatureImpl::getRequiredProtocols(Type type) const {
assert(type->isTypeParameter() && "Expected a type parameter");
return getRequirementMachine()->getRequiredProtocols(type);
}
bool GenericSignatureImpl::requiresProtocol(Type type,
ProtocolDecl *proto) const {
assert(type->isTypeParameter() && "Expected a type parameter");
return getRequirementMachine()->requiresProtocol(type, proto);
}
/// Determine whether the given dependent type is equal to a concrete type.
bool GenericSignatureImpl::isConcreteType(Type type) const {
assert(type->isTypeParameter() && "Expected a type parameter");
return getRequirementMachine()->isConcreteType(type);
}
/// Return the concrete type that the given type parameter is constrained to,
/// or the null Type if it is not the subject of a concrete same-type
/// constraint.
Type GenericSignatureImpl::getConcreteType(Type type) const {
assert(type->isTypeParameter() && "Expected a type parameter");
return getRequirementMachine()->getConcreteType(type, getGenericParams());
}
LayoutConstraint GenericSignatureImpl::getLayoutConstraint(Type type) const {
assert(type->isTypeParameter() &&
"Only type parameters can have layout constraints");
return getRequirementMachine()->getLayoutConstraint(type);
}
bool GenericSignatureImpl::areReducedTypeParametersEqual(Type type1,
Type type2) const {
assert(type1->isTypeParameter());
assert(type2->isTypeParameter());
if (type1.getPointer() == type2.getPointer())
return true;
return getRequirementMachine()->areReducedTypeParametersEqual(type1, type2);
}
bool GenericSignatureImpl::isRequirementSatisfied(
Requirement requirement,
bool allowMissing,
bool brokenPackBehavior) const {
if (requirement.getFirstType()->hasTypeParameter()) {
auto *genericEnv = getGenericEnvironment();
if (brokenPackBehavior) {
// Swift 5.9 shipped with a bug here where this method would return
// incorrect results. Maintain the old behavior specifically for two
// call sites in the ASTMangler.
if ((requirement.getKind() == RequirementKind::SameType ||
requirement.getKind() == RequirementKind::Superclass) &&
!requirement.getSecondType()->isTypeParameter() &&
requirement.getSecondType().findIf([&](Type t) -> bool {
return t->is<PackExpansionType>();
})) {
return false;
}
}
requirement = requirement.subst(
QueryInterfaceTypeSubstitutions{genericEnv},
LookUpConformanceInModule(),
SubstFlags::PreservePackExpansionLevel);
}
SmallVector<Requirement, 2> subReqs;
switch (requirement.checkRequirement(subReqs, allowMissing)) {
case CheckRequirementResult::Success:
return true;
case CheckRequirementResult::ConditionalConformance:
// FIXME: Need to check conditional requirements here.
return true;
case CheckRequirementResult::PackRequirement:
// FIXME
assert(false && "Refactor this");
return true;
case CheckRequirementResult::RequirementFailure:
case CheckRequirementResult::SubstitutionFailure:
return false;
}
}
SmallVector<Requirement, 4>
GenericSignature::requirementsNotSatisfiedBy(GenericSignature otherSig) const {
// The null generic signature has no requirements, therefore all requirements
// are satisfied by any signature.
if (isNull()) {
return {};
}
return getPointer()->requirementsNotSatisfiedBy(otherSig);
}
SmallVector<Requirement, 4> GenericSignatureImpl::requirementsNotSatisfiedBy(
GenericSignature otherSig) const {
SmallVector<Requirement, 4> result;
// If the signatures match by pointer, all requirements are satisfied.
if (otherSig.getPointer() == this) return result;
// If there is no other signature, no requirements are satisfied.
if (!otherSig) {
const auto reqs = getRequirements();
result.append(reqs.begin(), reqs.end());
return result;
}
// If the canonical signatures are equal, all requirements are satisfied.
if (getCanonicalSignature() == otherSig->getCanonicalSignature())
return result;
// Find the requirements that aren't satisfied.
for (const auto &req : getRequirements()) {
if (!otherSig->isRequirementSatisfied(req))
result.push_back(req);
}
return result;
}
bool GenericSignatureImpl::isReducedType(Type type) const {
// If the type isn't canonical, it's not reduced.
if (!type->isCanonical())
return false;
// A fully concrete canonical type is reduced.
if (!type->hasTypeParameter())
return true;
return getRequirementMachine()->isReducedType(type);
}
CanType GenericSignature::getReducedType(Type type) const {
// The null generic signature has no requirements so cannot influence the
// structure of the can type computed here.
if (isNull()) {
return type->getCanonicalType();
}
return getPointer()->getReducedType(type);
}
CanType GenericSignatureImpl::getReducedType(Type type) const {
type = type->getCanonicalType();
// A fully concrete type is already reduced.
if (!type->hasTypeParameter())
return CanType(type);
return getRequirementMachine()->getReducedType(
type, { })->getCanonicalType();
}
CanType GenericSignatureImpl::getReducedTypeParameter(CanType type) const {
return getRequirementMachine()->getReducedTypeParameter(
type, { })->getCanonicalType();
}
bool GenericSignatureImpl::isValidTypeParameter(Type type) const {
return getRequirementMachine()->isValidTypeParameter(type);
}
ArrayRef<CanTypeWrapper<GenericTypeParamType>>
CanGenericSignature::getGenericParams() const {
auto params =
this->GenericSignature::getGenericParams();
auto base = reinterpret_cast<const CanTypeWrapper<GenericTypeParamType> *>(
params.data());
return {base, params.size()};
}
ConformancePath
GenericSignatureImpl::getConformancePath(Type type,
ProtocolDecl *protocol) const {
return getRequirementMachine()->getConformancePath(type, protocol);
}
TypeDecl *
GenericSignatureImpl::lookupNestedType(Type type, Identifier name) const {
assert(type->isTypeParameter());
return getRequirementMachine()->lookupNestedType(type, name);
}
Type
GenericSignatureImpl::getReducedShape(Type type) const {
return getRequirementMachine()->getReducedShape(type, getGenericParams());
}
bool
GenericSignatureImpl::haveSameShape(Type type1, Type type2) const {
return getRequirementMachine()->haveSameShape(type1, type2);
}
llvm::SmallVector<CanType, 2> GenericSignatureImpl::getShapeClasses() const {
llvm::SmallSetVector<CanType, 2> result;
forEachParam([&](GenericTypeParamType *gp, bool canonical) {
if (!canonical || !gp->isParameterPack())
return;
result.insert(getReducedShape(gp)->getCanonicalType());
});
return result.takeVector();
}
unsigned GenericParamKey::findIndexIn(
ArrayRef<GenericTypeParamType *> genericParams) const {
// For depth 0, we have random access. We perform the extra checking so that
// we can return
if (Depth == 0 && Index < genericParams.size() &&
genericParams[Index] == *this)
return Index;
// At other depths, perform a binary search.
unsigned result =
std::lower_bound(genericParams.begin(), genericParams.end(), *this,
Ordering())
- genericParams.begin();
if (result < genericParams.size() && genericParams[result] == *this)
return result;
// We didn't find the parameter we were looking for.
return genericParams.size();
}
SubstitutionMap GenericSignatureImpl::getIdentitySubstitutionMap() const {
return SubstitutionMap::get(const_cast<GenericSignatureImpl *>(this),
[](SubstitutableType *t) -> Type {
auto param = cast<GenericTypeParamType>(t);
if (!param->isParameterPack())
return param;
return PackType::getSingletonPackExpansion(param);
},
MakeAbstractConformanceForGenericType());
}
GenericTypeParamType *GenericSignatureImpl::getSugaredType(
GenericTypeParamType *type) const {
unsigned ordinal = getGenericParamOrdinal(type);
return getGenericParams()[ordinal];
}
Type GenericSignatureImpl::getSugaredType(Type type) const {
if (!type->hasTypeParameter())
return type;
return type.transformRec([this](TypeBase *Ty) -> std::optional<Type> {
if (auto GP = dyn_cast<GenericTypeParamType>(Ty)) {
return Type(getSugaredType(GP));
}
return std::nullopt;
});
}
unsigned GenericSignatureImpl::getGenericParamOrdinal(
GenericTypeParamType *param) const {
return GenericParamKey(param).findIndexIn(getGenericParams());
}
Type GenericSignatureImpl::getUpperBound(Type type,
bool forExistentialSelf,
bool includeParameterizedProtocols) const {
assert(type->isTypeParameter());
llvm::SmallVector<Type, 2> types;
unsigned rootDepth = type->getRootGenericParam()->getDepth();
auto accept = [forExistentialSelf, rootDepth](Type t) {
if (!forExistentialSelf)
return true;
return !t.findIf([rootDepth](Type t) {
if (auto *paramTy = t->getAs<GenericTypeParamType>())
return (paramTy->getDepth() == rootDepth);
return false;
});
};
// We start with the assumption we'll add a '& AnyObject' member to our
// composition, but we might clear this below.
bool hasExplicitAnyObject = requiresClass(type);
// Look for the most derived superclass that does not involve the type
// being erased.
Type superclass = getSuperclassBound(type);
if (superclass) {
do {
superclass = getReducedType(superclass);
if (accept(superclass))
break;
} while ((superclass = superclass->getSuperclass()));
// If we're going to have a superclass, we can drop the '& AnyObject'.
if (superclass) {
types.push_back(getSugaredType(superclass));
hasExplicitAnyObject = false;
}
}
auto &ctx = getASTContext();
// Record the absence of Copyable and Escapable conformance, but only if
// we didn't have a superclass or require AnyObject.
InvertibleProtocolSet inverses;
if (!superclass && !hasExplicitAnyObject) {
for (auto ip : InvertibleProtocolSet::allKnown()) {
auto *kp = ctx.getProtocol(::getKnownProtocolKind(ip));
if (!requiresProtocol(type, kp))
inverses.insert(ip);
}
}
for (auto *proto : getRequiredProtocols(type)) {
// Don't add invertible protocols to the composition, because we recorded
// their absence above.
if (proto->getInvertibleProtocolKind())
continue;
if (proto->requiresClass())
hasExplicitAnyObject = false;
auto *baseType = proto->getDeclaredInterfaceType()->castTo<ProtocolType>();
auto primaryAssocTypes = proto->getPrimaryAssociatedTypes();
if (includeParameterizedProtocols && !primaryAssocTypes.empty()) {
SmallVector<Type, 2> argTypes;
// Attempt to recover same-type requirements on primary associated types.
for (auto *assocType : primaryAssocTypes) {
// For each primary associated type A of P, compute the reduced type
// of T.[P]A.
auto memberType = getReducedType(DependentMemberType::get(type, assocType));
// If the reduced type is at a lower depth than the root generic
// parameter of T, then it's constrained.
if (accept(memberType)) {
argTypes.push_back(getSugaredType(memberType));
}
}
// If we have constrained all primary associated types, create a
// parameterized protocol type. During code completion, we might call
// `getExistentialType` (which calls this method) on a generic parameter
// that doesn't have all parameters specified, e.g. to get a consise
// description of the parameter type to the following function.
//
// func foo<P: Publisher>(p: P) where P.Failure == Never
//
// In that case just add the base type in the default branch below.
if (argTypes.size() == primaryAssocTypes.size()) {
types.push_back(ParameterizedProtocolType::get(
getASTContext(), baseType, argTypes));
continue;
}
}
types.push_back(baseType);
}
return ProtocolCompositionType::get(ctx, types, inverses,
hasExplicitAnyObject);
}
Type GenericSignatureImpl::getExistentialType(Type paramTy) const {
auto upperBound = getUpperBound(paramTy,
/*forExistentialSelf=*/true,
/*includeParameterizedProtocols=*/true);
if (upperBound->isConstraintType())
return ExistentialType::get(upperBound);
assert(upperBound->getClassOrBoundGenericClass());
return upperBound;
}
void GenericSignature::Profile(llvm::FoldingSetNodeID &id) const {
return GenericSignature::Profile(id, getPointer()->getGenericParams(),
getPointer()->getRequirements());
}
void GenericSignature::Profile(llvm::FoldingSetNodeID &ID,
ArrayRef<GenericTypeParamType *> genericParams,
ArrayRef<Requirement> requirements) {
return GenericSignatureImpl::Profile(ID, genericParams, requirements);
}
void swift::simple_display(raw_ostream &out, GenericSignature sig) {
if (sig)
sig->print(out);
else
out << "NULL";
}
/// Compare two associated types.
int swift::compareAssociatedTypes(AssociatedTypeDecl *assocType1,
AssociatedTypeDecl *assocType2) {
// - by name.
if (int result = assocType1->getName().str().compare(
assocType2->getName().str()))
return result;
// Prefer an associated type with no overrides (i.e., an anchor) to one
// that has overrides.
bool hasOverridden1 = !assocType1->getOverriddenDecls().empty();
bool hasOverridden2 = !assocType2->getOverriddenDecls().empty();
if (hasOverridden1 != hasOverridden2)
return hasOverridden1 ? +1 : -1;
// - by protocol, so t_n_m.`P.T` < t_n_m.`Q.T` (given P < Q)
auto proto1 = assocType1->getProtocol();
auto proto2 = assocType2->getProtocol();
if (int compareProtocols = TypeDecl::compare(proto1, proto2))
return compareProtocols;
// Error case: if we have two associated types with the same name in the
// same protocol, just tie-break based on source location.
if (assocType1 != assocType2) {
auto &ctx = assocType1->getASTContext();
return ctx.SourceMgr.isBeforeInBuffer(assocType1->getLoc(),
assocType2->getLoc()) ? -1 : +1;
}
return 0;
}
/// Canonical ordering for type parameters.
int swift::compareDependentTypes(Type type1, Type type2) {
// Fast-path check for equality.
if (type1->isEqual(type2)) return 0;
// Ordering is as follows:
// - Generic params
auto gp1 = type1->getAs<GenericTypeParamType>();
auto gp2 = type2->getAs<GenericTypeParamType>();
if (gp1 && gp2)
return GenericParamKey(gp1) < GenericParamKey(gp2) ? -1 : +1;
// A generic parameter is always ordered before a nested type.
if (static_cast<bool>(gp1) != static_cast<bool>(gp2))
return gp1 ? -1 : +1;
// - Dependent members
auto depMemTy1 = type1->castTo<DependentMemberType>();
auto depMemTy2 = type2->castTo<DependentMemberType>();
// - by base, so t_0_n.`P.T` < t_1_m.`P.T`
if (int compareBases =
compareDependentTypes(depMemTy1->getBase(), depMemTy2->getBase()))
return compareBases;
// - by name, so t_n_m.`P.T` < t_n_m.`P.U`
if (int compareNames = depMemTy1->getName().str().compare(
depMemTy2->getName().str()))
return compareNames;
auto *assocType1 = depMemTy1->getAssocType();
auto *assocType2 = depMemTy2->getAssocType();
if (int result = compareAssociatedTypes(assocType1, assocType2))
return result;
return 0;
}
#pragma mark Generic signature verification
void GenericSignature::verify() const {
verify(getRequirements());
}
void GenericSignature::verify(ArrayRef<Requirement> reqts) const {
auto dumpAndAbort = [&]() {
llvm::errs() << "All requirements:\n";
for (auto reqt : reqts) {
reqt.dump(llvm::errs());
llvm::errs() << "\n";
}
getPointer()->getRequirementMachine()->dump(llvm::errs());
abort();
};
auto canSig = getCanonicalSignature();
PrettyStackTraceGenericSignature debugStack("checking", canSig);
// We collect conformance requirements to check that they're minimal.
llvm::SmallDenseMap<CanType, SmallVector<ProtocolDecl *, 2>, 2> conformances;
// We collect same-type requirements to check that they're minimal.
llvm::SmallDenseMap<CanType, SmallVector<Type, 2>, 2> sameTypeComponents;
// Check that the requirements satisfy certain invariants.
for (unsigned idx : indices(reqts)) {
const auto &reqt = reqts[idx].getCanonical();
// Left-hand side must be a canonical type parameter.
if (reqt.getKind() != RequirementKind::SameType) {
if (!reqt.getFirstType()->isTypeParameter()) {
llvm::errs() << "Left-hand side must be a type parameter: ";
reqt.dump(llvm::errs());
llvm::errs() << "\n";
dumpAndAbort();
}
if (!canSig->isReducedType(reqt.getFirstType())) {
llvm::errs() << "Left-hand side is not reduced: ";
reqt.dump(llvm::errs());
llvm::errs() << "\n";
dumpAndAbort();
}
}
// Check canonicalization of requirement itself.
switch (reqt.getKind()) {
case RequirementKind::SameShape:
if (!reqt.getFirstType()->is<GenericTypeParamType>()) {
llvm::errs() << "Left hand side is not a generic parameter: ";
reqt.dump(llvm::errs());
llvm::errs() << "\n";
dumpAndAbort();
}
if (!reqt.getFirstType()->isRootParameterPack()) {
llvm::errs() << "Left hand side is not a parameter pack: ";
reqt.dump(llvm::errs());
llvm::errs() << "\n";
dumpAndAbort();
}
if (!reqt.getSecondType()->is<GenericTypeParamType>()) {
llvm::errs() << "Right hand side is not a generic parameter: ";
reqt.dump(llvm::errs());
llvm::errs() << "\n";
dumpAndAbort();
}
if (!reqt.getSecondType()->isRootParameterPack()) {
llvm::errs() << "Right hand side is not a parameter pack: ";
reqt.dump(llvm::errs());
llvm::errs() << "\n";
dumpAndAbort();
}
break;
case RequirementKind::Superclass:
if (!canSig->isReducedType(reqt.getSecondType())) {
llvm::errs() << "Right-hand side is not reduced: ";
reqt.dump(llvm::errs());
llvm::errs() << "\n";
dumpAndAbort();
}
break;
case RequirementKind::Layout:
break;
case RequirementKind::SameType: {
auto hasReducedOrConcreteParent = [&](Type type) {
if (auto *dmt = type->getAs<DependentMemberType>()) {
return (canSig->isReducedType(dmt->getBase()) ||
canSig->isConcreteType(dmt->getBase()));
}
return type->is<GenericTypeParamType>();
};
auto firstType = reqt.getFirstType();
auto secondType = reqt.getSecondType();
auto canType = canSig->getReducedType(firstType);
auto &component = sameTypeComponents[canType];
if (!hasReducedOrConcreteParent(firstType)) {
llvm::errs() << "Left hand side does not have a reduced parent: ";
reqt.dump(llvm::errs());
llvm::errs() << "\n";
dumpAndAbort();
}
if (reqt.getSecondType()->isTypeParameter()) {
if (!hasReducedOrConcreteParent(secondType)) {
llvm::errs() << "Right hand side does not have a reduced parent: ";
reqt.dump(llvm::errs());
llvm::errs() << "\n";
dumpAndAbort();
}
if (compareDependentTypes(firstType, secondType) >= 0) {
llvm::errs() << "Out-of-order type parameters: ";
reqt.dump(llvm::errs());
llvm::errs() << "\n";
dumpAndAbort();
}
if (component.empty()) {
component.push_back(firstType);
} else if (!component.back()->isEqual(firstType)) {
llvm::errs() << "Same-type requirement within an equiv. class "
<< "is out-of-order: ";
reqt.dump(llvm::errs());
llvm::errs() << "\n";
dumpAndAbort();
}
component.push_back(secondType);
} else {
if (!canSig->isReducedType(secondType)) {
llvm::errs() << "Right hand side is not reduced: ";
reqt.dump(llvm::errs());
llvm::errs() << "\n";
dumpAndAbort();
}
if (component.empty()) {
component.push_back(secondType);
} else if (!component.back()->isEqual(secondType)) {
llvm::errs() << "Inconsistent concrete requirement in equiv. class: ";
reqt.dump(llvm::errs());
llvm::errs() << "\n";
dumpAndAbort();
}
}
break;
}
case RequirementKind::Conformance:
// Collect all conformance requirements on each type parameter.
conformances[CanType(reqt.getFirstType())].push_back(
reqt.getProtocolDecl());
break;
}