@@ -5158,6 +5158,9 @@ class TypePrinter : public TypeVisitor<TypePrinter> {
51585158 } else if (auto existential = dyn_cast<ExistentialType>(T.getPointer ())) {
51595159 if (!Options.PrintExplicitAny )
51605160 return isSimpleUnderPrintOptions (existential->getConstraintType ());
5161+ } else if (auto existential = dyn_cast<ExistentialMetatypeType>(T.getPointer ())) {
5162+ if (!Options.PrintExplicitAny )
5163+ return isSimpleUnderPrintOptions (existential->getInstanceType ());
51615164 }
51625165 return T->hasSimpleTypeRepr ();
51635166 }
@@ -5578,10 +5581,32 @@ class TypePrinter : public TypeVisitor<TypePrinter> {
55785581 }
55795582 }
55805583
5581- if (T->is <ExistentialMetatypeType>() && Options.PrintExplicitAny )
5582- Printer << " any " ;
5584+ Type instanceType = T->getInstanceType ();
5585+ if (Options.PrintExplicitAny ) {
5586+ if (T->is <ExistentialMetatypeType>()) {
5587+ Printer << " any " ;
5588+
5589+ // FIXME: We need to replace nested existential metatypes so that
5590+ // we don't print duplicate 'any'. This will be unnecessary once
5591+ // ExistentialMetatypeType is split into ExistentialType(MetatypeType).
5592+ instanceType = Type (instanceType).transform ([](Type type) -> Type {
5593+ if (auto existential = type->getAs <ExistentialMetatypeType>())
5594+ return MetatypeType::get (existential->getInstanceType ());
5595+
5596+ return type;
5597+ });
5598+ } else if (instanceType->isAny () || instanceType->isAnyObject ()) {
5599+ // FIXME: 'any' is needed to distinguish between '(any Any).Type'
5600+ // and 'any Any.Type'. However, this combined with the above hack
5601+ // to replace nested existential metatypes with metatypes causes
5602+ // a bug in printing nested existential metatypes for Any and AnyObject,
5603+ // e.g. 'any (any Any).Type.Type'. This will be fixed by using
5604+ // ExistentialType for Any and AnyObject.
5605+ instanceType = ExistentialType::get (instanceType, /* forceExistential=*/ true );
5606+ }
5607+ }
55835608
5584- printWithParensIfNotSimple (T-> getInstanceType () );
5609+ printWithParensIfNotSimple (instanceType );
55855610
55865611 // We spell normal metatypes of existential types as .Protocol.
55875612 if (isa<MetatypeType>(T) &&
@@ -6281,7 +6306,11 @@ class TypePrinter : public TypeVisitor<TypePrinter> {
62816306 if (printNamedOpaque ())
62826307 return ;
62836308
6284- visit (T->getExistentialType ());
6309+ auto constraint = T->getExistentialType ();
6310+ if (auto existential = constraint->getAs <ExistentialType>())
6311+ constraint = existential->getConstraintType ();
6312+
6313+ visit (constraint);
62856314 return ;
62866315 }
62876316 case PrintOptions::OpaqueReturnTypePrintingMode::StableReference: {
0 commit comments