-
Notifications
You must be signed in to change notification settings - Fork 10.4k
/
Copy pathObservable.swift
518 lines (417 loc) · 11.4 KB
/
Observable.swift
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
// REQUIRES: swift_swift_parser, executable_test
// RUN: %target-run-simple-swift( -Xfrontend -disable-availability-checking -parse-as-library -enable-experimental-feature Macros -Xfrontend -plugin-path -Xfrontend %swift-plugin-dir)
// Run this test via the swift-plugin-server
// RUN: %target-run-simple-swift( -Xfrontend -disable-availability-checking -parse-as-library -enable-experimental-feature Macros -Xfrontend -external-plugin-path -Xfrontend %swift-plugin-dir#%swift-plugin-server)
// REQUIRES: observation
// REQUIRES: concurrency
// REQUIRES: objc_interop
// REQUIRES: swift_feature_Macros
// UNSUPPORTED: use_os_stdlib
// UNSUPPORTED: back_deployment_runtime
import StdlibUnittest
import Observation
@usableFromInline
@inline(never)
func _blackHole<T>(_ value: T) { }
@Observable
class ContainsNothing { }
@Observable
class ContainsWeak {
weak var obj: AnyObject? = nil
}
@Observable
public class PublicContainsWeak {
public weak var obj: AnyObject? = nil
}
@Observable
class ContainsUnowned {
unowned var obj: AnyObject? = nil
}
@Observable
class ContainsIUO {
var obj: Int! = nil
}
class NonObservable {
}
@Observable
class InheritsFromNonObservable: NonObservable {
}
protocol NonObservableProtocol {
}
@Observable
class ConformsToNonObservableProtocol: NonObservableProtocol {
}
struct NonObservableContainer {
@Observable
class ObservableContents {
var field: Int = 3
}
}
@Observable
final class SendableClass: Sendable {
var field: Int = 3
}
@Observable
class CodableClass: Codable {
var field: Int = 3
}
@Observable
final class HashableClass {
var field: Int = 3
}
extension HashableClass: Hashable {
static func == (lhs: HashableClass, rhs: HashableClass) -> Bool {
lhs.field == rhs.field
}
func hash(into hasher: inout Hasher) {
hasher.combine(field)
}
}
@Observable
class ImplementsAccessAndMutation {
var field = 3
let accessCalled: (PartialKeyPath<ImplementsAccessAndMutation>) -> Void
let withMutationCalled: (PartialKeyPath<ImplementsAccessAndMutation>) -> Void
init(accessCalled: @escaping (PartialKeyPath<ImplementsAccessAndMutation>) -> Void, withMutationCalled: @escaping (PartialKeyPath<ImplementsAccessAndMutation>) -> Void) {
self.accessCalled = accessCalled
self.withMutationCalled = withMutationCalled
}
internal func access<Member>(
keyPath: KeyPath<ImplementsAccessAndMutation , Member>
) {
accessCalled(keyPath)
_$observationRegistrar.access(self, keyPath: keyPath)
}
internal func withMutation<Member, T>(
keyPath: KeyPath<ImplementsAccessAndMutation , Member>,
_ mutation: () throws -> T
) rethrows -> T {
withMutationCalled(keyPath)
return try _$observationRegistrar.withMutation(of: self, keyPath: keyPath, mutation)
}
}
@Observable
class HasIgnoredProperty {
var field = 3
@ObservationIgnored var ignored = 4
}
@Observable
class Entity {
var age: Int = 0
}
@Observable
class Person : Entity {
var firstName = ""
var lastName = ""
var friends = [Person]()
var fullName: String { firstName + " " + lastName }
}
@Observable
class MiddleNamePerson: Person {
var middleName = ""
override var fullName: String { firstName + " " + middleName + " " + lastName }
}
@Observable
class IsolatedClass {
@MainActor var test = "hello"
}
@MainActor
@Observable
class IsolatedInstance {
var test = "hello"
}
@Observable
class IgnoredComputed {
@ObservationIgnored
var message: String { "hello" }
}
@Observable
class ClassHasExistingConformance: Observable { }
protocol Intermediary: Observable { }
@Observable
class HasIntermediaryConformance: Intermediary { }
class CapturedState<State>: @unchecked Sendable {
var state: State
init(state: State) {
self.state = state
}
}
@Observable
class RecursiveInner {
var value = "prefix"
}
@Observable
class GenericClass<T> {
var value = 3
}
struct StructParent {
@Observable
class NestedGenericClass<T> {
var value = 3
}
}
struct GenericStructParent<T> {
@Observable
class NestedClass {
var value = 3
}
}
class ClassParent {
@Observable
class NestedGenericClass<T> {
var value = 3
}
}
class GenericClassParent<T> {
@Observable
class NestedClass {
var value = 3
}
}
@Observable
class RecursiveOuter {
var inner = RecursiveInner()
var value = "prefix"
@ObservationIgnored var innerEventCount = 0
@ObservationIgnored var outerEventCount = 0
func recursiveTrackingCalls() {
withObservationTracking({
let _ = value
_ = withObservationTracking({
inner.value
}, onChange: {
self.innerEventCount += 1
})
}, onChange: {
self.outerEventCount += 1
})
}
}
@Observable
#if FOO
@available(SwiftStdlib 5.9, *)
#elseif BAR
@available(SwiftStdlib 5.9, *)
#else
#endif
class GuardedAvailability {
}
@Observable class TestASTScopeLCA {
// Make sure ASTScope unqualified lookup can find local variables
// inside initial values with closures when accessor macros are
// involved.
var state : Bool = {
let value = true
return value
}()
}
@Observable class Parent {
class Nested {}
}
extension Parent.Nested {}
struct CowContainer {
final class Contents { }
var contents = Contents()
mutating func mutate() {
if !isKnownUniquelyReferenced(&contents) {
contents = Contents()
}
}
var id: ObjectIdentifier {
ObjectIdentifier(contents)
}
}
@Observable
final class CowTest {
var container = CowContainer()
}
@main
struct Validator {
@MainActor
static func main() {
let suite = TestSuite("Observable")
suite.test("only instantiate") {
let test = MiddleNamePerson()
}
suite.test("unobserved value changes") {
let test = MiddleNamePerson()
for i in 0..<100 {
test.firstName = "\(i)"
}
}
suite.test("tracking changes") {
let changed = CapturedState(state: false)
let test = MiddleNamePerson()
withObservationTracking {
_blackHole(test.firstName)
} onChange: {
changed.state = true
}
test.firstName = "c"
expectEqual(changed.state, true)
changed.state = false
test.firstName = "c"
expectEqual(changed.state, false)
}
suite.test("conformance") {
func testConformance<O: Observable>(_ o: O) -> Bool {
return true
}
func testConformance<O>(_ o: O) -> Bool {
return false
}
let test = Person()
expectEqual(testConformance(test), true)
}
suite.test("tracking nonchanged") {
let changed = CapturedState(state: false)
let test = MiddleNamePerson()
withObservationTracking {
_blackHole(test.lastName)
} onChange: {
changed.state = true
}
test.firstName = "c"
expectEqual(changed.state, false)
}
suite.test("tracking computed") {
let changed = CapturedState(state: false)
let test = MiddleNamePerson()
withObservationTracking {
_blackHole(test.fullName)
} onChange: {
changed.state = true
}
test.middleName = "c"
expectEqual(changed.state, true)
changed.state = false
test.middleName = "c"
expectEqual(changed.state, false)
}
suite.test("graph changes") {
let changed = CapturedState(state: false)
let test = MiddleNamePerson()
let friend = MiddleNamePerson()
test.friends.append(friend)
withObservationTracking {
_blackHole(test.friends.first?.fullName)
} onChange: {
changed.state = true
}
test.middleName = "c"
expectEqual(changed.state, false)
friend.middleName = "c"
expectEqual(changed.state, true)
}
suite.test("nesting") {
let changedOuter = CapturedState(state: false)
let changedInner = CapturedState(state: false)
let test = MiddleNamePerson()
withObservationTracking {
withObservationTracking {
_blackHole(test.firstName)
} onChange: {
changedInner.state = true
}
} onChange: {
changedOuter.state = true
}
test.firstName = "c"
expectEqual(changedInner.state, true)
expectEqual(changedOuter.state, true)
changedOuter.state = false
test.firstName = "c"
expectEqual(changedOuter.state, false)
}
suite.test("access and mutation") {
let accessKeyPath = CapturedState<PartialKeyPath<ImplementsAccessAndMutation>?>(state: nil)
let mutationKeyPath = CapturedState<PartialKeyPath<ImplementsAccessAndMutation>?>(state: nil)
let test = ImplementsAccessAndMutation { keyPath in
accessKeyPath.state = keyPath
} withMutationCalled: { keyPath in
mutationKeyPath.state = keyPath
}
expectEqual(accessKeyPath.state, nil)
_blackHole(test.field)
expectEqual(accessKeyPath.state, \.field)
expectEqual(mutationKeyPath.state, nil)
accessKeyPath.state = nil
test.field = 123
expectEqual(accessKeyPath.state, nil)
expectEqual(mutationKeyPath.state, \.field)
}
suite.test("ignores no change") {
let changed = CapturedState(state: false)
let test = HasIgnoredProperty()
withObservationTracking {
_blackHole(test.ignored)
} onChange: {
changed.state = true
}
test.ignored = 122112
expectEqual(changed.state, false)
changed.state = false
test.field = 3429
expectEqual(changed.state, false)
}
suite.test("ignores change") {
let changed = CapturedState(state: false)
let test = HasIgnoredProperty()
withObservationTracking {
_blackHole(test.ignored)
_blackHole(test.field)
} onChange: {
changed.state = true
}
test.ignored = 122112
expectEqual(changed.state, false)
changed.state = false
test.field = 3429
expectEqual(changed.state, true)
}
suite.test("isolated class") { @MainActor in
let changed = CapturedState(state: false)
let test = IsolatedClass()
withObservationTracking {
_blackHole(test.test)
} onChange: {
changed.state = true
}
test.test = "c"
expectEqual(changed.state, true)
changed.state = false
test.test = "c"
expectEqual(changed.state, false)
}
suite.test("recursive tracking inner then outer") {
let obj = RecursiveOuter()
obj.recursiveTrackingCalls()
obj.inner.value = "test"
expectEqual(obj.innerEventCount, 1)
expectEqual(obj.outerEventCount, 1)
obj.recursiveTrackingCalls()
obj.value = "test"
expectEqual(obj.innerEventCount, 1)
expectEqual(obj.outerEventCount, 2)
}
suite.test("recursive tracking outer then inner") {
let obj = RecursiveOuter()
obj.recursiveTrackingCalls()
obj.value = "test"
expectEqual(obj.innerEventCount, 0)
expectEqual(obj.outerEventCount, 1)
obj.recursiveTrackingCalls()
obj.inner.value = "test"
expectEqual(obj.innerEventCount, 2)
expectEqual(obj.outerEventCount, 2)
}
suite.test("validate copy on write semantics") {
let subject = CowTest()
let startId = subject.container.id
expectEqual(subject.container.id, startId)
subject.container.mutate()
expectEqual(subject.container.id, startId)
}
runAllTests()
}
}