File: protocols.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 (579 lines) | stat: -rw-r--r-- 16,749 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
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
// RUN: %target-typecheck-verify-swift

protocol Fooable { func foo() }
protocol Barable { func bar() }

extension Int : Fooable, Barable {
  func foo() {}
  func bar() {}
}

extension Float32 : Barable {
  func bar() {}
}

func f0(_: Barable) {}
func f1(_ x: Fooable & Barable) {}
func f2(_: Float) {}
let nilFunc: Optional<(Barable) -> ()> = nil

func g(_: (Barable & Fooable) -> ()) {}

protocol Classable : AnyObject {}
class SomeArbitraryClass {}

func fc0(_: Classable) {}
func fc1(_: Fooable & Classable) {}
func fc2(_: AnyObject) {}
func fc3(_: SomeArbitraryClass) {}
func gc(_: (Classable & Fooable) -> ()) {}

var i : Int
var f : Float
var b : Barable

//===----------------------------------------------------------------------===//
// Conversion to and among existential types
//===----------------------------------------------------------------------===//

f0(i)
f0(f)
f0(b)
f1(i)

f1(f) // expected-error{{argument type 'Float' does not conform to expected type 'Fooable'}}
f1(b) // expected-error{{argument type 'any Barable' does not conform to expected type 'Fooable'}}

//===----------------------------------------------------------------------===//
// Subtyping
//===----------------------------------------------------------------------===//
g(f0) // okay (subtype)
g(f1) // okay (exact match)

g(f2) // expected-error{{cannot convert value of type '(Float) -> ()' to expected argument type '(any Barable & Fooable) -> ()'}}
g(nilFunc ?? f0)

gc(fc0) // okay
gc(fc1) // okay
gc(fc2) // okay
gc(fc3) // expected-error{{cannot convert value of type '(SomeArbitraryClass) -> ()' to expected argument type '(any Classable & Fooable) -> ()'}}

// rdar://problem/19600325
func getAnyObject() -> AnyObject? {
  return SomeArbitraryClass()
}

func castToClass(_ object: Any) -> SomeArbitraryClass? {
  return object as? SomeArbitraryClass
}

_ = getAnyObject().map(castToClass)


_ = { (_: Any) -> Void in
  return
} as ((Int) -> Void)

let _: (Int) -> Void = {
  (_: Any) -> Void in
  return
}

let _: () -> Any = {
  () -> Int in
  return 0
}

let _: () -> Int = { 
  () -> String in  // expected-error {{declared closure result 'String' is incompatible with contextual type 'Int'}}
  return ""
}

//===----------------------------------------------------------------------===//
// Members of archetypes
//===----------------------------------------------------------------------===//

func id<T>(_ t: T) -> T { return t }

protocol Initable {
  init()
}

protocol P : Initable {
  func bar(_ x: Int)
  mutating func mut(_ x: Int)
  static func tum()
  
  typealias E = Int
  typealias F = Self.E
  typealias G = Array
}

protocol ClassP : class {
  func bas(_ x: Int)
  func quux(_ x: Int)
}

class ClassC : ClassP {
  func bas(_ x: Int) {}
}

extension ClassP {
  func quux(_ x: Int) {}
  func bing(_ x: Int) {}
}

func generic<T: P>(_ t: T) {
  var t = t
  // Instance member of archetype
  let _: (Int) -> () = id(t.bar)
  let _: () = id(t.bar(0))

  // Static member of archetype metatype
  let _: () -> () = id(T.tum)

  // Instance member of archetype metatype
  let _: (T) -> (Int) -> () = id(T.bar)
  let _: (Int) -> () = id(T.bar(t))

  _ = t.mut // expected-error{{cannot reference 'mutating' method as function value}}
  _ = t.tum // expected-error{{static member 'tum' cannot be used on instance of type 'T'}}
}

