Skip to content

Allow existential parameterized compositions: any P<A> & Q #76705

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
105 changes: 64 additions & 41 deletions lib/AST/ASTDemangler.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -767,65 +767,88 @@ Type ASTBuilder::createExistentialMetatypeType(
Type ASTBuilder::createConstrainedExistentialType(
Type base, ArrayRef<BuiltRequirement> constraints,
ArrayRef<BuiltInverseRequirement> inverseRequirements) {
Type constrainedBase;

if (auto baseTy = base->getAs<ProtocolType>()) {
auto baseDecl = baseTy->getDecl();
llvm::SmallDenseMap<Identifier, Type> cmap;
for (const auto &req : constraints) {
switch (req.getKind()) {
case RequirementKind::SameShape:
llvm_unreachable("Same-shape requirement not supported here");
case RequirementKind::Conformance:
case RequirementKind::Superclass:
case RequirementKind::Layout:
continue;
llvm::SmallDenseMap<Identifier, Type> primaryAssociatedTypes;
llvm::SmallDenseSet<Identifier> claimed;

for (const auto &req : constraints) {
switch (req.getKind()) {
case RequirementKind::SameShape:
case RequirementKind::Conformance:
case RequirementKind::Superclass:
case RequirementKind::Layout:
break;

case RequirementKind::SameType:
if (auto *DMT = req.getFirstType()->getAs<DependentMemberType>())
cmap[DMT->getName()] = req.getSecondType();
case RequirementKind::SameType: {
if (auto *memberTy = req.getFirstType()->getAs<DependentMemberType>()) {
if (memberTy->getBase()->is<GenericTypeParamType>()) {
// This is the only case we understand so far.
primaryAssociatedTypes[memberTy->getName()] = req.getSecondType();
continue;
}
}
break;
}
}

// If we end here, we didn't recognize this requirement.
return Type();
}

auto maybeFormParameterizedProtocolType = [&](ProtocolType *protoTy) -> Type {
auto *proto = protoTy->getDecl();

llvm::SmallVector<Type, 4> args;
for (auto *assocTy : baseDecl->getPrimaryAssociatedTypes()) {
auto argTy = cmap.find(assocTy->getName());
if (argTy == cmap.end()) {
return Type();
}
args.push_back(argTy->getSecond());
for (auto *assocTy : proto->getPrimaryAssociatedTypes()) {
auto found = primaryAssociatedTypes.find(assocTy->getName());
if (found == primaryAssociatedTypes.end())
return protoTy;
args.push_back(found->second);
claimed.insert(found->first);
}

// We may not have any arguments because the constrained existential is a
// plain protocol with an inverse requirement.
if (args.empty()) {
constrainedBase =
ProtocolType::get(baseDecl, baseTy, base->getASTContext());
} else {
constrainedBase =
ParameterizedProtocolType::get(base->getASTContext(), baseTy, args);
}
} else if (base->isAny()) {
// The only other case should be that we got an empty PCT, which is equal to
// the Any type. The other constraints should have been encoded in the
// existential's generic signature (and arrive as BuiltInverseRequirement).
constrainedBase = base;
if (args.empty())
return protoTy;

return ParameterizedProtocolType::get(Ctx, protoTy, args);
};

SmallVector<Type, 2> members;
bool hasExplicitAnyObject = false;
InvertibleProtocolSet inverses;

// We're given either a single protocol type, or a composition of protocol
// types. Transform each protocol type to add arguments, if necessary.
if (auto protoTy = base->getAs<ProtocolType>()) {
members.push_back(maybeFormParameterizedProtocolType(protoTy));
} else {
return Type();
auto compositionTy = base->castTo<ProtocolCompositionType>();
hasExplicitAnyObject = compositionTy->hasExplicitAnyObject();
ASSERT(compositionTy->getInverses().empty());

for (auto member : compositionTy->getMembers()) {
if (auto *protoTy = member->getAs<ProtocolType>()) {
members.push_back(maybeFormParameterizedProtocolType(protoTy));
continue;
}
ASSERT(member->getClassOrBoundGenericClass());
members.push_back(member);
}
}

assert(constrainedBase);
// Make sure that all arguments were actually used.
ASSERT(claimed.size() == primaryAssociatedTypes.size());

// Handle inverse requirements.
if (!inverseRequirements.empty()) {
InvertibleProtocolSet inverseSet;
for (const auto &inverseReq : inverseRequirements) {
inverseSet.insert(inverseReq.getKind());
inverses.insert(inverseReq.getKind());
}
constrainedBase = ProtocolCompositionType::get(
Ctx, { constrainedBase }, inverseSet, /*hasExplicitAnyObject=*/false);
}

return ExistentialType::get(constrainedBase);
return ExistentialType::get(ProtocolCompositionType::get(
Ctx, members, inverses, hasExplicitAnyObject));
}

Type ASTBuilder::createSymbolicExtendedExistentialType(NodePointer shapeNode,
Expand Down
6 changes: 1 addition & 5 deletions lib/Sema/TypeCheckType.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -6002,11 +6002,7 @@ TypeResolver::resolveCompositionType(CompositionTypeRepr *repr,
continue;
}

// FIXME: Support compositions involving parameterized protocol types,
// like 'any Collection<String> & Sendable', etc.
if (ty->is<ParameterizedProtocolType>() &&
!options.isConstraintImplicitExistential() &&
options.getContext() != TypeResolverContext::ExistentialConstraint) {
if (ty->is<ParameterizedProtocolType>()) {
checkMember(tyR->getStartLoc(), ty);
Members.push_back(ty);
continue;
Expand Down
61 changes: 61 additions & 0 deletions test/Constraints/parameterized_existential_composition.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
// RUN: %target-typecheck-verify-swift -disable-availability-checking

func f1(_ s: any Sequence<Int> & Hashable) -> any Sequence<Int> {
return s
}

func f2(_ s: any Sequence<Int> & Hashable) -> any Hashable {
return s
}

func f3(_ s: any Sequence<Int> & Hashable) -> any Sequence {
return s
}

func f4(_ s: any Sequence<Int> & Hashable) -> any Sequence & Hashable {
return s
}

func f5(_ s: any Sequence<Int> & Hashable) -> any Sequence<Int> & Equatable {
return s
}

func f6(_ s: any Sequence<Int> & Hashable) -> any Sequence<String> & Hashable {
return s // expected-error {{cannot convert return expression of type 'Int' to return type 'String'}}
}

func f7(_ s: any Sequence<Int> & Hashable) -> any Sequence<String> {
return s // expected-error {{cannot convert return expression of type 'Int' to return type 'String'}}
}

func f8(_ s: any Collection<Int> & Hashable) -> any Sequence<Int> & Hashable {
return s
}

// https://github.com/swiftlang/swift/issues/71012

protocol A<T> {
associatedtype T
}
protocol B {}
typealias C = A & B
typealias D<T> = A<T> & B

struct Foo: C {
typealias T = Int
}

struct Bar<Value> { // expected-note {{arguments to generic parameter 'Value' ('any C' (aka 'any A & B') and 'any A<Int> & B') are expected to be equal}}
let value: Value
}

struct Baz<U> {
let bar: Bar<any D<U>>
}

func run() {
let foo: any C = Foo()
let bar = Bar(value: foo)
_ = Baz<Int>(bar: bar)
// expected-error@-1 {{cannot convert value of type 'Bar<any C>' (aka 'Bar<any A & B>') to expected argument type 'Bar<any A<Int> & B>'}}
}
36 changes: 36 additions & 0 deletions test/DebugInfo/parameterized_existential_composition.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
// RUN: %target-swift-frontend -emit-ir %s -g -target %target-swift-5.9-abi-triple

public protocol P<A, B> {
associatedtype A
associatedtype B
}

public protocol Q<C> {
associatedtype C
}

public protocol R {}

public class C<T: Equatable> {}

public func foo(_ a: any P<Int, Float> & R) {}
public func foo(_ a: any P<Int, Float> & Q<String>) {}
public func foo(_ a: any P<Int, Float> & Q<String> & R) {}
public func foo(_ a: any P<Int, Float> & Q<String> & R & C<Bool>) {}
public func foo(_ a: any P<Int, Float> & Q<String> & R & AnyObject) {}

public func foo(_ a: any (P<Int, Float> & R).Type) {}
public func foo(_ a: any (P<Int, Float> & Q<String>).Type) {}
public func foo(_ a: any (P<Int, Float> & Q<String> & R).Type) {}
public func foo(_ a: any (P<Int, Float> & Q<String> & R & C<Bool>).Type) {}
public func foo(_ a: any (P<Int, Float> & Q<String> & R & AnyObject).Type) {}

public func foo(_ a: (any P<Int, Float> & R).Type) {}
public func foo(_ a: (any P<Int, Float> & Q<String>).Type) {}
public func foo(_ a: (any P<Int, Float> & Q<String> & R).Type) {}
public func foo(_ a: (any P<Int, Float> & Q<String> & R & C<Bool>).Type) {}
public func foo(_ a: (any P<Int, Float> & Q<String> & R & AnyObject).Type) {}

public struct Foo<each T, U> {
public var a1: (repeat any P<each T, U> & R)
}
40 changes: 40 additions & 0 deletions test/SILGen/parameterized_existential_composition.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
// RUN: %target-swift-emit-silgen -disable-availability-checking %s | %FileCheck %s

protocol P<A> {
associatedtype A
}

protocol Q<B> {
associatedtype B
}

// All of these should have unique mangling.
func overload(_: any P<Int> & Q<String>) {}
func overload(_: any P<Float> & Q<String>) {}
func overload(_: any P & Q<String>) {}
func overload(_: any P<Int> & Q<Bool>) {}
func overload(_: any P<Float> & Q<Bool>) {}
func overload(_: any P & Q<Bool>) {}
func overload(_: any P<Int> & Q) {}
func overload(_: any P<Float> & Q) {}
func overload(_: any P & Q) {}
func overload(_: any P<Int>) {}
func overload(_: any P<Float>) {}
func overload(_: any P) {}
func overload(_: any Q<Bool>) {}
func overload(_: any Q) {}

// CHECK-LABEL: sil hidden [ossa] @$s37parameterized_existential_composition8overloadyyAA1P_AA1QpSi1AAaCPRts_SS1BAaDPRtsXPF : $@convention(thin) (@in_guaranteed any P<Int> & Q<String>) -> () {
// CHECK-LABEL: sil hidden [ossa] @$s37parameterized_existential_composition8overloadyyAA1P_AA1QpSf1AAaCPRts_SS1BAaDPRtsXPF : $@convention(thin) (@in_guaranteed any P<Float> & Q<String>) -> () {
// CHECK-LABEL: sil hidden [ossa] @$s37parameterized_existential_composition8overloadyyAA1P_AA1QpSS1BAaDPRts_XPF : $@convention(thin) (@in_guaranteed any P & Q<String>) -> () {
// CHECK-LABEL: sil hidden [ossa] @$s37parameterized_existential_composition8overloadyyAA1P_AA1QpSi1AAaCPRts_Sb1BAaDPRtsXPF : $@convention(thin) (@in_guaranteed any P<Int> & Q<Bool>) -> () {
// CHECK-LABEL: sil hidden [ossa] @$s37parameterized_existential_composition8overloadyyAA1P_AA1QpSf1AAaCPRts_Sb1BAaDPRtsXPF : $@convention(thin) (@in_guaranteed any P<Float> & Q<Bool>) -> () {
// CHECK-LABEL: sil hidden [ossa] @$s37parameterized_existential_composition8overloadyyAA1P_AA1QpSb1BAaDPRts_XPF : $@convention(thin) (@in_guaranteed any P & Q<Bool>) -> () {
// CHECK-LABEL: sil hidden [ossa] @$s37parameterized_existential_composition8overloadyyAA1P_AA1QpSi1AAaCPRts_XPF : $@convention(thin) (@in_guaranteed any P<Int> & Q) -> () {
// CHECK-LABEL: sil hidden [ossa] @$s37parameterized_existential_composition8overloadyyAA1P_AA1QpSf1AAaCPRts_XPF : $@convention(thin) (@in_guaranteed any P<Float> & Q) -> () {
// CHECK-LABEL: sil hidden [ossa] @$s37parameterized_existential_composition8overloadyyAA1P_AA1QpF : $@convention(thin) (@in_guaranteed any P & Q) -> () {
// CHECK-LABEL: sil hidden [ossa] @$s37parameterized_existential_composition8overloadyyAA1P_pSi1AAaCPRts_XPF : $@convention(thin) (@in_guaranteed any P<Int>) -> () {
// CHECK-LABEL: sil hidden [ossa] @$s37parameterized_existential_composition8overloadyyAA1P_pSf1AAaCPRts_XPF : $@convention(thin) (@in_guaranteed any P<Float>) -> () {
// CHECK-LABEL: sil hidden [ossa] @$s37parameterized_existential_composition8overloadyyAA1P_pF : $@convention(thin) (@in_guaranteed any P) -> () {
// CHECK-LABEL: sil hidden [ossa] @$s37parameterized_existential_composition8overloadyyAA1Q_pSb1BAaCPRts_XPF : $@convention(thin) (@in_guaranteed any Q<Bool>) -> () {
// CHECK-LABEL: sil hidden [ossa] @$s37parameterized_existential_composition8overloadyyAA1Q_pF : $@convention(thin) (@in_guaranteed any Q) -> () {
2 changes: 0 additions & 2 deletions test/decl/protocol/existential_member_access/basic.swift
Original file line number Diff line number Diff line change
Expand Up @@ -506,8 +506,6 @@ do {
func invariant11() -> Struct<${type}>.InnerGeneric<Void>
// https://github.com/apple/swift/issues/61934
func invariant12() -> any Sequence<${type}>
// FIXME
// expected-error@+1 {{non-protocol, non-class type 'Sequence<${type}>' cannot be used within a protocol-constrained type}}
func invariant13() -> any P & Sequence<${type}>
func invariant14() -> (any Sequence<${type}>).Type
func invariant15() -> any (P & Class<${type}>).Type
Expand Down
10 changes: 0 additions & 10 deletions test/type/parameterized_existential.swift
Original file line number Diff line number Diff line change
Expand Up @@ -82,16 +82,6 @@ func typeExpr() {
_ = (any Sequence<Int>).self
}

/// Not supported as a protocol composition term for now

protocol SomeProto {}

func protocolCompositionNotSupported1(_: SomeProto & Sequence<Int>) {}
// expected-error@-1 {{non-protocol, non-class type 'Sequence<Int>' cannot be used within a protocol-constrained type}}

func protocolCompositionNotSupported2(_: any SomeProto & Sequence<Int>) {}
// expected-error@-1 {{non-protocol, non-class type 'Sequence<Int>' cannot be used within a protocol-constrained type}}

func increment(_ n : any Collection<Float>) {
for value in n {
_ = value + 1
Expand Down