-
Notifications
You must be signed in to change notification settings - Fork 10.4k
/
Copy pathKeyPath.swift
3493 lines (3130 loc) · 128 KB
/
KeyPath.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
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
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import SwiftShims
internal func _abstract(
methodName: StaticString = #function,
file: StaticString = #file, line: UInt = #line
) -> Never {
#if INTERNAL_CHECKS_ENABLED
_fatalErrorMessage("abstract method", methodName, file: file, line: line,
flags: _fatalErrorFlags())
#else
_conditionallyUnreachable()
#endif
}
// MARK: Type-erased abstract base classes
// NOTE: older runtimes had Swift.AnyKeyPath as the ObjC name.
// The two must coexist, so it was renamed. The old name must not be
// used in the new runtime. _TtCs11_AnyKeyPath is the mangled name for
// Swift._AnyKeyPath.
@_objcRuntimeName(_TtCs11_AnyKeyPath)
/// A type-erased key path, from any root type to any resulting value
/// type.
public class AnyKeyPath: Hashable, _AppendKeyPath {
/// The root type for this key path.
@inlinable
public static var rootType: Any.Type {
return _rootAndValueType.root
}
/// The value type for this key path.
@inlinable
public static var valueType: Any.Type {
return _rootAndValueType.value
}
internal final var _kvcKeyPathStringPtr: UnsafePointer<CChar>?
/// The hash value.
final public var hashValue: Int {
return _hashValue(for: self)
}
/// Hashes the essential components of this value by feeding them into the
/// given hasher.
///
/// - Parameter hasher: The hasher to use when combining the components
/// of this instance.
@_effects(releasenone)
final public func hash(into hasher: inout Hasher) {
ObjectIdentifier(type(of: self)).hash(into: &hasher)
return withBuffer {
var buffer = $0
if buffer.data.isEmpty { return }
while true {
let (component, type) = buffer.next()
hasher.combine(component.value)
if let type = type {
hasher.combine(unsafeBitCast(type, to: Int.self))
} else {
break
}
}
}
}
public static func ==(a: AnyKeyPath, b: AnyKeyPath) -> Bool {
// Fast-path identical objects
if a === b {
return true
}
// Short-circuit differently-typed key paths
if type(of: a) != type(of: b) {
return false
}
return a.withBuffer {
var aBuffer = $0
return b.withBuffer {
var bBuffer = $0
// Two equivalent key paths should have the same reference prefix
if aBuffer.hasReferencePrefix != bBuffer.hasReferencePrefix {
return false
}
// Identity is equal to identity
if aBuffer.data.isEmpty {
return bBuffer.data.isEmpty
}
while true {
let (aComponent, aType) = aBuffer.next()
let (bComponent, bType) = bBuffer.next()
if aComponent.header.endOfReferencePrefix
!= bComponent.header.endOfReferencePrefix
|| aComponent.value != bComponent.value
|| aType != bType {
return false
}
if aType == nil {
return true
}
}
}
}
}
// SPI for the Foundation overlay to allow interop with KVC keypath-based
// APIs.
public var _kvcKeyPathString: String? {
guard let ptr = _kvcKeyPathStringPtr else { return nil }
return String(validatingUTF8: ptr)
}
// MARK: Implementation details
// Prevent normal initialization. We use tail allocation via
// allocWithTailElems().
internal init() {
_internalInvariantFailure("use _create(...)")
}
@usableFromInline
internal class var _rootAndValueType: (root: Any.Type, value: Any.Type) {
_abstract()
}
internal static func _create(
capacityInBytes bytes: Int,
initializedBy body: (UnsafeMutableRawBufferPointer) -> Void
) -> Self {
_internalInvariant(bytes > 0 && bytes % 4 == 0,
"capacity must be multiple of 4 bytes")
let result = Builtin.allocWithTailElems_1(self, (bytes/4)._builtinWordValue,
Int32.self)
result._kvcKeyPathStringPtr = nil
let base = UnsafeMutableRawPointer(Builtin.projectTailElems(result,
Int32.self))
body(UnsafeMutableRawBufferPointer(start: base, count: bytes))
return result
}
internal func withBuffer<T>(_ f: (KeyPathBuffer) throws -> T) rethrows -> T {
defer { _fixLifetime(self) }
let base = UnsafeRawPointer(Builtin.projectTailElems(self, Int32.self))
return try f(KeyPathBuffer(base: base))
}
@usableFromInline // Exposed as public API by MemoryLayout<Root>.offset(of:)
internal var _storedInlineOffset: Int? {
return withBuffer {
var buffer = $0
// The identity key path is effectively a stored keypath of type Self
// at offset zero
if buffer.data.isEmpty { return 0 }
var offset = 0
while true {
let (rawComponent, optNextType) = buffer.next()
switch rawComponent.header.kind {
case .struct:
offset += rawComponent._structOrClassOffset
case .class, .computed, .optionalChain, .optionalForce, .optionalWrap, .external:
return .none
}
if optNextType == nil { return .some(offset) }
}
}
}
}
/// A partially type-erased key path, from a concrete root type to any
/// resulting value type.
public class PartialKeyPath<Root>: AnyKeyPath { }
// MARK: Concrete implementations
internal enum KeyPathKind { case readOnly, value, reference }
/// A key path from a specific root type to a specific resulting value type.
public class KeyPath<Root, Value>: PartialKeyPath<Root> {
@usableFromInline
internal final override class var _rootAndValueType: (
root: Any.Type,
value: Any.Type
) {
return (Root.self, Value.self)
}
// MARK: Implementation
internal typealias Kind = KeyPathKind
internal class var kind: Kind { return .readOnly }
internal static func appendedType<AppendedValue>(
with t: KeyPath<Value, AppendedValue>.Type
) -> KeyPath<Root, AppendedValue>.Type {
let resultKind: Kind
switch (self.kind, t.kind) {
case (_, .reference):
resultKind = .reference
case (let x, .value):
resultKind = x
default:
resultKind = .readOnly
}
switch resultKind {
case .readOnly:
return KeyPath<Root, AppendedValue>.self
case .value:
return WritableKeyPath.self
case .reference:
return ReferenceWritableKeyPath.self
}
}
@usableFromInline
internal final func _projectReadOnly(from root: Root) -> Value {
// TODO: For perf, we could use a local growable buffer instead of Any
var curBase: Any = root
return withBuffer {
var buffer = $0
if buffer.data.isEmpty {
return unsafeBitCast(root, to: Value.self)
}
while true {
let (rawComponent, optNextType) = buffer.next()
let valueType = optNextType ?? Value.self
let isLast = optNextType == nil
func project<CurValue>(_ base: CurValue) -> Value? {
func project2<NewValue>(_: NewValue.Type) -> Value? {
switch rawComponent._projectReadOnly(base,
to: NewValue.self, endingWith: Value.self) {
case .continue(let newBase):
if isLast {
_internalInvariant(NewValue.self == Value.self,
"key path does not terminate in correct type")
return unsafeBitCast(newBase, to: Value.self)
} else {
curBase = newBase
return nil
}
case .break(let result):
return result
}
}
return _openExistential(valueType, do: project2)
}
if let result = _openExistential(curBase, do: project) {
return result
}
}
}
}
deinit {
withBuffer { $0.destroy() }
}
}
/// A key path that supports reading from and writing to the resulting value.
public class WritableKeyPath<Root, Value>: KeyPath<Root, Value> {
// MARK: Implementation detail
internal override class var kind: Kind { return .value }
// `base` is assumed to be undergoing a formal access for the duration of the
// call, so must not be mutated by an alias
@usableFromInline
internal func _projectMutableAddress(from base: UnsafePointer<Root>)
-> (pointer: UnsafeMutablePointer<Value>, owner: AnyObject?) {
var p = UnsafeRawPointer(base)
var type: Any.Type = Root.self
var keepAlive: AnyObject?
return withBuffer {
var buffer = $0
_internalInvariant(!buffer.hasReferencePrefix,
"WritableKeyPath should not have a reference prefix")
if buffer.data.isEmpty {
return (
UnsafeMutablePointer<Value>(
mutating: p.assumingMemoryBound(to: Value.self)),
nil)
}
while true {
let (rawComponent, optNextType) = buffer.next()
let nextType = optNextType ?? Value.self
func project<CurValue>(_: CurValue.Type) {
func project2<NewValue>(_: NewValue.Type) {
p = rawComponent._projectMutableAddress(p,
from: CurValue.self,
to: NewValue.self,
isRoot: p == UnsafeRawPointer(base),
keepAlive: &keepAlive)
}
_openExistential(nextType, do: project2)
}
_openExistential(type, do: project)
if optNextType == nil { break }
type = nextType
}
// TODO: With coroutines, it would be better to yield here, so that
// we don't need the hack of the keepAlive reference to manage closing
// accesses.
let typedPointer = p.assumingMemoryBound(to: Value.self)
return (pointer: UnsafeMutablePointer(mutating: typedPointer),
owner: keepAlive)
}
}
}
/// A key path that supports reading from and writing to the resulting value
/// with reference semantics.
public class ReferenceWritableKeyPath<
Root, Value
> : WritableKeyPath<Root, Value> {
// MARK: Implementation detail
internal final override class var kind: Kind { return .reference }
internal final override func _projectMutableAddress(
from base: UnsafePointer<Root>
) -> (pointer: UnsafeMutablePointer<Value>, owner: AnyObject?) {
// Since we're a ReferenceWritableKeyPath, we know we don't mutate the base
// in practice.
return _projectMutableAddress(from: base.pointee)
}
@usableFromInline
internal final func _projectMutableAddress(from origBase: Root)
-> (pointer: UnsafeMutablePointer<Value>, owner: AnyObject?) {
var keepAlive: AnyObject?
var address: UnsafeMutablePointer<Value> = withBuffer {
var buffer = $0
// Project out the reference prefix.
var base: Any = origBase
while buffer.hasReferencePrefix {
let (rawComponent, optNextType) = buffer.next()
_internalInvariant(optNextType != nil,
"reference prefix should not go to end of buffer")
let nextType = optNextType.unsafelyUnwrapped
func project<NewValue>(_: NewValue.Type) -> Any {
func project2<CurValue>(_ base: CurValue) -> Any {
return rawComponent._projectReadOnly(
base, to: NewValue.self, endingWith: Value.self)
.assumingContinue
}
return _openExistential(base, do: project2)
}
base = _openExistential(nextType, do: project)
}
// Start formal access to the mutable value, based on the final base
// value.
func formalMutation<MutationRoot>(_ base: MutationRoot)
-> UnsafeMutablePointer<Value> {
var base2 = base
return withUnsafeBytes(of: &base2) { baseBytes in
var p = baseBytes.baseAddress.unsafelyUnwrapped
var curType: Any.Type = MutationRoot.self
while true {
let (rawComponent, optNextType) = buffer.next()
let nextType = optNextType ?? Value.self
func project<CurValue>(_: CurValue.Type) {
func project2<NewValue>(_: NewValue.Type) {
p = rawComponent._projectMutableAddress(p,
from: CurValue.self,
to: NewValue.self,
isRoot: p == baseBytes.baseAddress,
keepAlive: &keepAlive)
}
_openExistential(nextType, do: project2)
}
_openExistential(curType, do: project)
if optNextType == nil { break }
curType = nextType
}
let typedPointer = p.assumingMemoryBound(to: Value.self)
return UnsafeMutablePointer(mutating: typedPointer)
}
}
return _openExistential(base, do: formalMutation)
}
return (address, keepAlive)
}
}
// MARK: Implementation details
internal enum KeyPathComponentKind {
/// The keypath references an externally-defined property or subscript whose
/// component describes how to interact with the key path.
case external
/// The keypath projects within the storage of the outer value, like a
/// stored property in a struct.
case `struct`
/// The keypath projects from the referenced pointer, like a
/// stored property in a class.
case `class`
/// The keypath projects using a getter/setter pair.
case computed
/// The keypath optional-chains, returning nil immediately if the input is
/// nil, or else proceeding by projecting the value inside.
case optionalChain
/// The keypath optional-forces, trapping if the input is
/// nil, or else proceeding by projecting the value inside.
case optionalForce
/// The keypath wraps a value in an optional.
case optionalWrap
}
internal struct ComputedPropertyID: Hashable {
internal var value: Int
internal var kind: KeyPathComputedIDKind
internal static func ==(
x: ComputedPropertyID, y: ComputedPropertyID
) -> Bool {
return x.value == y.value
&& x.kind == y.kind
}
internal func hash(into hasher: inout Hasher) {
hasher.combine(value)
hasher.combine(kind)
}
}
internal struct ComputedArgumentWitnesses {
internal typealias Destroy = @convention(thin)
(_ instanceArguments: UnsafeMutableRawPointer, _ size: Int) -> ()
internal typealias Copy = @convention(thin)
(_ srcInstanceArguments: UnsafeRawPointer,
_ destInstanceArguments: UnsafeMutableRawPointer,
_ size: Int) -> ()
internal typealias Equals = @convention(thin)
(_ xInstanceArguments: UnsafeRawPointer,
_ yInstanceArguments: UnsafeRawPointer,
_ size: Int) -> Bool
// FIXME(hasher) Combine to an inout Hasher instead
internal typealias Hash = @convention(thin)
(_ instanceArguments: UnsafeRawPointer,
_ size: Int) -> Int
internal let destroy: Destroy?
internal let copy: Copy
internal let equals: Equals
internal let hash: Hash
}
internal enum KeyPathComponent: Hashable {
internal struct ArgumentRef {
internal init(
data: UnsafeRawBufferPointer,
witnesses: UnsafePointer<ComputedArgumentWitnesses>,
witnessSizeAdjustment: Int
) {
self.data = data
self.witnesses = witnesses
self.witnessSizeAdjustment = witnessSizeAdjustment
}
internal var data: UnsafeRawBufferPointer
internal var witnesses: UnsafePointer<ComputedArgumentWitnesses>
internal var witnessSizeAdjustment: Int
}
/// The keypath projects within the storage of the outer value, like a
/// stored property in a struct.
case `struct`(offset: Int)
/// The keypath projects from the referenced pointer, like a
/// stored property in a class.
case `class`(offset: Int)
/// The keypath projects using a getter.
case get(id: ComputedPropertyID,
get: UnsafeRawPointer, argument: ArgumentRef?)
/// The keypath projects using a getter/setter pair. The setter can mutate
/// the base value in-place.
case mutatingGetSet(id: ComputedPropertyID,
get: UnsafeRawPointer, set: UnsafeRawPointer,
argument: ArgumentRef?)
/// The keypath projects using a getter/setter pair that does not mutate its
/// base.
case nonmutatingGetSet(id: ComputedPropertyID,
get: UnsafeRawPointer, set: UnsafeRawPointer,
argument: ArgumentRef?)
/// The keypath optional-chains, returning nil immediately if the input is
/// nil, or else proceeding by projecting the value inside.
case optionalChain
/// The keypath optional-forces, trapping if the input is
/// nil, or else proceeding by projecting the value inside.
case optionalForce
/// The keypath wraps a value in an optional.
case optionalWrap
internal static func ==(a: KeyPathComponent, b: KeyPathComponent) -> Bool {
switch (a, b) {
case (.struct(offset: let a), .struct(offset: let b)),
(.class (offset: let a), .class (offset: let b)):
return a == b
case (.optionalChain, .optionalChain),
(.optionalForce, .optionalForce),
(.optionalWrap, .optionalWrap):
return true
case (.get(id: let id1, get: _, argument: let argument1),
.get(id: let id2, get: _, argument: let argument2)),
(.mutatingGetSet(id: let id1, get: _, set: _, argument: let argument1),
.mutatingGetSet(id: let id2, get: _, set: _, argument: let argument2)),
(.nonmutatingGetSet(id: let id1, get: _, set: _, argument: let argument1),
.nonmutatingGetSet(id: let id2, get: _, set: _, argument: let argument2)):
if id1 != id2 {
return false
}
if let arg1 = argument1, let arg2 = argument2 {
return arg1.witnesses.pointee.equals(
arg1.data.baseAddress.unsafelyUnwrapped,
arg2.data.baseAddress.unsafelyUnwrapped,
arg1.data.count - arg1.witnessSizeAdjustment)
}
// If only one component has arguments, that should indicate that the
// only arguments in that component were generic captures and therefore
// not affecting equality.
return true
case (.struct, _),
(.class, _),
(.optionalChain, _),
(.optionalForce, _),
(.optionalWrap, _),
(.get, _),
(.mutatingGetSet, _),
(.nonmutatingGetSet, _):
return false
}
}
@_effects(releasenone)
internal func hash(into hasher: inout Hasher) {
func appendHashFromArgument(
_ argument: KeyPathComponent.ArgumentRef?
) {
if let argument = argument {
let hash = argument.witnesses.pointee.hash(
argument.data.baseAddress.unsafelyUnwrapped,
argument.data.count - argument.witnessSizeAdjustment)
// Returning 0 indicates that the arguments should not impact the
// hash value of the overall key path.
// FIXME(hasher): hash witness should just mutate hasher directly
if hash != 0 {
hasher.combine(hash)
}
}
}
switch self {
case .struct(offset: let a):
hasher.combine(0)
hasher.combine(a)
case .class(offset: let b):
hasher.combine(1)
hasher.combine(b)
case .optionalChain:
hasher.combine(2)
case .optionalForce:
hasher.combine(3)
case .optionalWrap:
hasher.combine(4)
case .get(id: let id, get: _, argument: let argument):
hasher.combine(5)
hasher.combine(id)
appendHashFromArgument(argument)
case .mutatingGetSet(id: let id, get: _, set: _, argument: let argument):
hasher.combine(6)
hasher.combine(id)
appendHashFromArgument(argument)
case .nonmutatingGetSet(id: let id, get: _, set: _, argument: let argument):
hasher.combine(7)
hasher.combine(id)
appendHashFromArgument(argument)
}
}
}
// A class that maintains ownership of another object while a mutable projection
// into it is underway. The lifetime of the instance of this class is also used
// to begin and end exclusive 'modify' access to the projected address.
internal final class ClassHolder<ProjectionType> {
/// The type of the scratch record passed to the runtime to record
/// accesses to guarantee exlcusive access.
internal typealias AccessRecord = Builtin.UnsafeValueBuffer
internal var previous: AnyObject?
internal var instance: AnyObject
internal init(previous: AnyObject?, instance: AnyObject) {
self.previous = previous
self.instance = instance
}
internal final class func _create(
previous: AnyObject?,
instance: AnyObject,
accessingAddress address: UnsafeRawPointer,
type: ProjectionType.Type
) -> ClassHolder {
// Tail allocate the UnsafeValueBuffer used as the AccessRecord.
// This avoids a second heap allocation since there is no source-level way to
// initialize a Builtin.UnsafeValueBuffer type and thus we cannot have a
// stored property of that type.
let holder: ClassHolder = Builtin.allocWithTailElems_1(self,
1._builtinWordValue,
AccessRecord.self)
// Initialize the ClassHolder's instance variables. This is done via
// withUnsafeMutablePointer(to:) because the instance was just allocated with
// allocWithTailElems_1 and so we need to make sure to use an initialization
// rather than an assignment.
withUnsafeMutablePointer(to: &holder.previous) {
$0.initialize(to: previous)
}
withUnsafeMutablePointer(to: &holder.instance) {
$0.initialize(to: instance)
}
let accessRecordPtr = Builtin.projectTailElems(holder, AccessRecord.self)
// Begin a 'modify' access to the address. This access is ended in
// ClassHolder's deinitializer.
Builtin.beginUnpairedModifyAccess(address._rawValue, accessRecordPtr, type)
return holder
}
deinit {
let accessRecordPtr = Builtin.projectTailElems(self, AccessRecord.self)
// Ends the access begun in _create().
Builtin.endUnpairedAccess(accessRecordPtr)
}
}
// A class that triggers writeback to a pointer when destroyed.
internal final class MutatingWritebackBuffer<CurValue, NewValue> {
internal let previous: AnyObject?
internal let base: UnsafeMutablePointer<CurValue>
internal let set: @convention(thin) (NewValue, inout CurValue, UnsafeRawPointer, Int) -> ()
internal let argument: UnsafeRawPointer
internal let argumentSize: Int
internal var value: NewValue
deinit {
set(value, &base.pointee, argument, argumentSize)
}
internal init(previous: AnyObject?,
base: UnsafeMutablePointer<CurValue>,
set: @escaping @convention(thin) (NewValue, inout CurValue, UnsafeRawPointer, Int) -> (),
argument: UnsafeRawPointer,
argumentSize: Int,
value: NewValue) {
self.previous = previous
self.base = base
self.set = set
self.argument = argument
self.argumentSize = argumentSize
self.value = value
}
}
// A class that triggers writeback to a non-mutated value when destroyed.
internal final class NonmutatingWritebackBuffer<CurValue, NewValue> {
internal let previous: AnyObject?
internal let base: CurValue
internal let set: @convention(thin) (NewValue, CurValue, UnsafeRawPointer, Int) -> ()
internal let argument: UnsafeRawPointer
internal let argumentSize: Int
internal var value: NewValue
deinit {
set(value, base, argument, argumentSize)
}
internal
init(previous: AnyObject?,
base: CurValue,
set: @escaping @convention(thin) (NewValue, CurValue, UnsafeRawPointer, Int) -> (),
argument: UnsafeRawPointer,
argumentSize: Int,
value: NewValue) {
self.previous = previous
self.base = base
self.set = set
self.argument = argument
self.argumentSize = argumentSize
self.value = value
}
}
internal typealias KeyPathComputedArgumentLayoutFn = @convention(thin)
(_ patternArguments: UnsafeRawPointer?) -> (size: Int, alignmentMask: Int)
internal typealias KeyPathComputedArgumentInitializerFn = @convention(thin)
(_ patternArguments: UnsafeRawPointer?,
_ instanceArguments: UnsafeMutableRawPointer) -> ()
internal enum KeyPathComputedIDKind {
case pointer
case storedPropertyIndex
case vtableOffset
}
internal enum KeyPathComputedIDResolution {
case resolved
case indirectPointer
case functionCall
}
internal struct RawKeyPathComponent {
internal init(header: Header, body: UnsafeRawBufferPointer) {
self.header = header
self.body = body
}
internal var header: Header
internal var body: UnsafeRawBufferPointer
internal struct Header {
internal static var payloadMask: UInt32 {
return _SwiftKeyPathComponentHeader_PayloadMask
}
internal static var discriminatorMask: UInt32 {
return _SwiftKeyPathComponentHeader_DiscriminatorMask
}
internal static var discriminatorShift: UInt32 {
return _SwiftKeyPathComponentHeader_DiscriminatorShift
}
internal static var externalTag: UInt32 {
return _SwiftKeyPathComponentHeader_ExternalTag
}
internal static var structTag: UInt32 {
return _SwiftKeyPathComponentHeader_StructTag
}
internal static var computedTag: UInt32 {
return _SwiftKeyPathComponentHeader_ComputedTag
}
internal static var classTag: UInt32 {
return _SwiftKeyPathComponentHeader_ClassTag
}
internal static var optionalTag: UInt32 {
return _SwiftKeyPathComponentHeader_OptionalTag
}
internal static var optionalChainPayload: UInt32 {
return _SwiftKeyPathComponentHeader_OptionalChainPayload
}
internal static var optionalWrapPayload: UInt32 {
return _SwiftKeyPathComponentHeader_OptionalWrapPayload
}
internal static var optionalForcePayload: UInt32 {
return _SwiftKeyPathComponentHeader_OptionalForcePayload
}
internal static var endOfReferencePrefixFlag: UInt32 {
return _SwiftKeyPathComponentHeader_EndOfReferencePrefixFlag
}
internal static var storedMutableFlag: UInt32 {
return _SwiftKeyPathComponentHeader_StoredMutableFlag
}
internal static var storedOffsetPayloadMask: UInt32 {
return _SwiftKeyPathComponentHeader_StoredOffsetPayloadMask
}
internal static var outOfLineOffsetPayload: UInt32 {
return _SwiftKeyPathComponentHeader_OutOfLineOffsetPayload
}
internal static var unresolvedFieldOffsetPayload: UInt32 {
return _SwiftKeyPathComponentHeader_UnresolvedFieldOffsetPayload
}
internal static var unresolvedIndirectOffsetPayload: UInt32 {
return _SwiftKeyPathComponentHeader_UnresolvedIndirectOffsetPayload
}
internal static var maximumOffsetPayload: UInt32 {
return _SwiftKeyPathComponentHeader_MaximumOffsetPayload
}
internal var isStoredMutable: Bool {
_internalInvariant(kind == .struct || kind == .class)
return _value & Header.storedMutableFlag != 0
}
internal static var computedMutatingFlag: UInt32 {
return _SwiftKeyPathComponentHeader_ComputedMutatingFlag
}
internal var isComputedMutating: Bool {
_internalInvariant(kind == .computed)
return _value & Header.computedMutatingFlag != 0
}
internal static var computedSettableFlag: UInt32 {
return _SwiftKeyPathComponentHeader_ComputedSettableFlag
}
internal var isComputedSettable: Bool {
_internalInvariant(kind == .computed)
return _value & Header.computedSettableFlag != 0
}
internal static var computedIDByStoredPropertyFlag: UInt32 {
return _SwiftKeyPathComponentHeader_ComputedIDByStoredPropertyFlag
}
internal static var computedIDByVTableOffsetFlag: UInt32 {
return _SwiftKeyPathComponentHeader_ComputedIDByVTableOffsetFlag
}
internal var computedIDKind: KeyPathComputedIDKind {
let storedProperty = _value & Header.computedIDByStoredPropertyFlag != 0
let vtableOffset = _value & Header.computedIDByVTableOffsetFlag != 0
switch (storedProperty, vtableOffset) {
case (true, true):
_internalInvariantFailure("not allowed")
case (true, false):
return .storedPropertyIndex
case (false, true):
return .vtableOffset
case (false, false):
return .pointer
}
}
internal static var computedHasArgumentsFlag: UInt32 {
return _SwiftKeyPathComponentHeader_ComputedHasArgumentsFlag
}
internal var hasComputedArguments: Bool {
_internalInvariant(kind == .computed)
return _value & Header.computedHasArgumentsFlag != 0
}
// If a computed component is instantiated from an external property
// descriptor, and both components carry arguments, we need to carry some
// extra matter to be able to map between the client and external generic
// contexts.
internal static var computedInstantiatedFromExternalWithArgumentsFlag: UInt32 {
return _SwiftKeyPathComponentHeader_ComputedInstantiatedFromExternalWithArgumentsFlag
}
internal var isComputedInstantiatedFromExternalWithArguments: Bool {
get {
_internalInvariant(kind == .computed)
return
_value & Header.computedInstantiatedFromExternalWithArgumentsFlag != 0
}
set {
_internalInvariant(kind == .computed)
_value =
_value & ~Header.computedInstantiatedFromExternalWithArgumentsFlag
| (newValue ? Header.computedInstantiatedFromExternalWithArgumentsFlag
: 0)
}
}
internal static var externalWithArgumentsExtraSize: Int {
return MemoryLayout<Int>.size
}
internal static var computedIDResolutionMask: UInt32 {
return _SwiftKeyPathComponentHeader_ComputedIDResolutionMask
}
internal static var computedIDResolved: UInt32 {
return _SwiftKeyPathComponentHeader_ComputedIDResolved
}
internal static var computedIDUnresolvedIndirectPointer: UInt32 {
return _SwiftKeyPathComponentHeader_ComputedIDUnresolvedIndirectPointer
}
internal static var computedIDUnresolvedFunctionCall: UInt32 {
return _SwiftKeyPathComponentHeader_ComputedIDUnresolvedFunctionCall
}
internal var computedIDResolution: KeyPathComputedIDResolution {
switch payload & Header.computedIDResolutionMask {
case Header.computedIDResolved:
return .resolved
case Header.computedIDUnresolvedIndirectPointer:
return .indirectPointer
case Header.computedIDUnresolvedFunctionCall:
return .functionCall
default:
_internalInvariantFailure("invalid key path resolution")
}
}
internal var _value: UInt32
internal var discriminator: UInt32 {
get {
return (_value & Header.discriminatorMask) >> Header.discriminatorShift
}
set {
let shifted = newValue << Header.discriminatorShift
_internalInvariant(shifted & Header.discriminatorMask == shifted,
"discriminator doesn't fit")
_value = _value & ~Header.discriminatorMask | shifted
}
}
internal var payload: UInt32 {
get {
return _value & Header.payloadMask
}
set {
_internalInvariant(newValue & Header.payloadMask == newValue,
"payload too big")
_value = _value & ~Header.payloadMask | newValue
}
}
internal var storedOffsetPayload: UInt32 {
get {
_internalInvariant(kind == .struct || kind == .class,
"not a stored component")
return _value & Header.storedOffsetPayloadMask
}
set {
_internalInvariant(kind == .struct || kind == .class,
"not a stored component")
_internalInvariant(newValue & Header.storedOffsetPayloadMask == newValue,
"payload too big")
_value = _value & ~Header.storedOffsetPayloadMask | newValue
}
}
internal var endOfReferencePrefix: Bool {
get {
return _value & Header.endOfReferencePrefixFlag != 0
}
set {
if newValue {
_value |= Header.endOfReferencePrefixFlag
} else {
_value &= ~Header.endOfReferencePrefixFlag
}
}
}
internal var kind: KeyPathComponentKind {
switch (discriminator, payload) {
case (Header.externalTag, _):
return .external
case (Header.structTag, _):
return .struct
case (Header.classTag, _):
return .class
case (Header.computedTag, _):
return .computed
case (Header.optionalTag, Header.optionalChainPayload):
return .optionalChain
case (Header.optionalTag, Header.optionalWrapPayload):
return .optionalWrap
case (Header.optionalTag, Header.optionalForcePayload):
return .optionalForce
default:
_internalInvariantFailure("invalid header")
}
}
// The component header is 4 bytes, but may be followed by an aligned
// pointer field for some kinds of component, forcing padding.
internal static var pointerAlignmentSkew: Int {
return MemoryLayout<Int>.size - MemoryLayout<Int32>.size
}
internal var isTrivialPropertyDescriptor: Bool {
return _value ==
_SwiftKeyPathComponentHeader_TrivialPropertyDescriptorMarker
}
/// If this is the header for a component in a key path pattern, return
/// the size of the body of the component.