func genericClassP<T: ClassP>(_ t: T) {
  // Instance member of archetype)
  let _: (Int) -> () = id(t.bas)
  let _: () = id(t.bas(0))

  // Instance member of archetype metatype)
  let _: (T) -> (Int) -> () = id(T.bas)
  let _: (Int) -> () = id(T.bas(t))
  let _: () = id(T.bas(t)(1))
}

func genericClassC<C : ClassC>(_ c: C) {
  // Make sure that we can find members of protocol extensions
  // on a class-bound archetype
  let _ = c.bas(123)
  let _ = c.quux(123)
  let _ = c.bing(123)
}

//===----------------------------------------------------------------------===//
// Members of existentials
//===----------------------------------------------------------------------===//

func existential(_ p: P) {
  var p = p
  // Fully applied mutating method
  p.mut(1)
  _ = p.mut // expected-error{{cannot reference 'mutating' method as function value}}

  // Instance member of existential)
  let _: (Int) -> () = id(p.bar)
  let _: () = id(p.bar(0))

  // Static member of existential metatype)
  let _: () -> () = id(type(of: p).tum)
}

func staticExistential(_ p: P.Type, pp: P.Protocol) {
  let _ = p() // expected-error{{initializing from a metatype value must reference 'init' explicitly}}
  let _ = p().bar // expected-error{{initializing from a metatype value must reference 'init' explicitly}}
  let _ = p().bar(1) // expected-error{{initializing from a metatype value must reference 'init' explicitly}}

  let ppp: P = p.init()

  _ = pp() // expected-error{{value of type '(any P).Type' is a protocol; it cannot be instantiated}}
  _ = pp().bar // expected-error{{value of type '(any P).Type' is a protocol; it cannot be instantiated}}
  _ = pp().bar(2) // expected-error{{value of type '(any P).Type' is a protocol; it cannot be instantiated}}

  _ = pp.init() // expected-error{{type 'any P' cannot be instantiated}}
  _ = pp.init().bar // expected-error{{type 'any P' cannot be instantiated}}
  _ = pp.init().bar(3) // expected-error{{type 'any P' cannot be instantiated}}

  _ = P() // expected-error{{type 'any P' cannot be instantiated}}
  _ = P().bar // expected-error{{type 'any P' cannot be instantiated}}
  _ = P().bar(4) // expected-error{{type 'any P' cannot be instantiated}}

  // Instance member of metatype
  let _: (P) -> (Int) -> () = P.bar
  let _: (Int) -> () = P.bar(ppp)
  P.bar(ppp)(5)

  // Instance member of metatype value
  let _: (P) -> (Int) -> () = pp.bar
  let _: (Int) -> () = pp.bar(ppp)
  pp.bar(ppp)(5)

  // Static member of existential metatype value
  let _: () -> () = p.tum

  // Instance member of existential metatype -- not allowed
  _ = p.bar // expected-error{{instance member 'bar' cannot be used on type 'P'}}
  _ = p.mut // expected-error{{instance member 'mut' cannot be used on type 'P'}}
  // expected-error@-1 {{cannot reference 'mutating' method as function value}}

  // Static member of metatype -- not allowed
  _ = pp.tum // expected-error{{static member 'tum' cannot be used on protocol metatype '(any P).Type'}}
  _ = P.tum // expected-error{{static member 'tum' cannot be used on protocol metatype '(any P).Type'}}

  // Access typealias through protocol and existential metatypes
  _ = pp.E.self
  _ = p.E.self

  _ = pp.F.self
  _ = p.F.self

  // Make sure that we open generics
  let _: [Int].Type = p.G.self
}

protocol StaticP {
  static func foo(a: Int)
}
extension StaticP {
  func bar() {
    _ = StaticP.foo(a:) // expected-error{{static member 'foo(a:)' cannot be used on protocol metatype '(any StaticP).Type'}} {{9-16=Self}}

    func nested() {
      _ = StaticP.foo(a:) // expected-error{{static member 'foo(a:)' cannot be used on protocol metatype '(any StaticP).Type'}} {{11-18=Self}}
    }
  }
}

