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
|
//===--- 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/Basic/Defer.h"
using namespace swift;
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();
}
OpaqueTypeDecl *GenericEnvironment::getOpaqueTypeDecl() const {
assert(getKind() == Kind::Opaque);
return getTrailingObjects<OpaqueEnvironmentData>()->decl;
}
SubstitutionMap GenericEnvironment::getOpaqueSubstitutions() const {
assert(getKind() == Kind::Opaque);
return getTrailingObjects<OpaqueEnvironmentData>()->subMap;
}
SubstitutionMap
GenericEnvironment::getPackElementContextSubstitutions() const {
assert(getKind() == Kind::OpenedElement);
auto environmentData = getTrailingObjects<OpenedElementEnvironmentData>();
return environmentData->outerSubstitutions;
}
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;
}
GenericSignature
GenericEnvironment::getOpenedExistentialParentSignature() const {
assert(getKind() == Kind::OpenedExistential);
return getTrailingObjects<OpenedExistentialEnvironmentData>()->parentSig;
}
UUID GenericEnvironment::getOpenedElementUUID() const {
assert(getKind() == Kind::OpenedElement);
return getTrailingObjects<OpenedElementEnvironmentData>()->uuid;
}
namespace {
struct FindOpenedElementParam {
ArrayRef<Type> openedPacks;
ArrayRef<GenericTypeParamType *> packElementParams;
FindOpenedElementParam(const GenericEnvironment *env,
ArrayRef<Type> openedPacks)
: openedPacks(openedPacks),
packElementParams(
env->getGenericSignature().getInnermostGenericParams()) {
assert(openedPacks.size() == packElementParams.size());
}
GenericTypeParamType *operator()(Type packParam) {
for (auto i : indices(openedPacks)) {
if (openedPacks[i]->isEqual(packParam))
return packElementParams[i];
}
llvm_unreachable("parameter was not an opened pack parameter");
}
};
struct FindElementArchetypeForOpenedPackParam {
FindOpenedElementParam findElementParam;
QueryInterfaceTypeSubstitutions getElementArchetype;
FindElementArchetypeForOpenedPackParam(const GenericEnvironment *env,
ArrayRef<Type> openedPacks)
: findElementParam(env, openedPacks), getElementArchetype(env) {}
ElementArchetypeType *operator()(Type interfaceType) {
assert(interfaceType->isTypeParameter());
if (auto member = interfaceType->getAs<DependentMemberType>()) {
auto baseArchetype = (*this)(member->getBase());
return baseArchetype->getNestedType(member->getAssocType())
->castTo<ElementArchetypeType>();
}
assert(interfaceType->is<GenericTypeParamType>());
return getElementArchetype(findElementParam(interfaceType))
->castTo<ElementArchetypeType>();
}
};
}
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, GenericSignature parentSig, UUID uuid)
: SignatureAndKind(signature, Kind::OpenedExistential)
{
new (getTrailingObjects<OpenedExistentialEnvironmentData>())
OpenedExistentialEnvironmentData{ existential, parentSig, 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)
{
new (getTrailingObjects<OpaqueEnvironmentData>())
OpaqueEnvironmentData{opaque, subs};
// 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)
{
new (getTrailingObjects<OpenedElementEnvironmentData>())
OpenedElementEnvironmentData{uuid, shapeClass, outerSubs};
// 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());
}
void GenericEnvironment::addMapping(GenericParamKey key,
Type contextType) {
// 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;
}
std::optional<Type>
GenericEnvironment::getMappingIfPresent(GenericParamKey key) const {
// 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");
if (auto type = getContextTypes()[index])
return type;
return std::nullopt;
}
namespace {
/// Substitute the outer generic parameters from a substitution map, ignoring
/// innter generic parameters with a given depth.
struct SubstituteOuterFromSubstitutionMap {
SubstitutionMap subs;
unsigned depth;
/// Whether this is a type parameter that should not be substituted.
bool isUnsubstitutedTypeParameter(Type type) const {
if (!type->isTypeParameter())
return false;
if (auto depMemTy = type->getAs<DependentMemberType>())
return isUnsubstitutedTypeParameter(depMemTy->getBase());
if (auto genericParam = type->getAs<GenericTypeParamType>())
return genericParam->getDepth() >= depth;
return false;
}
Type operator()(SubstitutableType *type) const {
if (isUnsubstitutedTypeParameter(type))
return Type(type);
return QuerySubstitutionMap{subs}(type);
}
ProtocolConformanceRef operator()(CanType dependentType,
Type conformingReplacementType,
ProtocolDecl *conformedProtocol) const {
if (isUnsubstitutedTypeParameter(dependentType))
return ProtocolConformanceRef(conformedProtocol);
return LookUpConformanceInSubstitutionMap(subs)(
dependentType, conformingReplacementType, conformedProtocol);
}
};
}
Type
GenericEnvironment::maybeApplyOuterContextSubstitutions(Type type) const {
switch (getKind()) {
case Kind::Primary:
case Kind::OpenedExistential:
return type;
case Kind::OpenedElement: {
auto packElements = getGenericSignature().getInnermostGenericParams();
auto elementDepth = packElements.front()->getDepth();
SubstituteOuterFromSubstitutionMap replacer{
getPackElementContextSubstitutions(), elementDepth};
return type.subst(replacer, replacer);
}
case Kind::Opaque: {
// Substitute outer generic parameters of an opaque archetype environment.
unsigned opaqueDepth =
getOpaqueTypeDecl()->getOpaqueGenericParams().front()->getDepth();
SubstituteOuterFromSubstitutionMap replacer{
getOpaqueSubstitutions(), opaqueDepth};
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::AllowLoweredTypes |
SubstFlags::PreservePackExpansionLevel);
}
class GenericEnvironment::NestedTypeStorage
: public llvm::DenseMap<CanType, Type> { };
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 genericSig = getGenericSignature();
LookUpConformanceInSignature conformanceLookupFn(genericSig.getPointer());
auto requirements = genericSig->getLocalRequirements(depType);
/// Substitute a type for the purpose of requirements.
auto substForRequirements = [&](Type type) {
switch (getKind()) {
case Kind::Primary:
case Kind::OpenedExistential:
if (type->hasTypeParameter()) {
return mapTypeIntoContext(type, conformanceLookupFn);
} else {
return type;
}
case Kind::OpenedElement:
case Kind::Opaque:
return maybeApplyOuterContextSubstitutions(type);
}
};
if (requirements.concreteType) {
return substForRequirements(requirements.concreteType);
}
assert(requirements.anchor && "No anchor or concrete type?");
auto &ctx = genericSig->getASTContext();
// First, write an ErrorType to the location where this type is cached,
// to catch re-entrant lookups that might arise from an invalid generic
// signature (eg, <X where X == Array<X>>).
CanDependentMemberType nestedType;
GenericTypeParamType *genericParam = nullptr;
if (auto depMemTy = requirements.anchor->getAs<DependentMemberType>()) {
nestedType = cast<DependentMemberType>(depMemTy->getCanonicalType());
auto &entry = getOrCreateNestedTypeStorage()[nestedType];
if (entry)
return entry;
entry = ErrorType::get(ctx);
} else {
genericParam = requirements.anchor->castTo<GenericTypeParamType>();
if (auto type = getMappingIfPresent(genericParam))
return *type;
addMapping(genericParam, ErrorType::get(ctx));
}
// Substitute into the superclass.
Type superclass = requirements.superclass;
if (superclass && superclass->hasTypeParameter()) {
superclass = substForRequirements(superclass);
if (superclass->is<ErrorType>())
superclass = Type();
}
Type result;
auto rootGP = requirements.anchor->getRootGenericParam();
switch (getKind()) {
case Kind::Primary:
if (rootGP->isParameterPack()) {
result = PackArchetypeType::get(ctx, this, requirements.anchor,
requirements.packShape,
requirements.protos, superclass,
requirements.layout);
} else {
result = PrimaryArchetypeType::getNew(ctx, this, requirements.anchor,
requirements.protos, superclass,
requirements.layout);
}
break;
case Kind::Opaque: {
assert(!rootGP->isParameterPack());
// 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.
unsigned opaqueDepth =
getOpaqueTypeDecl()->getOpaqueGenericParams().front()->getDepth();
if (rootGP->getDepth() < opaqueDepth) {
result = maybeApplyOuterContextSubstitutions(requirements.anchor);
break;
}
result = OpaqueTypeArchetypeType::getNew(this, requirements.anchor,
requirements.protos, superclass,
requirements.layout);
break;
}
case Kind::OpenedExistential: {
assert(!rootGP->isParameterPack());
// 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 (depType->is<GenericTypeParamType>()) {
auto layout = getOpenedExistentialType()->getExistentialLayout();
SmallVector<ProtocolDecl *, 2> protos;
for (auto proto : layout.getProtocols())
protos.push_back(proto);
result = OpenedArchetypeType::getNew(this, requirements.anchor, protos,
superclass, requirements.layout);
} else {
result = OpenedArchetypeType::getNew(this, requirements.anchor,
requirements.protos, superclass,
requirements.layout);
}
break;
}
case Kind::OpenedElement: {
auto packElements = getGenericSignature().getInnermostGenericParams();
auto elementDepth = packElements.front()->getDepth();
if (rootGP->getDepth() < elementDepth) {
result = maybeApplyOuterContextSubstitutions(requirements.anchor);
break;
}
result = ElementArchetypeType::getNew(this, requirements.anchor,
requirements.protos, superclass,
requirements.layout);
break;
}
}
if (genericParam)
addMapping(genericParam, result);
else
getOrCreateNestedTypeStorage()[nestedType] = result;
return result;
}
Type QueryInterfaceTypeSubstitutions::operator()(SubstitutableType *type) const{
if (auto gp = type->getAs<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.
unsigned index = key.findIndexIn(genericParams);
if (index == genericParams.size() || genericParams[index] != key)
return Type();
// If the context type isn't already known, lazily create it.
auto mutableSelf = const_cast<GenericEnvironment *>(self);
Type &contextType = mutableSelf->getContextTypes()[index];
if (contextType)
return contextType;
auto result = mutableSelf->getOrCreateArchetypeFromInterfaceType(type);
assert (!contextType ||
contextType->isEqual(result) ||
contextType->is<ErrorType>());
contextType = result;
return result;
}
return Type();
}
Type GenericEnvironment::mapTypeIntoContext(
Type type,
LookupConformanceFn lookupConformance) const {
assert(!type->hasPrimaryArchetype() && "already have a contextual type");
Type result = type.subst(QueryInterfaceTypeSubstitutions(this),
lookupConformance,
SubstFlags::AllowLoweredTypes |
SubstFlags::PreservePackExpansionLevel);
assert((!result->hasTypeParameter() || result->hasError() ||
getKind() == Kind::Opaque) &&
"not fully substituted");
return result;
}
Type GenericEnvironment::mapTypeIntoContext(Type type) const {
auto sig = getGenericSignature();
return mapTypeIntoContext(type, LookUpConformanceInSignature(sig.getPointer()));
}
Type GenericEnvironment::mapTypeIntoContext(GenericTypeParamType *type) const {
auto self = const_cast<GenericEnvironment *>(this);
Type result = QueryInterfaceTypeSubstitutions(self)(type);
if (!result)
return ErrorType::get(type);
return result;
}
/// 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 = getPackElementContextSubstitutions()
.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::AllowLoweredTypes |
SubstFlags::PreservePackExpansionLevel);
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 = type->getAs<GenericTypeParamType>();
if (!genericParam)
return Type();
if (genericParam->getDepth() == elementDepth) {
genericParam = members[genericParam->getIndex()];
assert(genericParam->isParameterPack());
}
return mapIntoContext(genericParam);
},
LookUpConformanceInSignature(sig.getPointer()),
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 = type->castTo<GenericTypeParamType>();
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),
LookUpConformanceInSignature(getGenericSignature().getPointer()));
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};
}
|