File: opened_existentials.swift

package info (click to toggle)
swiftlang 6.0.3-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,519,992 kB
  • sloc: cpp: 9,107,863; ansic: 2,040,022; asm: 1,135,751; python: 296,500; objc: 82,456; f90: 60,502; lisp: 34,951; pascal: 19,946; sh: 18,133; perl: 7,482; ml: 4,937; javascript: 4,117; makefile: 3,840; awk: 3,535; xml: 914; fortran: 619; cs: 573; ruby: 573
file content (418 lines) | stat: -rw-r--r-- 12,492 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
// RUN: %target-typecheck-verify-swift -disable-availability-checking

protocol Q { }

protocol P {
  associatedtype A: Q
}

protocol P1<A> {
  associatedtype A
}

extension Int: P {
  typealias A = Double
}

extension Array: P where Element: P {
  typealias A = String
}

extension Double: Q { }
extension String: Q { }

func acceptGeneric<T: P>(_: T) -> T.A? { nil }
func acceptCollection<C: Collection>(_ c: C) -> C.Element { c.first! }

// --- Simple opening of existential values
func testSimpleExistentialOpening(p: any P, pq: any P & Q, c: any Collection) {
  let pa = acceptGeneric(p)
  let _: Int = pa // expected-error{{cannot convert value of type '(any Q)?' to specified type 'Int'}}

  var vp = p
  let vpa = acceptGeneric(vp)
  let _: Int = vpa // expected-error{{cannot convert value of type '(any Q)?' to specified type 'Int'}}

  let pqa = acceptGeneric(pq)
  let _: Int = pqa  // expected-error{{cannot convert value of type '(any Q)?' to specified type 'Int'}}

  let element = acceptCollection(c) 
  let _: Int = element // expected-error{{cannot convert value of type 'Any' to specified type 'Int'}}
}

// --- Requirements on nested types
protocol CollectionOfPs: Collection where Self.Element: P { }

func takeCollectionOfPs<C: Collection>(_: C) -> C.Element.A?    
  where C.Element: P
{
  nil
}

func testCollectionOfPs(cp: any CollectionOfPs) {
  let e = takeCollectionOfPs(cp)
  let _: Int = e // expected-error{{cannot convert value of type '(any Q)?' to specified type 'Int'}}
}

// --- Multiple opened existentials in the same expression
func takeTwoGenerics<T1: P, T2: P>(_ a: T1, _ b: T2) -> (T1, T2) { (a, b) }

extension P {
  func combineThePs<T: P & Q>(_ other: T) -> (A, T.A)? { nil }
}

func testMultipleOpened(a: any P, b: any P & Q) {
  let r1 = takeTwoGenerics(a, b)
  let _: Int = r1  // expected-error{{cannot convert value of type '(any P, any P & Q)' to specified type 'Int'}}

  let r2 = a.combineThePs(b)
  let _: Int = r2  // expected-error{{cannot convert value of type '(any Q, any Q)?' to specified type 'Int'}}
}

// --- Opening existential metatypes
func conjureValue<T: P>(of type: T.Type) -> T? {
  nil
}

func testMagic(pt: any P.Type) {
  let pOpt = conjureValue(of: pt)
  let _: Int = pOpt // expected-error{{cannot convert value of type '(any P)?' to specified type 'Int'}}
}

// --- With primary associated types and opaque parameter types
protocol CollectionOf<Element>: Collection { }

extension Array: CollectionOf { }
extension Set: CollectionOf { }

// expected-note@+2{{required by global function 'reverseIt' where 'some CollectionOf<T>' = 'any CollectionOf'}}
@available(SwiftStdlib 5.1, *)
func reverseIt<T>(_ c: some CollectionOf<T>) -> some CollectionOf<T> {
  return c.reversed()
}

@available(SwiftStdlib 5.1, *)
func useReverseIt(_ c: any CollectionOf) {
  // Can't type-erase the `T` from the result.
  _ = reverseIt(c) // expected-error{{type 'any CollectionOf' cannot conform to 'CollectionOf'}}
  // expected-note@-1{{only concrete types such as structs, enums and classes can conform to protocols}}
}

/// --- Opening existentials when returning opaque types.
@available(SwiftStdlib 5.1, *)
extension P {
  func getQ() -> some Q {
    let a: A? = nil
    return a!
  }

  func getCollectionOf() -> some CollectionOf<A> {
    return [] as [A]
  }
}

@available(SwiftStdlib 5.1, *)
func getPQ<T: P>(_: T) -> some Q {
  let a: T.A? = nil
  return a!
}

// expected-note@+2{{required by global function 'getCollectionOfP' where 'T' = 'any P'}}
@available(SwiftStdlib 5.1, *)
func getCollectionOfP<T: P>(_: T) -> some CollectionOf<T.A> {
  return [] as [T.A]
}

func funnyIdentity<T: P>(_ value: T) -> T? {
  value
}

func arrayOfOne<T: P>(_ value: T) -> [T] {
  [value]
}

struct X<T: P> {
  // expected-note@-1{{required by generic struct 'X' where 'T' = 'any P'}}
  func f(_: T) { }
}

// expected-note@+1{{required by global function 'createX' where 'T' = 'any P'}}
func createX<T: P>(_ value: T) -> X<T> {
  X<T>()
}

func doNotOpenOuter(p: any P) {
  _ = X().f(p) // expected-error{{type 'any P' cannot conform to 'P'}}
  // expected-note@-1{{only concrete types such as structs, enums and classes can conform to protocols}}
}

func takesVariadic<T: P>(_ args: T...) { }
// expected-note@-1 2{{required by global function 'takesVariadic' where 'T' = 'any P'}}
// expected-note@-2{{in call to function 'takesVariadic'}}

func callVariadic(p1: any P, p2: any P) {
  takesVariadic() // expected-error{{generic parameter 'T' could not be inferred}}
  takesVariadic(p1) // expected-error{{type 'any P' cannot conform to 'P'}}
  // expected-note@-1{{only concrete types such as structs, enums and classes can conform to protocols}}
  takesVariadic(p1, p2) // expected-error{{type 'any P' cannot conform to 'P'}}
  // expected-note@-1{{only concrete types such as structs, enums and classes can conform to protocols}}
}

func takesInOut<T: P>(_ value: inout T) { }

func passesInOut(i: Int) {
  var p: any P = i
  takesInOut(&p)
}

func takesOptional<T: P>(_ value: T?) { }
// expected-note@-1{{required by global function 'takesOptional' where 'T' = 'any P'}}

func passesToOptional(p: any P, pOpt: (any P)?) {
  takesOptional(p) // okay
  takesOptional(pOpt) // expected-error{{type 'any P' cannot conform to 'P'}}
  // expected-note@-1{{only concrete types such as structs, enums and classes can conform to protocols}}
}


@available(SwiftStdlib 5.1, *)
func testReturningOpaqueTypes(p: any P) {
  let q = p.getQ()
  let _: Int = q  // expected-error{{cannot convert value of type 'any Q' to specified type 'Int'}}

  p.getCollectionOf() // expected-error{{member 'getCollectionOf' cannot be used on value of type 'any P'; consider using a generic constraint instead}}

  let q2 = getPQ(p)
  let _: Int = q2  // expected-error{{cannot convert value of type 'any Q' to specified type 'Int'}}

  getCollectionOfP(p) // expected-error{{type 'any P' cannot conform to 'P'}}
  // expected-note@-1{{only concrete types such as structs, enums and classes can conform to protocols}}

  let fi = funnyIdentity(p)
  let _: Int = fi // expected-error{{cannot convert value of type '(any P)?' to specified type 'Int'}}

  _ = arrayOfOne(p) // okay, arrays are covariant in their argument

  _ = createX(p) // expected-error{{type 'any P' cannot conform to 'P'}}
  // expected-note@-1{{only concrete types such as structs, enums and classes can conform to protocols}}
}

// Type-erasing vs. opening for parameters after the opened one.
func takeValueAndClosure<T: P>(_ value: T, body: (T) -> Void) { }
func takeValueAndClosureBackwards<T: P>(body: (T) -> Void, _ value: T) { }
// expected-note@-1{{required by global function 'takeValueAndClosureBackwards(body:_:)' where 'T' = 'any P'}}

func genericFunctionTakingP<T: P>(_: T) { }
func genericFunctionTakingPQ<T: P & Q>(_: T) { }

func overloadedGenericFunctionTakingP<T: P>(_: T) -> Int { 0 }
func overloadedGenericFunctionTakingP<T: P>(_: T) { }

func testTakeValueAndClosure(p: any P) {
  // Type-erase when not provided with a generic function.
  takeValueAndClosure(p) { x in
    print(x)
    let _: Int = x // expected-error{{cannot convert value of type 'any P' to specified type 'Int'}}
  }

  // Do not erase when referring to a generic function.
  takeValueAndClosure(p, body: genericFunctionTakingP)
  takeValueAndClosure(p, body: overloadedGenericFunctionTakingP)
  takeValueAndClosure(p, body: genericFunctionTakingPQ) // expected-error{{global function 'genericFunctionTakingPQ' requires that 'T' conform to 'Q'}}

  // Do not allow opening if there are any uses of the type parameter before
  // the opened parameter. This maintains left-to-right evaluation order.
  takeValueAndClosureBackwards( // expected-error{{type 'any P' cannot conform to 'P'}}
    // expected-note@-1{{only concrete types such as structs, enums and classes can conform to protocols}}
    body: { x in x as Int }, // expected-error{{'any P' is not convertible to 'Int'}}
    // expected-note@-1{{did you mean to use 'as!' to force downcast?}}
    p)
}

protocol B {
  associatedtype C: P where C.A == Double
  associatedtype D: P
  associatedtype E: P1 where E.A == Double
}

protocol D {
  associatedtype E
}

extension B {
  var testVar: (Int, [C]) { get { fatalError() } }

  func getC() -> C { fatalError() }
}

