forked from swiftlang/swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathArchetypeBuilder.cpp
1843 lines (1552 loc) · 62.2 KB
/
ArchetypeBuilder.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
//===--- ArchetypeBuilder.cpp - Generic Requirement Builder ---------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// Support for collecting a set of generic requirements, both explicitly stated
// and inferred, and computing the archetypes and required witness tables from
// those requirements.
//
//===----------------------------------------------------------------------===//
#include "swift/AST/ArchetypeBuilder.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/DiagnosticsSema.h"
#include "swift/AST/DiagnosticEngine.h"
#include "swift/AST/Module.h"
#include "swift/AST/Pattern.h"
#include "swift/AST/ProtocolConformance.h"
#include "swift/AST/TypeRepr.h"
#include "swift/AST/TypeWalker.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/Support/raw_ostream.h"
#include <algorithm>
using namespace swift;
using llvm::DenseMap;
using NestedType = ArchetypeType::NestedType;
void RequirementSource::dump(SourceManager *srcMgr) const {
dump(llvm::errs(), srcMgr);
}
void RequirementSource::dump(llvm::raw_ostream &out,
SourceManager *srcMgr) const {
switch (getKind()) {
case Explicit:
out << "explicit";
break;
case Redundant:
out << "redundant";
break;
case Protocol:
out << "protocol";
break;
case Inferred:
out << "inferred";
break;
case OuterScope:
out << "outer";
break;
}
if (srcMgr && getLoc().isValid()) {
out << " @ ";
getLoc().dump(*srcMgr);
}
}
/// Update the recorded requirement source when a new requirement
/// source provides the same requirement.
static void updateRequirementSource(RequirementSource &source,
const RequirementSource &newSource) {
switch (newSource.getKind()) {
case RequirementSource::Explicit:
case RequirementSource::Redundant:
// Nothing to do; the new source is always redundant.
switch (source.getKind()) {
case RequirementSource::Explicit:
case RequirementSource::Redundant:
// Nothing to do.
break;
case RequirementSource::Inferred:
case RequirementSource::Protocol:
// Mark the original source as redundant.
source = RequirementSource(RequirementSource::Redundant,
newSource.getLoc());
break;
case RequirementSource::OuterScope:
// Leave the outer scope in place.
break;
}
break;
case RequirementSource::Inferred:
// A new inferred source will never override an existing source.
break;
case RequirementSource::Protocol: {
switch (source.getKind()) {
case RequirementSource::Explicit:
case RequirementSource::Redundant:
// The original source is redundant.
source.setKind(RequirementSource::Redundant);
break;
case RequirementSource::Protocol:
case RequirementSource::OuterScope:
// Keep the original source.
break;
case RequirementSource::Inferred:
// Replace the inferred source with the protocol source.
source = newSource;
break;
}
break;
}
case RequirementSource::OuterScope:
// An outer-scope source always overrides an existing source.
source = newSource;
break;
}
}
/// The identifying information for a generic parameter.
namespace {
struct GenericTypeParamKey {
unsigned Depth : 16;
unsigned Index : 16;
static GenericTypeParamKey forDecl(GenericTypeParamDecl *d) {
return {d->getDepth(), d->getIndex()};
}
static GenericTypeParamKey forType(GenericTypeParamType *t) {
return {t->getDepth(), t->getIndex()};
}
};
}
namespace llvm {
template<>
struct DenseMapInfo<GenericTypeParamKey> {
static inline GenericTypeParamKey getEmptyKey() { return {0xFFFF, 0xFFFF}; }
static inline GenericTypeParamKey getTombstoneKey() { return {0xFFFE, 0xFFFE}; }
static inline unsigned getHashValue(GenericTypeParamKey k) {
return DenseMapInfo<unsigned>::getHashValue(k.Depth << 16 | k.Index);
}
static bool isEqual(GenericTypeParamKey a, GenericTypeParamKey b) {
return a.Depth == b.Depth && a.Index == b.Index;
}
};
}
struct ArchetypeBuilder::Implementation {
/// A mapping from generic parameters to the corresponding potential
/// archetypes.
llvm::MapVector<GenericTypeParamKey, PotentialArchetype*> PotentialArchetypes;
/// A vector containing all of the archetypes, expanded out.
/// FIXME: This notion should go away, because it's impossible to expand
/// out "all" archetypes
SmallVector<ArchetypeType *, 4> AllArchetypes;
/// A vector containing the same-type requirements introduced into the
/// system.
SmallVector<SameTypeRequirement, 4> SameTypeRequirements;
/// The number of nested types that haven't yet been resolved to archetypes.
/// Once all requirements have been added, this will be zero in well-formed
/// code.
unsigned NumUnresolvedNestedTypes = 0;
};
ArchetypeBuilder::PotentialArchetype::~PotentialArchetype() {
for (const auto &nested : NestedTypes) {
for (auto pa : nested.second) {
if (pa != this)
delete pa;
}
}
}
void ArchetypeBuilder::PotentialArchetype::buildFullName(
bool forDebug,
SmallVectorImpl<char> &result) const {
if (auto parent = getParent()) {
parent->buildFullName(forDebug, result);
// When building the name for debugging purposes, include the
// protocol into which the associated type was resolved.
if (forDebug) {
if (auto assocType = getResolvedAssociatedType()) {
result.push_back('[');
result.push_back('.');
result.append(assocType->getProtocol()->getName().str().begin(),
assocType->getProtocol()->getName().str().end());
result.push_back(']');
}
}
result.push_back('.');
}
result.append(getName().str().begin(), getName().str().end());
}
Identifier ArchetypeBuilder::PotentialArchetype::getName() const {
if (auto assocType = NameOrAssociatedType.dyn_cast<AssociatedTypeDecl *>())
return assocType->getName();
return NameOrAssociatedType.get<Identifier>();
}
std::string ArchetypeBuilder::PotentialArchetype::getFullName() const {
llvm::SmallString<64> result;
buildFullName(false, result);
return result.str().str();
}
std::string ArchetypeBuilder::PotentialArchetype::getDebugName() const {
llvm::SmallString<64> result;
buildFullName(true, result);
return result.str().str();
}
unsigned ArchetypeBuilder::PotentialArchetype::getNestingDepth() const {
unsigned Depth = 0;
for (auto P = getParent(); P; P = P->getParent())
++Depth;
return Depth;
}
void ArchetypeBuilder::PotentialArchetype::resolveAssociatedType(
AssociatedTypeDecl *assocType,
ArchetypeBuilder &builder) {
assert(!NameOrAssociatedType.is<AssociatedTypeDecl *>() &&
"associated type is already resolved");
NameOrAssociatedType = assocType;
assert(builder.Impl->NumUnresolvedNestedTypes > 0 &&
"Mismatch in number of unresolved nested types");
--builder.Impl->NumUnresolvedNestedTypes;
}
bool ArchetypeBuilder::PotentialArchetype::addConformance(
ProtocolDecl *proto,
const RequirementSource &source,
ArchetypeBuilder &builder) {
auto rep = getRepresentative();
if (rep != this)
return rep->addConformance(proto, source, builder);
// Check whether we already know about this conformance.
auto known = ConformsTo.find(proto);
if (known != ConformsTo.end()) {
// We already have this requirement. Update the requirement source
// appropriately.
updateRequirementSource(known->second, source);
return false;
}
// Add this conformance.
ConformsTo.insert(std::make_pair(proto, source));
// Check whether any associated types in this protocol resolve
// nested types of this potential archetype.
for (auto member : proto->getMembers()) {
auto assocType = dyn_cast<AssociatedTypeDecl>(member);
if (!assocType)
continue;
auto known = NestedTypes.find(assocType->getName());
if (known == NestedTypes.end())
continue;
// If the nested type was not already resolved, do so now.
if (!known->second.front()->getResolvedAssociatedType()) {
known->second.front()->resolveAssociatedType(assocType, builder);
continue;
}
// Otherwise, create a new potential archetype for this associated type
// and make it equivalent to the first potential archetype we encountered.
auto otherPA = new PotentialArchetype(this, assocType);
auto frontRep = known->second.front()->getRepresentative();
otherPA->Representative = frontRep;
frontRep->EquivalenceClass.push_back(otherPA);
otherPA->SameTypeSource = RequirementSource(RequirementSource::Inferred,
source.getLoc());
known->second.push_back(otherPA);
}
return true;
}
auto ArchetypeBuilder::PotentialArchetype::getRepresentative()
-> PotentialArchetype *{
// Find the representative.
PotentialArchetype *Result = Representative;
while (Result != Result->Representative)
Result = Result->Representative;
// Perform (full) path compression.
PotentialArchetype *FixUp = this;
while (FixUp != FixUp->Representative) {
PotentialArchetype *Next = FixUp->Representative;
FixUp->Representative = Result;
FixUp = Next;
}
return Result;
}
bool ArchetypeBuilder::PotentialArchetype::hasConcreteTypeInPath() const {
for (auto pa = this; pa; pa = pa->getParent()) {
if (pa->ArchetypeOrConcreteType.isConcreteType() &&
!pa->ArchetypeOrConcreteType.getAsConcreteType()->is<ArchetypeType>())
return true;
}
return false;
}
bool ArchetypeBuilder::PotentialArchetype::isBetterArchetypeAnchor(
PotentialArchetype *other) {
auto concrete = hasConcreteTypeInPath();
auto otherConcrete = other->hasConcreteTypeInPath();
if (concrete != otherConcrete)
return otherConcrete;
// FIXME: Not a total order.
return std::make_tuple(getRootParam()->getDepth(),
getRootParam()->getIndex(),
getNestingDepth())
< std::make_tuple(other->getRootParam()->getDepth(),
other->getRootParam()->getIndex(),
other->getNestingDepth());
}
auto ArchetypeBuilder::PotentialArchetype::getArchetypeAnchor()
-> PotentialArchetype * {
// Default to the representative, unless we find something better.
PotentialArchetype *best = getRepresentative();
for (auto pa : getEquivalenceClass()) {
if (pa->isBetterArchetypeAnchor(best))
best = pa;
}
return best;
}
auto ArchetypeBuilder::PotentialArchetype::getNestedType(
Identifier nestedName,
ArchetypeBuilder &builder) -> PotentialArchetype * {
// Retrieve the nested type from the representation of this set.
if (Representative != this)
return getRepresentative()->getNestedType(nestedName, builder);
llvm::TinyPtrVector<PotentialArchetype *> &nested = NestedTypes[nestedName];
if (!nested.empty()) {
return nested.front();
}
// Attempt to resolve this nested type to an associated type
// of one of the protocols to which the parent potential
// archetype conforms.
for (const auto &conforms : ConformsTo) {
for (auto member : conforms.first->lookupDirect(nestedName)) {
auto assocType = dyn_cast<AssociatedTypeDecl>(member);
if (!assocType)
continue;
// Resolve this nested type to this associated type.
auto pa = new PotentialArchetype(this, assocType);
// If we have resolved this nested type to more than one associated
// type, create same-type constraints between them.
if (!nested.empty()) {
pa->Representative = nested.front()->getRepresentative();
pa->Representative->EquivalenceClass.push_back(pa);
pa->SameTypeSource = RequirementSource(RequirementSource::Inferred,
SourceLoc());
}
// Add this resolved nested type.
nested.push_back(pa);
}
}
// We couldn't resolve the nested type yet, so create an
// unresolved associated type.
if (nested.empty()) {
nested.push_back(new PotentialArchetype(this, nestedName));
++builder.Impl->NumUnresolvedNestedTypes;
}
return nested.front();
}
/// Replace dependent types with their archetypes or concrete types.
static Type substConcreteTypesForDependentTypes(ArchetypeBuilder &builder,
Type type) {
return type.transform([&](Type type) -> Type {
if (auto depMemTy = type->getAs<DependentMemberType>()) {
auto newBase = substConcreteTypesForDependentTypes(builder,
depMemTy->getBase());
return depMemTy->substBaseType(&builder.getModule(), newBase,
builder.getLazyResolver());
}
if (auto typeParam = type->getAs<GenericTypeParamType>()) {
auto potentialArchetype = builder.resolveArchetype(typeParam);
return potentialArchetype->getType(builder).getValue();
}
return type;
});
}
ArchetypeType::NestedType
ArchetypeBuilder::PotentialArchetype::getType(ArchetypeBuilder &builder) {
auto representative = getRepresentative();
// Retrieve the archetype from the archetype anchor in this equivalence class.
auto archetypeAnchor = getArchetypeAnchor();
if (archetypeAnchor != this)
return archetypeAnchor->getType(builder);
// Return a concrete type or archetype we've already resolved.
if (representative->ArchetypeOrConcreteType) {
// If the concrete type is dependent, substitute dependent types
// for archetypes.
if (auto concreteType
= representative->ArchetypeOrConcreteType.getAsConcreteType()) {
if (concreteType->hasTypeParameter()) {
// If we already know the concrete type is recursive, just
// return an error. It will be diagnosed elsewhere.
if (representative->RecursiveConcreteType) {
return NestedType::forConcreteType(
ErrorType::get(builder.getASTContext()));
}
// If we're already substituting a concrete type, mark this
// potential archetype as having a recursive concrete type.
if (representative->SubstitutingConcreteType) {
representative->RecursiveConcreteType = true;
return NestedType::forConcreteType(
ErrorType::get(builder.getASTContext()));
}
representative->SubstitutingConcreteType = true;
NestedType result = NestedType::forConcreteType(
substConcreteTypesForDependentTypes(
builder,
concreteType));
representative->SubstitutingConcreteType = false;
// If all went well, we're done.
if (!representative->RecursiveConcreteType)
return result;
// Otherwise, we found that the concrete type is recursive,
// complain and return an error.
builder.Diags.diagnose(SameTypeSource->getLoc(),
diag::recursive_same_type_constraint,
getDependentType(builder, false),
concreteType);
return NestedType::forConcreteType(
ErrorType::get(builder.getASTContext()));
}
}
return representative->ArchetypeOrConcreteType;
}
ArchetypeType::AssocTypeOrProtocolType assocTypeOrProto = RootProtocol;
// Allocate a new archetype.
ArchetypeType *ParentArchetype = nullptr;
auto &mod = builder.getModule();
if (auto parent = getParent()) {
assert(assocTypeOrProto.isNull() &&
"root protocol type given for non-root archetype");
auto parentTy = parent->getType(builder);
if (!parentTy)
return NestedType::forConcreteType(
ErrorType::get(builder.getASTContext()));
ParentArchetype = parentTy.getAsArchetype();
if (!ParentArchetype) {
// We might have an outer archetype as a concrete type here; if so, just
// return that.
ParentArchetype = parentTy.getValue()->getAs<ArchetypeType>();
if (ParentArchetype) {
representative->ArchetypeOrConcreteType
= NestedType::forConcreteType(
ParentArchetype->getNestedTypeValue(getName()));
return representative->ArchetypeOrConcreteType;
}
LazyResolver *resolver = builder.getLazyResolver();
assert(resolver && "need a lazy resolver");
(void) resolver;
// Resolve the member type.
auto depMemberType = getDependentType(builder, false)
->castTo<DependentMemberType>();
Type memberType = depMemberType->substBaseType(
&mod,
parent->ArchetypeOrConcreteType.getAsConcreteType(),
builder.getLazyResolver());
if (auto memberPA = builder.resolveArchetype(memberType)) {
// If the member type maps to an archetype, resolve that archetype.
if (memberPA->getRepresentative() != getRepresentative()) {
representative->ArchetypeOrConcreteType = memberPA->getType(builder);
return representative->ArchetypeOrConcreteType;
}
llvm_unreachable("we have no parent archetype");
} else {
// Otherwise, it's a concrete type.
representative->ArchetypeOrConcreteType
= NestedType::forConcreteType(
builder.substDependentType(memberType));
return representative->ArchetypeOrConcreteType;
}
}
assocTypeOrProto = getResolvedAssociatedType();
}
// If we ended up building our parent archetype, then we'll have
// already filled in our own archetype.
if (auto arch = representative->ArchetypeOrConcreteType.getAsArchetype())
return NestedType::forArchetype(arch);
SmallVector<ProtocolDecl *, 4> Protos;
for (const auto &conforms : ConformsTo) {
Protos.push_back(conforms.first);
}
auto arch
= ArchetypeType::getNew(builder.getASTContext(), ParentArchetype,
assocTypeOrProto, getName(), Protos,
Superclass, isRecursive());
representative->ArchetypeOrConcreteType = NestedType::forArchetype(arch);
// Collect the set of nested types of this archetype, and put them into
// the archetype itself.
if (!NestedTypes.empty()) {
builder.getASTContext().registerLazyArchetype(arch, builder, this);
SmallVector<std::pair<Identifier, NestedType>, 4> FlatNestedTypes;
for (auto Nested : NestedTypes) {
bool anyNotRenamed = false;
for (auto NestedPA : Nested.second) {
if (!NestedPA->wasRenamed()) {
anyNotRenamed = true;
break;
}
}
if (!anyNotRenamed)
continue;
FlatNestedTypes.push_back({ Nested.first, NestedType() });
}
arch->setNestedTypes(builder.getASTContext(), FlatNestedTypes);
// Force the resolution of the nested types.
(void)arch->getNestedTypes();
builder.getASTContext().unregisterLazyArchetype(arch);
}
return NestedType::forArchetype(arch);
}
Type ArchetypeBuilder::PotentialArchetype::getDependentType(
ArchetypeBuilder &builder,
bool allowUnresolved) {
if (auto parent = getParent()) {
Type parentType = parent->getDependentType(builder, allowUnresolved);
if (parentType->is<ErrorType>())
return parentType;
// If we've resolved to an associated type, use it.
if (auto assocType = getResolvedAssociatedType())
return DependentMemberType::get(parentType, assocType, builder.Context);
// If typo correction renamed this type, get the renamed type.
if (wasRenamed())
return parent->getNestedType(getName(), builder)
->getDependentType(builder, allowUnresolved);
// If we don't allow unresolved dependent member types, fail.
if (!allowUnresolved)
return ErrorType::get(builder.Context);
return DependentMemberType::get(parentType, getName(), builder.Context);
}
assert(getGenericParam() && "Not a generic parameter?");
return getGenericParam();
}
void ArchetypeBuilder::PotentialArchetype::dump(llvm::raw_ostream &Out,
SourceManager *SrcMgr,
unsigned Indent) {
// Print name.
Out.indent(Indent) << getName();
// Print superclass.
if (Superclass) {
Out << " : ";
Superclass.print(Out);
Out << " [";
SuperclassSource->dump(Out, SrcMgr);
Out << "]";
}
// Print requirements.
if (!ConformsTo.empty()) {
Out << " : ";
if (ConformsTo.size() != 1)
Out << "protocol<";
bool First = true;
for (const auto &ProtoAndSource : ConformsTo) {
if (First)
First = false;
else
Out << ", ";
Out << ProtoAndSource.first->getName().str() << " [";
ProtoAndSource.second.dump(Out, SrcMgr);
Out << "]";
}
if (ConformsTo.size() != 1)
Out << ">";
}
if (Representative != this) {
Out << " [represented by " << getRepresentative()->getFullName() << "]";
}
Out << "\n";
// Print nested types.
for (const auto &nestedVec : NestedTypes) {
for (auto nested : nestedVec.second) {
nested->dump(Out, SrcMgr, Indent + 2);
}
}
}
ArchetypeBuilder::ArchetypeBuilder(Module &mod, DiagnosticEngine &diags)
: Mod(mod), Context(mod.getASTContext()), Diags(diags),
Impl(new Implementation)
{
}
ArchetypeBuilder::ArchetypeBuilder(ArchetypeBuilder &&) = default;
ArchetypeBuilder::~ArchetypeBuilder() {
if (!Impl)
return;
for (auto PA : Impl->PotentialArchetypes)
delete PA.second;
}
LazyResolver *ArchetypeBuilder::getLazyResolver() const {
return Context.getLazyResolver();
}
auto ArchetypeBuilder::resolveArchetype(Type type) -> PotentialArchetype * {
if (auto genericParam = type->getAs<GenericTypeParamType>()) {
auto known
= Impl->PotentialArchetypes.find(GenericTypeParamKey::forType(genericParam));
if (known == Impl->PotentialArchetypes.end())
return nullptr;
return known->second;
}
if (auto dependentMember = type->getAs<DependentMemberType>()) {
auto base = resolveArchetype(dependentMember->getBase());
if (!base)
return nullptr;
return base->getNestedType(dependentMember->getName(), *this);
}
return nullptr;
}
auto ArchetypeBuilder::addGenericParameter(GenericTypeParamType *GenericParam,
ProtocolDecl *RootProtocol,
Identifier ParamName)
-> PotentialArchetype *
{
GenericTypeParamKey Key{GenericParam->getDepth(), GenericParam->getIndex()};
// Create a potential archetype for this type parameter.
assert(!Impl->PotentialArchetypes[Key]);
auto PA = new PotentialArchetype(GenericParam, RootProtocol, ParamName);
Impl->PotentialArchetypes[Key] = PA;
return PA;
}
bool ArchetypeBuilder::addGenericParameter(GenericTypeParamDecl *GenericParam) {
ProtocolDecl *RootProtocol = dyn_cast<ProtocolDecl>(GenericParam->getDeclContext());
if (!RootProtocol) {
if (auto Ext = dyn_cast<ExtensionDecl>(GenericParam->getDeclContext()))
RootProtocol = dyn_cast_or_null<ProtocolDecl>(Ext->getExtendedType()->getAnyNominal());
}
PotentialArchetype *PA
= addGenericParameter(
GenericParam->getDeclaredType()->castTo<GenericTypeParamType>(),
RootProtocol,
GenericParam->getName());
if (!PA)
return true;
// Add the requirements from the declaration.
llvm::SmallPtrSet<ProtocolDecl *, 8> visited;
return addAbstractTypeParamRequirements(GenericParam, PA,
RequirementSource::Explicit,
visited);
}
bool ArchetypeBuilder::addGenericParameter(GenericTypeParamType *GenericParam) {
auto name = GenericParam->getName();
// Trim '$' so that archetypes are more readily discernible from abstract
// parameters.
if (name.str().startswith("$"))
name = Context.getIdentifier(name.str().slice(1, name.str().size()));
PotentialArchetype *PA = addGenericParameter(GenericParam,
nullptr,
name);
return !PA;
}
bool ArchetypeBuilder::addConformanceRequirement(PotentialArchetype *PAT,
ProtocolDecl *Proto,
RequirementSource Source) {
llvm::SmallPtrSet<ProtocolDecl *, 8> Visited;
return addConformanceRequirement(PAT, Proto, Source, Visited);
}
bool ArchetypeBuilder::addConformanceRequirement(PotentialArchetype *PAT,
ProtocolDecl *Proto,
RequirementSource Source,
llvm::SmallPtrSetImpl<ProtocolDecl *> &Visited) {
// Add the requirement to the representative.
auto T = PAT->getRepresentative();
// Add the requirement, if we haven't done so already.
if (!T->addConformance(Proto, Source, *this))
return false;
RequirementSource InnerSource(RequirementSource::Protocol, Source.getLoc());
bool inserted = Visited.insert(Proto).second;
assert(inserted);
(void) inserted;
// Add all of the inherited protocol requirements, recursively.
if (auto resolver = getLazyResolver())
resolver->resolveInheritedProtocols(Proto);
for (auto InheritedProto : Proto->getInheritedProtocols(getLazyResolver())) {
if (Visited.count(InheritedProto))
continue;
if (addConformanceRequirement(T, InheritedProto, InnerSource, Visited))
return true;
}
// Add requirements for each of the associated types.
// FIXME: This should use the generic signature, not walk the members.
for (auto Member : Proto->getMembers()) {
if (auto AssocType = dyn_cast<AssociatedTypeDecl>(Member)) {
// Add requirements placed directly on this associated type.
auto AssocPA = T->getNestedType(AssocType->getName(), *this);
if (AssocPA != T) {
if (addAbstractTypeParamRequirements(AssocType, AssocPA,
RequirementSource::Protocol,
Visited))
return true;
}
continue;
}
// FIXME: Requirement declarations.
}
Visited.erase(Proto);
return false;
}
bool ArchetypeBuilder::addSuperclassRequirement(PotentialArchetype *T,
Type Superclass,
RequirementSource Source) {
// If T already has a superclass, make sure it's related.
if (T->Superclass) {
if (T->Superclass->isSuperclassOf(Superclass, nullptr)) {
T->Superclass = Superclass;
} else if (!Superclass->isSuperclassOf(T->Superclass, nullptr)) {
Diags.diagnose(Source.getLoc(),
diag::requires_superclass_conflict, T->getName(),
T->Superclass, Superclass)
.highlight(T->SuperclassSource->getLoc());
return true;
}
updateRequirementSource(*T->SuperclassSource, Source);
return false;
}
// Set the superclass.
T->Superclass = Superclass;
T->SuperclassSource = Source;
return false;
}
bool ArchetypeBuilder::addSameTypeRequirementBetweenArchetypes(
PotentialArchetype *T1,
PotentialArchetype *T2,
RequirementSource Source)
{
auto OrigT1 = T1, OrigT2 = T2;
// Operate on the representatives
T1 = T1->getRepresentative();
T2 = T2->getRepresentative();
// If the representives are already the same, we're done.
if (T1 == T2)
return false;
// Decide which potential archetype is to be considered the representative.
// We necessarily prefer potential archetypes rooted at parameters that come
// from outer generic parameter lists, since those generic parameters will
// have archetypes bound in the outer context.
// FIXME: This isn't a total ordering
auto T1Param = T1->getRootParam();
auto T2Param = T2->getRootParam();
unsigned T1Depth = T1->getNestingDepth();
unsigned T2Depth = T2->getNestingDepth();
if (std::make_tuple(T2->wasRenamed(), T2Param->getDepth(),
T2Param->getIndex(), T2Depth)
< std::make_tuple(T1->wasRenamed(), T1Param->getDepth(),
T1Param->getIndex(), T1Depth))
std::swap(T1, T2);
// Don't allow two generic parameters to be equivalent, because then we
// don't actually have two parameters.
// FIXME: Should we simply allow this?
if (T1Depth == 0 && T2Depth == 0) {
Diags.diagnose(Source.getLoc(), diag::requires_generic_params_made_equal,
T1->getName(), T2->getName());
return true;
}
// Merge any concrete constraints.
Type concrete1 = T1->ArchetypeOrConcreteType.getAsConcreteType();
Type concrete2 = T2->ArchetypeOrConcreteType.getAsConcreteType();
if (concrete1 && concrete2) {
if (!concrete1->isEqual(concrete2)) {
Diags.diagnose(Source.getLoc(), diag::requires_same_type_conflict,
T1->getName(), concrete1, concrete2);
return true;
}
} else if (concrete1) {
assert(!T2->ArchetypeOrConcreteType
&& "already formed archetype for concrete-constrained parameter");
T2->ArchetypeOrConcreteType = NestedType::forConcreteType(concrete1);
T2->SameTypeSource = T1->SameTypeSource;
} else if (concrete2) {
assert(!T1->ArchetypeOrConcreteType
&& "already formed archetype for concrete-constrained parameter");
T1->ArchetypeOrConcreteType = NestedType::forConcreteType(concrete2);
T1->SameTypeSource = T2->SameTypeSource;
}
// Make T1 the representative of T2, merging the equivalence classes.
T2->Representative = T1;
T2->SameTypeSource = Source;
for (auto equiv : T2->EquivalenceClass)
T1->EquivalenceClass.push_back(equiv);
if (!T1->wasRenamed() && !T2->wasRenamed()) {
// Record this same-type requirement.
Impl->SameTypeRequirements.push_back({ OrigT1, OrigT2 });
}
// FIXME: superclass requirements!
// Add all of the protocol conformance requirements of T2 to T1.
for (auto conforms : T2->ConformsTo) {
T1->addConformance(conforms.first, conforms.second, *this);
}
// Recursively merge the associated types of T2 into T1.
RequirementSource inferredSource(RequirementSource::Inferred, SourceLoc());
for (auto T2Nested : T2->NestedTypes) {
auto T1Nested = T1->getNestedType(T2Nested.first, *this);
if (addSameTypeRequirementBetweenArchetypes(T1Nested,
T2Nested.second.front(),
inferredSource))
return true;
}
return false;
}
bool ArchetypeBuilder::addSameTypeRequirementToConcrete(
PotentialArchetype *T,
Type Concrete,
RequirementSource Source) {
// Operate on the representative.
auto OrigT = T;
T = T->getRepresentative();
assert(!T->ArchetypeOrConcreteType.getAsArchetype()
&& "already formed archetype for concrete-constrained parameter");
// If we've already been bound to a type, we're either done, or we have a
// problem.
if (auto oldConcrete = T->ArchetypeOrConcreteType.getAsConcreteType()) {
if (!oldConcrete->isEqual(Concrete)) {
Diags.diagnose(Source.getLoc(), diag::requires_same_type_conflict,
T->getName(), oldConcrete, Concrete);
return true;
}
return false;
}
// Don't allow a generic parameter to be equivalent to a concrete type,
// because then we don't actually have a parameter.
// FIXME: Should we simply allow this?
if (T->getNestingDepth() == 0) {
Diags.diagnose(Source.getLoc(),
diag::requires_generic_param_made_equal_to_concrete,
T->getName());
return true;
}
// Make sure the concrete type fulfills the requirements on the archetype.
DenseMap<ProtocolDecl *, ProtocolConformance*> conformances;
if (!Concrete->is<ArchetypeType>()) {
for (auto conforms : T->getConformsTo()) {
auto protocol = conforms.first;
auto conformance = Mod.lookupConformance(Concrete, protocol,
getLazyResolver());
if (conformance.getInt() == ConformanceKind::DoesNotConform) {
Diags.diagnose(Source.getLoc(),
diag::requires_generic_param_same_type_does_not_conform,
Concrete, protocol->getName());
return true;
}
assert(conformance.getPointer() && "No conformance pointer?");
conformances[protocol] = conformance.getPointer();
}
}
// Record the requirement.
T->ArchetypeOrConcreteType = NestedType::forConcreteType(Concrete);
T->SameTypeSource = Source;
Impl->SameTypeRequirements.push_back({OrigT, Concrete});
// Recursively resolve the associated types to their concrete types.
for (auto nested : T->getNestedTypes()) {
AssociatedTypeDecl *assocType
= nested.second.front()->getResolvedAssociatedType();
if (auto *concreteArchetype = Concrete->getAs<ArchetypeType>()) {