-
Notifications
You must be signed in to change notification settings - Fork 10.4k
/
Copy pathGenericEnvironment.cpp
799 lines (657 loc) · 26.7 KB
/
GenericEnvironment.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
//===--- GenericEnvironment.cpp - GenericEnvironment 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 GenericEnvironment class.
//
//===----------------------------------------------------------------------===//
#include "swift/AST/GenericEnvironment.h"
#include "swift/AST/GenericSignature.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/ExistentialLayout.h"
#include "swift/AST/ProtocolConformance.h"
#include "swift/AST/TypeTransform.h"
#include "swift/Basic/Assertions.h"
#include "swift/Basic/Defer.h"
using namespace swift;
size_t GenericEnvironment::numTrailingObjects(
OverloadToken<SubstitutionMap>) const {
switch (getKind()) {
case Kind::Primary:
return 0;
case Kind::OpenedExistential:
case Kind::OpenedElement:
case Kind::Opaque:
return 1;
}
}
size_t GenericEnvironment::numTrailingObjects(
OverloadToken<OpaqueEnvironmentData>) const {
switch (getKind()) {
case Kind::Primary:
case Kind::OpenedExistential:
case Kind::OpenedElement:
return 0;
case Kind::Opaque:
return 1;
}
}
size_t GenericEnvironment::numTrailingObjects(
OverloadToken<OpenedExistentialEnvironmentData>) const {
switch (getKind()) {
case Kind::Primary:
case Kind::Opaque:
case Kind::OpenedElement:
return 0;
case Kind::OpenedExistential:
return 1;
}
}
size_t GenericEnvironment::numTrailingObjects(
OverloadToken<OpenedElementEnvironmentData>) const {
switch (getKind()) {
case Kind::Primary:
case Kind::Opaque:
case Kind::OpenedExistential:
return 0;
case Kind::OpenedElement:
return 1;
}
}
size_t GenericEnvironment::numTrailingObjects(OverloadToken<Type>) const {
return getGenericParams().size()
+ (getKind() == Kind::OpenedElement ? getNumOpenedPackParams() : 0);
}
/// Retrieve the array containing the context types associated with the
/// generic parameters, stored in parallel with the generic parameters of the
/// generic signature.
MutableArrayRef<Type> GenericEnvironment::getContextTypes() {
return MutableArrayRef<Type>(getTrailingObjects<Type>(),
getGenericParams().size());
}
/// Retrieve the array containing the context types associated with the
/// generic parameters, stored in parallel with the generic parameters of the
/// generic signature.
ArrayRef<Type> GenericEnvironment::getContextTypes() const {
return ArrayRef<Type>(getTrailingObjects<Type>(),
getGenericParams().size());
}
unsigned GenericEnvironment::getNumOpenedPackParams() const {
assert(getKind() == Kind::OpenedElement);
return getGenericSignature().getInnermostGenericParams().size();
}
MutableArrayRef<Type> GenericEnvironment::getOpenedPackParams() {
auto begin = getTrailingObjects<Type>() + getGenericParams().size();
return MutableArrayRef<Type>(begin, getNumOpenedPackParams());
}
ArrayRef<Type> GenericEnvironment::getOpenedPackParams() const {
auto begin = getTrailingObjects<Type>() + getGenericParams().size();
return ArrayRef<Type>(begin, getNumOpenedPackParams());
}
ArrayRef<GenericTypeParamType *>
GenericEnvironment::getGenericParams() const {
return getGenericSignature().getGenericParams();
}
SubstitutionMap GenericEnvironment::getOuterSubstitutions() const {
assert(getKind() != Kind::Primary);
return *getTrailingObjects<SubstitutionMap>();
}
OpaqueTypeDecl *GenericEnvironment::getOpaqueTypeDecl() const {
assert(getKind() == Kind::Opaque);
return getTrailingObjects<OpaqueEnvironmentData>()->decl;
}
CanGenericTypeParamType
GenericEnvironment::getOpenedElementShapeClass() const {
assert(getKind() == Kind::OpenedElement);
auto environmentData = getTrailingObjects<OpenedElementEnvironmentData>();
return environmentData->shapeClass;
}
Type GenericEnvironment::getOpenedExistentialType() const {
assert(getKind() == Kind::OpenedExistential);
return getTrailingObjects<OpenedExistentialEnvironmentData>()->existential;
}
UUID GenericEnvironment::getOpenedExistentialUUID() const {
assert(getKind() == Kind::OpenedExistential);
return getTrailingObjects<OpenedExistentialEnvironmentData>()->uuid;
}
UUID GenericEnvironment::getOpenedElementUUID() const {
assert(getKind() == Kind::OpenedElement);
return getTrailingObjects<OpenedElementEnvironmentData>()->uuid;
}
void GenericEnvironment::forEachPackElementArchetype(
llvm::function_ref<void(ElementArchetypeType *)> function) const {
auto packElements = getGenericSignature().getInnermostGenericParams();
for (auto eltInterfaceType: packElements) {
auto *elementArchetype =
mapTypeIntoContext(eltInterfaceType)->castTo<ElementArchetypeType>();
function(elementArchetype);
}
}
void GenericEnvironment::forEachPackElementGenericTypeParam(
llvm::function_ref<void(GenericTypeParamType *)> function) const {
auto sig = getGenericSignature();
auto shapeClass = getOpenedElementShapeClass();
auto packElements = sig.getInnermostGenericParams();
auto packElementDepth = packElements.front()->getDepth();
// Each parameter pack in the outer generic parameters has
// a corresponding pack element parameter at the innermost
// depth.
for (auto *genericParam : getGenericParams()) {
if (genericParam->getDepth() == packElementDepth)
break;
if (!genericParam->isParameterPack())
continue;
// Only include opened element parameters for packs in the given
// shape equivalence class.
if (!sig->haveSameShape(genericParam, shapeClass))
continue;
function(genericParam);
}
}
void GenericEnvironment::forEachPackElementBinding(
PackElementBindingCallback function) const {
auto sig = getGenericSignature();
auto packElements = sig.getInnermostGenericParams();
auto elementIt = packElements.begin();
forEachPackElementGenericTypeParam([&](auto *genericParam) {
assert(elementIt != packElements.end());
auto *elementArchetype =
mapTypeIntoContext(*elementIt++)->castTo<ElementArchetypeType>();
auto *packSubstitution = maybeApplyOuterContextSubstitutions(genericParam)
->getPackSubstitutionAsPackType();
function(elementArchetype, packSubstitution);
});
assert(elementIt == packElements.end());
}
GenericEnvironment::GenericEnvironment(GenericSignature signature)
: SignatureAndKind(signature, Kind::Primary)
{
// Clear out the memory that holds the context types.
std::uninitialized_fill(getContextTypes().begin(), getContextTypes().end(),
Type());
}
GenericEnvironment::GenericEnvironment(
GenericSignature signature,
Type existential, SubstitutionMap subs, UUID uuid)
: SignatureAndKind(signature, Kind::OpenedExistential)
{
*getTrailingObjects<SubstitutionMap>() = subs;
new (getTrailingObjects<OpenedExistentialEnvironmentData>())
OpenedExistentialEnvironmentData{ existential, uuid };
// Clear out the memory that holds the context types.
std::uninitialized_fill(getContextTypes().begin(), getContextTypes().end(),
Type());
}
GenericEnvironment::GenericEnvironment(
GenericSignature signature, OpaqueTypeDecl *opaque, SubstitutionMap subs)
: SignatureAndKind(signature, Kind::Opaque)
{
*getTrailingObjects<SubstitutionMap>() = subs;
new (getTrailingObjects<OpaqueEnvironmentData>())
OpaqueEnvironmentData{opaque};
// Clear out the memory that holds the context types.
std::uninitialized_fill(getContextTypes().begin(), getContextTypes().end(),
Type());
}
GenericEnvironment::GenericEnvironment(GenericSignature signature,
UUID uuid,
CanGenericTypeParamType shapeClass,
SubstitutionMap outerSubs)
: SignatureAndKind(signature, Kind::OpenedElement)
{
*getTrailingObjects<SubstitutionMap>() = outerSubs;
new (getTrailingObjects<OpenedElementEnvironmentData>())
OpenedElementEnvironmentData{uuid, shapeClass};
// Clear out the memory that holds the context types.
std::uninitialized_fill(getContextTypes().begin(), getContextTypes().end(),
Type());
// Fill in the array of opened pack parameters.
auto openedPacksBuffer = getOpenedPackParams();
unsigned i = 0;
for (auto param : signature.getGenericParams()) {
if (!param->isParameterPack()) continue;
if (!signature->haveSameShape(param, shapeClass)) continue;
openedPacksBuffer[i++] = param;
}
assert(i == openedPacksBuffer.size());
}
class GenericEnvironment::NestedTypeStorage
: public llvm::DenseMap<CanType, Type> { };
void GenericEnvironment::addMapping(CanType depType, Type contextType) {
if (auto genericParam = dyn_cast<GenericTypeParamType>(depType)) {
GenericParamKey key(genericParam);
// Find the index into the parallel arrays of generic parameters and
// context types.
auto genericParams = getGenericParams();
unsigned index = key.findIndexIn(genericParams);
assert(genericParams[index] == key && "Bad generic parameter");
// Add the mapping from the generic parameter to the context type.
assert(getContextTypes()[index].isNull() ||
getContextTypes()[index]->is<ErrorType>() &&
"Already recoded this mapping");
getContextTypes()[index] = contextType;
} else {
getOrCreateNestedTypeStorage()[depType] = contextType;
}
}
Type GenericEnvironment::getMappingIfPresent(CanType depType) const {
if (auto genericParam = dyn_cast<GenericTypeParamType>(depType)) {
GenericParamKey key(genericParam);
// Find the index into the parallel arrays of generic parameters and
// context types.
auto genericParams = getGenericParams();
unsigned index = key.findIndexIn(genericParams);
assert(genericParams[index] == key && "Bad generic parameter");
return getContextTypes()[index];
} else {
auto &storage = const_cast<GenericEnvironment *>(this)
->getOrCreateNestedTypeStorage();
auto found = storage.find(depType);
if (found != storage.end())
return found->second;
return Type();
}
}
Type
GenericEnvironment::maybeApplyOuterContextSubstitutions(Type type) const {
switch (getKind()) {
case Kind::Primary:
return type;
case Kind::OpenedExistential:
case Kind::OpenedElement:
case Kind::Opaque: {
OuterSubstitutions replacer{
getOuterSubstitutions(), getGenericSignature()->getMaxDepth()};
return type.subst(replacer, replacer);
}
}
}
Type GenericEnvironment::mapTypeIntoContext(GenericEnvironment *env,
Type type) {
assert(!type->hasPrimaryArchetype() && "already have a contextual type");
if (!env) {
assert(!type->hasTypeParameter() &&
"no generic environment provided for type with type parameters");
return type;
}
return env->mapTypeIntoContext(type);
}
Type MapTypeOutOfContext::operator()(SubstitutableType *type) const {
if (isa<PrimaryArchetypeType>(type) ||
isa<PackArchetypeType>(type)) {
return cast<ArchetypeType>(type)->getInterfaceType();
}
return type;
}
Type TypeBase::mapTypeOutOfContext() {
assert(!hasTypeParameter() && "already have an interface type");
return Type(this).subst(MapTypeOutOfContext(),
MakeAbstractConformanceForGenericType(),
SubstFlags::PreservePackExpansionLevel |
SubstFlags::SubstitutePrimaryArchetypes);
}
auto GenericEnvironment::getOrCreateNestedTypeStorage() -> NestedTypeStorage & {
if (nestedTypeStorage)
return *nestedTypeStorage;
nestedTypeStorage = new NestedTypeStorage();
ASTContext &ctx = getGenericParams().front()->getASTContext();
ctx.addCleanup([nestedTypeStorage=this->nestedTypeStorage]() {
delete nestedTypeStorage;
});
return *nestedTypeStorage;
}
Type
GenericEnvironment::getOrCreateArchetypeFromInterfaceType(Type depType) {
auto canType = depType->getCanonicalType();
// Have we seen this exact type parameter before?
if (auto type = getMappingIfPresent(canType))
return type;
auto genericSig = getGenericSignature();
// Reduce it.
auto reducedType = genericSig->getReducedTypeParameter(canType);
// If this type parameter is equivalent to a concrete type,
// map the concrete type into context and cache the result.
if (!reducedType->isTypeParameter()) {
auto result = mapTypeIntoContext(reducedType);
addMapping(canType, result);
return result;
}
auto &ctx = genericSig->getASTContext();
// If the original type parameter was not reduced, see if we have an
// archetype for the reduced type parameter.
if (canType != reducedType) {
if (auto type = getMappingIfPresent(reducedType)) {
// Cache the result.
addMapping(canType, type);
return type;
}
}
// Otherwise, we're going to create a new archetype. Look up its
// requirements.
auto requirements = genericSig->getLocalRequirements(reducedType);
Type result;
auto sugaredType = genericSig->getSugaredType(reducedType);
auto rootGP = reducedType->getRootGenericParam();
switch (getKind()) {
case Kind::Primary:
if (rootGP->isParameterPack()) {
result = PackArchetypeType::get(ctx, this, sugaredType,
requirements.packShape,
requirements.protos,
requirements.superclass,
requirements.layout);
} else {
result = PrimaryArchetypeType::getNew(ctx, this, sugaredType,
requirements.protos,
requirements.superclass,
requirements.layout);
}
break;
case Kind::Opaque: {
// If the anchor type isn't rooted in a generic parameter that
// represents an opaque declaration, then apply the outer substitutions.
// It would be incorrect to build an opaque type archetype here.
if (rootGP->getDepth() < genericSig->getMaxDepth()) {
result = maybeApplyOuterContextSubstitutions(reducedType);
break;
}
result = OpaqueTypeArchetypeType::getNew(this, sugaredType,
requirements.protos,
requirements.superclass,
requirements.layout);
break;
}
case Kind::OpenedExistential: {
if (rootGP->getDepth() < genericSig->getMaxDepth()) {
result = maybeApplyOuterContextSubstitutions(reducedType);
break;
}
// FIXME: The existential layout's protocols might differ from the
// canonicalized set of protocols determined by the generic signature.
// Before NestedArchetypeType was removed, we used the former when
// building a root OpenedArchetypeType, and the latter when building
// nested archetypes.
// For compatibility, continue using the existential layout's version when
// the interface type is a generic parameter. We should align these at
// some point.
if (isa<GenericTypeParamType>(reducedType)) {
auto layout = getOpenedExistentialType()->getExistentialLayout();
SmallVector<ProtocolDecl *, 2> protos;
for (auto proto : layout.getProtocols())
protos.push_back(proto);
result = OpenedArchetypeType::getNew(this, sugaredType, protos,
requirements.superclass,
requirements.layout);
} else {
result = OpenedArchetypeType::getNew(this, sugaredType,
requirements.protos,
requirements.superclass,
requirements.layout);
}
break;
}
case Kind::OpenedElement: {
if (rootGP->getDepth() < genericSig->getMaxDepth()) {
result = maybeApplyOuterContextSubstitutions(reducedType);
break;
}
result = ElementArchetypeType::getNew(this, sugaredType,
requirements.protos,
requirements.superclass,
requirements.layout);
break;
}
}
// Cache the result.
addMapping(canType, result);
if (canType != reducedType)
addMapping(reducedType, result);
return result;
}
Type QueryInterfaceTypeSubstitutions::operator()(SubstitutableType *type) const{
auto gp = type->castTo<GenericTypeParamType>();
// Find the index into the parallel arrays of generic parameters and
// context types.
auto genericParams = self->getGenericParams();
GenericParamKey key(gp);
// Make sure that this generic parameter is from this environment and
// return substitution failure if not.
unsigned index = key.findIndexIn(genericParams);
if (index == genericParams.size())
return Type();
// If the context type isn't already known, lazily create it.
if (auto contextType = self->getContextTypes()[index])
return contextType;
return const_cast<GenericEnvironment *>(self)
->getOrCreateArchetypeFromInterfaceType(gp);
}
namespace {
struct MapTypeIntoContext: TypeTransform<MapTypeIntoContext> {
GenericEnvironment *env;
explicit MapTypeIntoContext(GenericEnvironment *env, ASTContext &ctx)
: TypeTransform(ctx), env(env) {}
std::optional<Type> transform(TypeBase *type, TypePosition pos) {
if (!type->hasTypeParameter())
return Type(type);
return std::nullopt;
}
Type transformGenericTypeParamType(GenericTypeParamType *param,
TypePosition pos) {
return env->getOrCreateArchetypeFromInterfaceType(param);
}
Type transformDependentMemberType(DependentMemberType *dependent,
TypePosition pos) {
return env->getOrCreateArchetypeFromInterfaceType(dependent);
}
CanType transformSILField(CanType fieldTy, TypePosition pos) {
return fieldTy;
}
};
}
Type GenericEnvironment::mapTypeIntoContext(Type type) const {
assert(!type->hasPrimaryArchetype() && "already have a contextual type");
if (!type->hasTypeParameter())
return type;
return MapTypeIntoContext(const_cast<GenericEnvironment *>(this),
type->getASTContext())
.doIt(type, TypePosition::Invariant);
}
Type GenericEnvironment::mapTypeIntoContext(GenericTypeParamType *type) const {
return const_cast<GenericEnvironment *>(this)
->getOrCreateArchetypeFromInterfaceType(type);
}
namespace {
struct FindElementArchetypeForOpenedPackParam {
ArrayRef<Type> openedPacks;
ArrayRef<GenericTypeParamType *> packElementParams;
const GenericEnvironment *env;
FindElementArchetypeForOpenedPackParam(const GenericEnvironment *env,
ArrayRef<Type> openedPacks)
: openedPacks(openedPacks),
packElementParams(env->getGenericSignature().getInnermostGenericParams()),
env(env) {}
Type getInterfaceType(Type interfaceType) const {
if (auto member = interfaceType->getAs<DependentMemberType>()) {
return DependentMemberType::get(getInterfaceType(member->getBase()),
member->getAssocType());
}
assert(interfaceType->is<GenericTypeParamType>());
for (auto i : indices(openedPacks)) {
if (openedPacks[i]->isEqual(interfaceType))
return packElementParams[i];
}
llvm_unreachable("parameter was not an opened pack parameter");
}
Type operator()(Type interfaceType) const {
return env->mapTypeIntoContext(getInterfaceType(interfaceType));
}
};
}
/// So this expects a type written with the archetypes of the original generic
/// environment, not 'this', the opened element environment, because it is the
/// original PackArchetypes that become ElementArchetypes. Also this function
/// does not apply outer substitutions, which might not be what you expect.
Type
GenericEnvironment::mapContextualPackTypeIntoElementContext(Type type) const {
assert(getKind() == Kind::OpenedElement);
assert(!type->hasTypeParameter() && "expected contextual type");
if (!type->hasPackArchetype()) return type;
auto sig = getGenericSignature();
auto shapeClass = getOpenedElementShapeClass();
FindElementArchetypeForOpenedPackParam
findElementArchetype(this, getOpenedPackParams());
return type.transformTypeParameterPacks(
[&](SubstitutableType *ty) -> std::optional<Type> {
if (auto *packArchetype = dyn_cast<PackArchetypeType>(ty)) {
auto interfaceType = packArchetype->getInterfaceType();
if (sig->haveSameShape(interfaceType, shapeClass))
return Type(findElementArchetype(interfaceType));
}
return std::nullopt;
});
}
CanType
GenericEnvironment::mapContextualPackTypeIntoElementContext(CanType type) const {
return CanType(mapContextualPackTypeIntoElementContext(Type(type)));
}
/// Unlike mapContextualPackTypeIntoElementContext(), this also applies outer
/// substitutions, so it behaves like mapTypeIntoContext() in that respect.
Type
GenericEnvironment::mapPackTypeIntoElementContext(Type type) const {
assert(getKind() == Kind::OpenedElement);
assert(!type->hasPackArchetype());
if (!type->hasParameterPack()) return type;
// Get a contextual type in the original generic environment, not the
// substituted one, which is what mapContextualPackTypeIntoElementContext()
// expects.
auto contextualType = getOuterSubstitutions()
.getGenericSignature().getGenericEnvironment()->mapTypeIntoContext(type);
contextualType = mapContextualPackTypeIntoElementContext(contextualType);
return maybeApplyOuterContextSubstitutions(contextualType);
}
Type
GenericEnvironment::mapElementTypeIntoPackContext(Type type) const {
assert(getKind() == Kind::Primary);
// We need to pass in an archetype to get the shape class from its
// generic environment.
assert(type->hasElementArchetype());
GenericEnvironment *elementEnv = nullptr;
// Map element archetypes to interface types in the element generic
// environment's signature.
type = type.subst(
[&](SubstitutableType *type) -> Type {
auto *archetype = cast<ArchetypeType>(type);
if (isa<OpenedArchetypeType>(archetype))
return archetype;
if (isa<ElementArchetypeType>(archetype)) {
assert(!elementEnv ||
elementEnv == archetype->getGenericEnvironment());
elementEnv = archetype->getGenericEnvironment();
}
return archetype->getInterfaceType();
},
MakeAbstractConformanceForGenericType(),
SubstFlags::PreservePackExpansionLevel |
SubstFlags::SubstitutePrimaryArchetypes |
SubstFlags::SubstituteLocalArchetypes);
auto shapeClass = elementEnv->getOpenedElementShapeClass();
llvm::SmallVector<GenericTypeParamType *, 2> members;
auto elementDepth = elementEnv->getGenericSignature()->getMaxDepth();
auto sig = getGenericSignature();
for (auto *genericParam : sig.getGenericParams()) {
if (!genericParam->isParameterPack())
continue;
if (!sig->haveSameShape(genericParam, shapeClass))
continue;
members.push_back(genericParam);
}
// Map element interface types to pack archetypes.
QueryInterfaceTypeSubstitutions mapIntoContext(this);
return type.subst(
[&](SubstitutableType *type) {
auto *genericParam = cast<GenericTypeParamType>(type);
if (genericParam->getDepth() == elementDepth) {
genericParam = members[genericParam->getIndex()];
assert(genericParam->isParameterPack());
}
return mapIntoContext(genericParam);
},
LookUpConformanceInModule(),
SubstFlags::PreservePackExpansionLevel);
}
namespace {
/// A function suitable for use as a \c TypeSubstitutionFn that produces
/// correct forwarding substitutions for a generic environment.
///
/// This differs from QueryInterfaceTypeSubstitutions only in that it
/// always produces PackTypes for pack parameters.
class BuildForwardingSubstitutions {
QueryInterfaceTypeSubstitutions Query;
public:
BuildForwardingSubstitutions(const GenericEnvironment *self)
: Query(self) { }
Type operator()(SubstitutableType *type) const;
};
} // end anonymous namespace
Type BuildForwardingSubstitutions::operator()(SubstitutableType *type) const {
if (auto resultType = Query(type)) {
auto param = cast<GenericTypeParamType>(type);
if (!param->isParameterPack())
return resultType;
if (resultType->is<PackType>())
return resultType;
return PackType::getSingletonPackExpansion(resultType);
}
return Type();
}
SubstitutionMap GenericEnvironment::getForwardingSubstitutionMap() const {
auto genericSig = getGenericSignature();
return SubstitutionMap::get(genericSig,
BuildForwardingSubstitutions(this),
MakeAbstractConformanceForGenericType());
}
std::pair<Type, ProtocolConformanceRef>
GenericEnvironment::mapConformanceRefIntoContext(GenericEnvironment *genericEnv,
Type conformingType,
ProtocolConformanceRef conformance) {
if (!genericEnv)
return {conformingType, conformance};
return genericEnv->mapConformanceRefIntoContext(conformingType, conformance);
}
std::pair<Type, ProtocolConformanceRef>
GenericEnvironment::mapConformanceRefIntoContext(
Type conformingInterfaceType,
ProtocolConformanceRef conformance) const {
auto contextConformance = conformance.subst(conformingInterfaceType,
QueryInterfaceTypeSubstitutions(this),
LookUpConformanceInModule());
auto contextType = mapTypeIntoContext(conformingInterfaceType);
return {contextType, contextConformance};
}
OpenedElementContext
OpenedElementContext::createForContextualExpansion(ASTContext &ctx,
CanPackExpansionType expansionType) {
assert(!expansionType->hasTypeParameter() &&
"must be given a contextual type");
// Get the outer generic signature and environment.
auto countArchetype = cast<ArchetypeType>(expansionType.getCountType());
auto *genericEnv = countArchetype->getGenericEnvironment();
auto subMap = genericEnv->getForwardingSubstitutionMap();
auto countType = cast<GenericTypeParamType>(
countArchetype->getInterfaceType()->getCanonicalType());
auto genericSig = genericEnv->getGenericSignature().getCanonicalSignature();
// Create an opened element signature and environment.
auto elementSig = ctx.getOpenedElementSignature(
genericSig, countType);
auto *elementEnv = GenericEnvironment::forOpenedElement(
elementSig, UUID::fromTime(), countType, subMap);
return {elementEnv, elementSig};
}