func existentialClassP(_ p: ClassP) {
  // Instance member of existential)
  let _: (Int) -> () = id(p.bas)
  let _: () = id(p.bas(0))

  // Instance member of existential metatype)
  let _: (ClassP) -> (Int) -> () = id(ClassP.bas)
  let _: (Int) -> () = id(ClassP.bas(p))
  let _: () = id(ClassP.bas(p)(1))
}

// Partial application of curried protocol methods
protocol Scalar {}
protocol Vector {
  func scale(_ c: Scalar) -> Self
}
protocol Functional {
  func apply(_ v: Vector) -> Scalar
}
protocol Coalgebra {
  func coproduct(_ f: Functional) -> (_ v1: Vector, _ v2: Vector) -> Scalar
}

// Make sure existential is closed early when we partially apply
func wrap<T>(_ t: T) -> T {
  return t
}

func exercise(_ c: Coalgebra, f: Functional, v: Vector) {
  let _: (Vector, Vector) -> Scalar = wrap(c.coproduct(f))
  let _: (Scalar) -> Vector = v.scale
}

// Make sure existential isn't closed too late
protocol Copyable {
  func copy() -> Self
}

func copyTwice(_ c: Copyable) -> Copyable {
  return c.copy().copy()
}

//===----------------------------------------------------------------------===//
// Dynamic self
//===----------------------------------------------------------------------===//
protocol Clonable {
  func maybeClone() -> Self?
  func doubleMaybeClone() -> Self??
  func subdivideClone() -> (Self, Self)
  func metatypeOfClone() -> Self.Type
  func goodClonerFn() -> (() -> Self)
}

extension Clonable {
  func badClonerFn() -> ((Self) -> Self) { }

  func veryBadClonerFn() -> ((inout Self) -> ()) { }

  func extClone() -> Self { }

  func extMaybeClone(_ b: Bool) -> Self? { }

  func extProbablyClone(_ b: Bool) -> Self! { }

  static func returnSelfStatic() -> Self { }

  static func returnSelfOptionalStatic(_ b: Bool) -> Self? { }

  static func returnSelfIUOStatic(_ b: Bool) -> Self! { }
}

func testClonableArchetype<T : Clonable>(_ t: T) {
  // Instance member of extension returning Self)
  let _: (T) -> () -> T = id(T.extClone)
  let _: () -> T = id(T.extClone(t))
  let _: T = id(T.extClone(t)())

  let _: () -> T = id(t.extClone)
  let _: T = id(t.extClone())

  let _: (T) -> (Bool) -> T? = id(T.extMaybeClone)
  let _: (Bool) -> T? = id(T.extMaybeClone(t))
  let _: T? = id(T.extMaybeClone(t)(false))

  let _: (Bool) -> T? = id(t.extMaybeClone)
  let _: T? = id(t.extMaybeClone(true))

  let _: (T) -> (Bool) -> T? = id(T.extProbablyClone as (T) -> (Bool) -> T?)
  let _: (Bool) -> T? = id(T.extProbablyClone(t) as (Bool) -> T?)
  let _: T! = id(T.extProbablyClone(t)(true))

  let _: (Bool) -> T? = id(t.extProbablyClone as (Bool) -> T?)
  let _: T! = id(t.extProbablyClone(true))

  // Static member of extension returning Self)
  let _: () -> T = id(T.returnSelfStatic)
  let _: T = id(T.returnSelfStatic())

  let _: (Bool) -> T? = id(T.returnSelfOptionalStatic)
  let _: T? = id(T.returnSelfOptionalStatic(false))

  let _: (Bool) -> T? = id(T.returnSelfIUOStatic as (Bool) -> T?)
  let _: T! = id(T.returnSelfIUOStatic(true))
}

func testClonableExistential(_ v: Clonable, _ vv: Clonable.Type) {
  let _: Clonable? = v.maybeClone()
  let _: Clonable?? = v.doubleMaybeClone()
  let _: (Clonable, Clonable) = v.subdivideClone()
  let _: Clonable.Type = v.metatypeOfClone()
  let _: () -> Clonable = v.goodClonerFn()

  // Instance member of extension returning Self
  let _: () -> Clonable = id(v.extClone)
  let _: Clonable = id(v.extClone())
  let _: Clonable? = id(v.extMaybeClone(true))
  let _: Clonable! = id(v.extProbablyClone(true))

  // Static member of extension returning Self)
  let _: () -> Clonable = id(vv.returnSelfStatic)
  let _: Clonable = id(vv.returnSelfStatic())

  let _: (Bool) -> Clonable? = id(vv.returnSelfOptionalStatic)
  let _: Clonable? = id(vv.returnSelfOptionalStatic(false))

  let _: (Bool) -> Clonable? = id(vv.returnSelfIUOStatic as (Bool) -> Clonable?)
  let _: Clonable! = id(vv.returnSelfIUOStatic(true))

  let _ = v.badClonerFn() // expected-error {{member 'badClonerFn' cannot be used on value of type 'any Clonable'; consider using a generic constraint instead}}
  let _ = v.veryBadClonerFn() // expected-error {{member 'veryBadClonerFn' cannot be used on value of type 'any Clonable'; consider using a generic constraint instead}}

}


// rdar://problem/50099849

protocol Trivial {
  associatedtype T
}

func rdar_50099849() {
  struct A : Trivial {
    typealias T = A
  }

  struct B<C : Trivial> : Trivial { // expected-note {{'C' declared as parameter to type 'B'}}
    typealias T = C.T
  }

  struct C<W: Trivial, Z: Trivial> : Trivial where W.T == Z.T {
    typealias T = W.T
  }

  let _ = C<A, B>() // expected-error {{generic parameter 'C' could not be inferred}}
  // expected-note@-1 {{explicitly specify the generic arguments to fix this issue}} {{17-17=<<#C: Trivial#>>}}
}

// rdar://problem/50512161 - improve diagnostic when generic parameter cannot be deduced
func rdar_50512161() {
  struct Item {}

  struct TrivialItem : Trivial {
    typealias T = Item?
  }

  func foo<I>(_: I.Type = I.self, item: I.T) where I : Trivial { // expected-note {{in call to function 'foo(_:item:)'}}
    fatalError()
  }

  func bar(_ item: Item) {
    foo(item: item) // expected-error {{generic parameter 'I' could not be inferred}}
  }
}

// https://github.com/apple/swift/issues/54017
// Compiler crash on missing conformance for default param
do {
  func foo<T : Initable>(_ x: T = .init()) -> T { x } // expected-note {{where 'T' = 'String'}}
  let _: String = foo()
  // expected-error@-1 {{local function 'foo' requires that 'String' conform to 'Initable'}}
}

// rdar://70814576 -- failed to produce a diagnostic when implicit value-to-optional conversion is involved.
func rdar70814576() {
  struct S {}

  func test(_: Fooable?) {
  }

  test(S()) // expected-error {{argument type 'S' does not conform to expected type 'Fooable'}}
}

extension Optional : Trivial {
  typealias T = Wrapped
}

extension UnsafePointer : Trivial {
  typealias T = Int
}

extension AnyHashable : Trivial {
  typealias T = Int
}

extension UnsafeRawPointer : Trivial {
  typealias T = Int
}

extension UnsafeMutableRawPointer : Trivial {
  typealias T = Int
}