func testExplicitCoercionRequirement(v: any B, otherV: any B & D) {
  func getC<T: B>(_: T) -> T.C { fatalError() }
  func getE<T: B>(_: T) -> T.E { fatalError() }
  func getTuple<T: B>(_: T) -> (T, T.C) { fatalError() }
  func getNoError<T: B>(_: T) -> T.C.A { fatalError() }
  func getComplex<T: B>(_: T) -> ([(x: (a: T.C, b: Int), y: Int)], [Int: T.C]) { fatalError() }

  func overloaded<T: B>(_: T) -> (x: Int, y: T.C) { fatalError() }
  func overloaded<T: P>(_: T) -> Int { 42 }

  _ = getC(v) // Ok
  _ = getC(v) as any P // Ok
  
  _ = getE(v) // Ok
  _ = getE(v) as any P1<Double> // Ok
  
  _ = getTuple(v) // Ok
  _ = getTuple(v) as (any B, any P) // Ok
  // Ok because T.C.A == Double
  _ = getNoError(v)

  _ = getComplex(v) // Ok
  _ = getComplex(v) as ([(x: (a: any P, b: Int), y: Int)], [Int : any P]) // Ok

  _ = overloaded(v) // Ok

  func acceptsAny<T>(_: T) {}

  acceptsAny(getC(v)) // Ok
  acceptsAny(getC(v) as any P) // Ok

  acceptsAny(getComplex(v)) // Ok
  acceptsAny(getComplex(v) as ([(x: (a: any P, b: Int), y: Int)], [Int : any P]))

  func getAssocNoRequirements<T: B>(_: T) -> (Int, [T.D]) { fatalError() }

  _ = getAssocNoRequirements(v) // Ok, `D` doesn't have any requirements

  // Test existential opening from protocol extension access
  _ = v.getC() // Ok
  _ = v.getC() as any P // Ok

  _ = v.testVar // Ok
  _ = v.testVar as (Int, [any P])

  func getF<T: D>(_: T) -> T.E { fatalError() }

  _ = getF(otherV) // Ok `E` doesn't have a `where` clause

  func getSelf<T: B>(_: T) -> T { fatalError() } // expected-note {{found this candidate}}
  func getSelf<T: D>(_: T) -> T { fatalError() } // expected-note {{found this candidate}}

  _ = getSelf(v) // Ok
  _ = getSelf(v) as any B // Ok
  _ = getSelf(otherV) as any B & D // expected-error {{ambiguous use of 'getSelf'}}

  func getBDSelf<T: D>(_: T) -> T { fatalError() }
  _ = getBDSelf(otherV) // Ok
  _ = getBDSelf(otherV) as any B & D // Ok

  func getP<T: P>(_: T) {}
  getP(getC(v)) // Ok
  getP(v.getC()) // Ok

  getP((getC(v) as any P))   // Ok - parens avoid opening suppression
  getP((v.getC() as any P))  // Ok - parens avoid opening suppression
}

class C1 {}
class C2<T>: C1 {}

// Test Associated Types
protocol P2 {
  associatedtype A
  associatedtype B: C2<A>

  func returnAssocTypeB() -> B
}

func testAssocReturn(p: any P2) {
  let _ = p.returnAssocTypeB()  // returns C1
}

protocol Q2 : P2 where A == Int {}

do {
  let q: any Q2
  let _ = q.returnAssocTypeB() // returns C1
}

// Test Primary Associated Types
protocol P3<A> {
  associatedtype A
  associatedtype B: C2<A>

  func returnAssocTypeB() -> B
}

func testAssocReturn(p: any P3<Int>) {
  let _ = p.returnAssocTypeB() // returns C2<A>
}

func testAssocReturn(p: any P3<any P3<String>>) {
  let _ = p.returnAssocTypeB()
}

protocol P4<A> {
  associatedtype A
  associatedtype B: C2<A>

  func returnPrimaryAssocTypeA() -> A
  func returnAssocTypeCollection() -> any Collection<A>
}

 //Confirm there is no way to access Primary Associated Type directly
func testPrimaryAssocReturn(p: any P4<Int>) {
  let _ = p.returnPrimaryAssocTypeA()
}

func testPrimaryAssocCollection(p: any P4<Float>) {
  let _: any Collection<Float> = p.returnAssocTypeCollection()
}

protocol P5<X> {
  associatedtype X = Void
}

struct K<T>: P5 {
  typealias X = T
}

extension P5 {
  @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
  func foo() -> some P5<X>{
    K<X>()
  }
  func bar(_ handler: @escaping (X) -> Void) -> some P5<X> {
    K<X>()
  }
}

@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
func testFoo(_ p: any P5<String>) -> any P5 {
  p.foo()
}

func testFooGeneric<U>(_ p: any P5<Result<U, Error>>) -> any P5 {
  p.foo()
}

@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
func testBar<U>(_ p: any P5<Result<U, Error>>) -> any P5 {
  p.bar { _ in }
}

enum Node<T> {
  case e(any P5)
  case f(any P5<Result<T, Error>>)
}

struct S<T, U> {
  @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
  func foo(_ elt: Node<U>) -> Node<T>? {
    switch elt {
    case let .e(p):
      return .e(p)
    case let .f(p):
      return .e(p.bar { _ in })
    }
  }
}