Skip to content

Commit 1b5f9f9

Browse files
committed
AST: add TypeBase::canBeExistential()
Checks if the type is an existential or an archetype which may be an existential.
1 parent 6f09b80 commit 1b5f9f9

File tree

2 files changed

+27
-0
lines changed

2 files changed

+27
-0
lines changed

include/swift/AST/Types.h

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -752,6 +752,10 @@ class alignas(1 << TypeAlignInBits) TypeBase
752752
return getRecursiveProperties().hasOpenedExistential();
753753
}
754754

755+
/// True if this type is an existential or an archetype which may be an
756+
/// existential.
757+
bool canBeExistential();
758+
755759
/// Determine whether the type involves an opened element archetype.
756760
bool hasElementArchetype() const {
757761
return getRecursiveProperties().hasElementArchetype();

lib/AST/Type.cpp

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -616,6 +616,29 @@ bool TypeBase::isTypeVariableOrMember() {
616616
return getDependentMemberRoot()->is<TypeVariableType>();
617617
}
618618

619+
bool TypeBase::canBeExistential() {
620+
if (isAnyExistentialType())
621+
return true;
622+
623+
Type ty(this);
624+
// Unwrap (potentially multiple levels of) metatypes.
625+
while (auto *mt = ty->getAs<MetatypeType>())
626+
ty = mt->getInstanceType();
627+
628+
if (auto *archeTy = ty->getAs<ArchetypeType>()) {
629+
// Only if all conformances are self-conforming protocols, the archetype
630+
// may be an existential.
631+
for (auto *proto : archeTy->getConformsTo()) {
632+
if (!proto->existentialConformsToSelf())
633+
return false;
634+
}
635+
// If there are no requirements on the archetype at all (`getConformsTo`
636+
// is empty), the archetype can still be `Any` and we have to return true.
637+
return true;
638+
}
639+
return false;
640+
}
641+
619642
bool TypeBase::isTypeParameter() {
620643
return getDependentMemberRoot()->is<GenericTypeParamType>();
621644
}

0 commit comments

Comments
 (0)