Skip to content

Conversation

hborla
Copy link
Member

@hborla hborla commented Oct 27, 2021

Protocol conformances for existential types are not supported today. If a programmers tries to fulfill an associated type with conformance requirements using an existential type, they'll get an unactionable error message:

protocol P1 {}
protocol P2 {
  associatedtype A: P1 // note: unable to infer associated type 'A' for protocol 'P2'
  var a: A { get }
}

struct S1: P1 {}
struct S2: P2 { // error: Type 'S2' does not conform to protocol 'P2'
  var a: P1 { S1() } // note: Candidate can not infer 'A' = 'P1' because 'P1' is not a nominal type and so can't conform to 'P1'
}

When the associated type was inferred from an existential result type, the compiler can suggest that the programmer use an opaque type instead by inserting some, which is usually a better solution for hiding a concrete return type behind a protocol:

note: cannot infer 'A' = 'P1' because 'P1' as a type cannot conform to protocols; did you mean to use an opaque result type?
  var a: P1 { S1() }
         ^~
         some 

…rence

failed because existential types can't conform to protocols.
@hborla hborla requested a review from slavapestov October 27, 2021 05:34
Copy link
Contributor

@slavapestov slavapestov left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is an excellent idea.

if (auto *var = dyn_cast<VarDecl>(failed.Witness)) {
resultType = var->getValueInterfaceType();
typeRange = var->getTypeSourceRangeForDiagnostics();
} else if (auto *func = dyn_cast<FuncDecl>(failed.Witness)) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nitpick: what about SubscriptDecl?

inference from the element type of a subscript value witness.
@hborla
Copy link
Member Author

hborla commented Oct 27, 2021

@swift-ci please smoke test

@hborla hborla merged commit a9c2055 into swiftlang:main Oct 27, 2021
@hborla hborla deleted the opaque-type-fixit branch October 27, 2021 21:01
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants