@@ -6688,13 +6688,24 @@ Expr *ExprRewriter::coerceExistential(Expr *expr, Type toType,
6688
6688
Type fromInstanceType = fromType;
6689
6689
Type toInstanceType = toType;
6690
6690
6691
- // Look through metatypes
6691
+ // For existential-to-existential coercions, open the source existential.
6692
+ Type openedFromType;
6693
+ if (fromType->isAnyExistentialType ()) {
6694
+ openedFromType = OpenedArchetypeType::getAny (fromType->getCanonicalType (),
6695
+ dc->getGenericSignatureOfContext ());
6696
+ }
6697
+
6698
+ Type openedFromInstanceType = openedFromType;
6699
+
6700
+ // Look through metatypes.
6692
6701
while ((fromInstanceType->is <UnresolvedType>() ||
6693
6702
fromInstanceType->is <AnyMetatypeType>()) &&
6694
6703
toInstanceType->is <ExistentialMetatypeType>()) {
6695
6704
if (!fromInstanceType->is <UnresolvedType>())
6696
- fromInstanceType = fromInstanceType->castTo <AnyMetatypeType>()->getInstanceType ();
6697
- toInstanceType = toInstanceType->castTo <ExistentialMetatypeType>()->getExistentialInstanceType ();
6705
+ fromInstanceType = fromInstanceType->getMetatypeInstanceType ();
6706
+ if (openedFromInstanceType && !openedFromInstanceType->is <UnresolvedType>())
6707
+ openedFromInstanceType = openedFromInstanceType->getMetatypeInstanceType ();
6708
+ toInstanceType = toInstanceType->getMetatypeInstanceType ();
6698
6709
}
6699
6710
6700
6711
ASTContext &ctx = cs.getASTContext ();
@@ -6758,20 +6769,13 @@ Expr *ExprRewriter::coerceExistential(Expr *expr, Type toType,
6758
6769
}
6759
6770
6760
6771
// For existential-to-existential coercions, open the source existential.
6761
- if (fromType->isAnyExistentialType ()) {
6762
- fromType = OpenedArchetypeType::getAny (fromType->getCanonicalType (),
6763
- dc->getGenericSignatureOfContext ());
6764
-
6772
+ if (openedFromType) {
6765
6773
auto *archetypeVal = cs.cacheType (
6766
- new (ctx) OpaqueValueExpr (expr->getSourceRange (), fromType));
6767
-
6768
- fromInstanceType = fromType;
6769
- while (auto *metatypeType = fromInstanceType->getAs <MetatypeType>())
6770
- fromInstanceType = metatypeType->getInstanceType ();
6774
+ new (ctx) OpaqueValueExpr (expr->getSourceRange (), openedFromType));
6771
6775
6772
6776
auto conformances =
6773
6777
dc->getParentModule ()
6774
- ->collectExistentialConformances (fromInstanceType ->getCanonicalType (),
6778
+ ->collectExistentialConformances (openedFromInstanceType ->getCanonicalType (),
6775
6779
toInstanceType->getCanonicalType (),
6776
6780
/* allowMissing=*/ true );
6777
6781
0 commit comments