func test_inference_through_implicit_conversion() {
  struct C : Hashable {}

  func test<T: Trivial>(_: T) -> T {}

  var arr: [C] = []
  let ptr: UnsafeMutablePointer<C> = UnsafeMutablePointer(bitPattern: 0)!
  let rawPtr: UnsafeMutableRawPointer = UnsafeMutableRawPointer(bitPattern: 0)!

  let _: C? = test(C()) // Ok -> argument is implicitly promoted into an optional
  let _: UnsafePointer<C> = test([C()]) // Ok - argument is implicitly converted to a pointer
  let _: UnsafeRawPointer = test([C()]) // Ok - argument is implicitly converted to a raw pointer
  let _: UnsafeMutableRawPointer = test(&arr) // Ok - inout Array<T> -> UnsafeMutableRawPointer
  let _: UnsafePointer<C> = test(ptr) // Ok - UnsafeMutablePointer<T> -> UnsafePointer<T>
  let _: UnsafeRawPointer = test(ptr) // Ok - UnsafeMutablePointer<T> -> UnsafeRawPointer
  let _: UnsafeRawPointer = test(rawPtr) // Ok - UnsafeMutableRawPointer -> UnsafeRawPointer
  let _: UnsafeMutableRawPointer = test(ptr) // Ok - UnsafeMutablePointer<T> -> UnsafeMutableRawPointer
  let _: AnyHashable = test(C()) // Ok - argument is implicitly converted to `AnyHashable` because it's Hashable
}

// Make sure that conformances transitively checked through implicit conversions work with conditional requirements
protocol TestCond {}

extension Optional : TestCond where Wrapped == Int? {}

func simple<T : TestCond>(_ x: T) -> T { x }

func overloaded<T: TestCond>(_ x: T) -> T { x }
func overloaded<T: TestCond>(_ x: String) -> T { fatalError() }

func overloaded_result() -> Int { 42 }
func overloaded_result() -> String { "" }

func test_arg_conformance_with_conditional_reqs(i: Int) {
  let _: Int?? = simple(i)
  let _: Int?? = overloaded(i)
  let _: Int?? = simple(overloaded_result())
  let _: Int?? = overloaded(overloaded_result())
}

// rdar://77570994 - regression in type unification for literal collections

protocol Elt {
}

extension Int : Elt {}
extension Int64 : Elt {}
extension Dictionary : Elt where Key == String, Value: Elt {}

struct Object {}

extension Object : ExpressibleByDictionaryLiteral {
  init(dictionaryLiteral elements: (String, Elt)...) {
  }
}

enum E {
case test(cond: Bool, v: Int64)

  var test_prop: Object {
    switch self {
    case let .test(cond, v):
      return ["obj": ["a": v, "b": cond ? 0 : 42]] // Ok
    }
  }
}

// https://github.com/apple/swift/issues/58231

protocol P_58231 {}
struct S_58231 {}

func f1_58231(x: Int) -> P_58231 {
  return S_58231() // expected-error{{return expression of type 'S_58231' does not conform to 'P_58231'}}
}

func f2_58231(x: Int) -> P_58231? {
  return S_58231() // expected-error{{return expression of type 'S_58231' does not conform to 'P_58231'}}
}

// https://github.com/apple/swift/issues/61517

protocol P_61517 {
  init()
  init(_: Bool)
}

_ = P_61517() // expected-error{{type 'any P_61517' cannot be instantiated}}
_ = P_61517(false) // expected-error{{type 'any P_61517' cannot be instantiated}}

_ = P_61517.init() // expected-error{{type 'any P_61517' cannot be instantiated}}
_ = P_61517.init(false) // expected-error{{type 'any P_61517' cannot be instantiated}}

@_marker
protocol Marker {}

do {
  class C : Fooable, Error {
    func foo() {}
  }

  struct Other {}

  func overloaded() -> C & Marker {
    fatalError()
  }

  func overloaded() -> Other {
    fatalError()
  }

  func isFooable<T: Fooable>(_: T) {}

  isFooable(overloaded()) // Ok

  func isError<T: Error>(_: T) {}

  isError(overloaded()) // Ok

  func isFooableError<T: Fooable & Error>(_: T) {}

  isFooableError(overloaded()) // Ok
}