-
Notifications
You must be signed in to change notification settings - Fork 10.5k
/
Copy pathKeyPath.swift
4460 lines (3975 loc) · 164 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.
/// A type-erased key path, from any root type to any resulting value
/// type.
@_objcRuntimeName(_TtCs11_AnyKeyPath)
@safe
public class AnyKeyPath: _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
}
/// Used to store the offset from the root to the value
/// in the case of a pure struct KeyPath.
/// It's a regular kvcKeyPathStringPtr otherwise.
internal final var _kvcKeyPathStringPtr: UnsafePointer<CChar>?
/*
The following pertains to 32-bit architectures only.
We assume everything is a valid pointer to a potential
_kvcKeyPathStringPtr except for the first 4KB page which is reserved
for the nil pointer. Note that we have to distinguish between a valid
keypath offset of 0, and the nil pointer itself.
We use maximumOffsetOn32BitArchitecture + 1 for this case.
The variable maximumOffsetOn32BitArchitecture is duplicated in the two
functions below since having it as a global would make accesses slower,
given getOffsetFromStorage() gets called on each KeyPath read. Further,
having it as an instance variable in AnyKeyPath would increase the size
of AnyKeyPath by 8 bytes.
TODO: Find a better method of refactoring this variable if possible.
*/
final func assignOffsetToStorage(offset: Int) {
let maximumOffsetOn32BitArchitecture = 4094
guard offset >= 0 else {
return
}
#if _pointerBitWidth(_64)
_kvcKeyPathStringPtr = unsafe UnsafePointer<CChar>(bitPattern: -offset - 1)
#elseif _pointerBitWidth(_32)
if offset <= maximumOffsetOn32BitArchitecture {
_kvcKeyPathStringPtr = UnsafePointer<CChar>(bitPattern: (offset + 1))
} else {
_kvcKeyPathStringPtr = nil
}
#else
// Don't assign anything.
#endif
}
final func getOffsetFromStorage() -> Int? {
let maximumOffsetOn32BitArchitecture = 4094
guard unsafe _kvcKeyPathStringPtr != nil else {
return nil
}
#if _pointerBitWidth(_64)
let offset = (0 &- Int(bitPattern: _kvcKeyPathStringPtr)) &- 1
guard _fastPath(offset >= 0) else {
// This happens to be an actual _kvcKeyPathStringPtr, not an offset, if
// we get here.
return nil
}
return offset
#elseif _pointerBitWidth(_32)
let offset = Int(bitPattern: _kvcKeyPathStringPtr) &- 1
// Pointers above 0x7fffffff will come in as negative numbers which are
// less than maximumOffsetOn32BitArchitecture, be sure to reject them.
if offset >= 0, offset <= maximumOffsetOn32BitArchitecture {
return offset
}
return nil
#else
// Otherwise, we assigned nothing so return nothing.
return nil
#endif
}
// SPI for the Foundation overlay to allow interop with KVC keypath-based
// APIs.
@_unavailableInEmbedded
public var _kvcKeyPathString: String? {
@_semantics("keypath.kvcKeyPathString")
get {
guard self.getOffsetFromStorage() == nil else {
return nil
}
guard let ptr = _kvcKeyPathStringPtr else { return nil }
return unsafe String(validatingCString: ptr)
}
}
// MARK: Implementation details
// Prevent normal initialization. We use tail allocation via
// allocWithTailElems().
@available(*, unavailable)
internal init() {
_internalInvariantFailure("use _create(...)")
}
@usableFromInline
internal class var _rootAndValueType: (root: Any.Type, value: Any.Type) {
_abstract()
}
@_unavailableInEmbedded
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))
unsafe body(UnsafeMutableRawBufferPointer(start: base, count: bytes))
return result
}
@_unavailableInEmbedded
final internal func withBuffer<T>(_ f: (KeyPathBuffer) throws -> T) rethrows -> T {
defer { _fixLifetime(self) }
let base = UnsafeRawPointer(Builtin.projectTailElems(self, Int32.self))
return try unsafe f(KeyPathBuffer(base: base))
}
@usableFromInline // Exposed as public API by MemoryLayout<Root>.offset(of:)
internal var _storedInlineOffset: Int? {
#if !$Embedded
return withBuffer {
var buffer = unsafe $0
// The identity key path is effectively a stored keypath of type Self
// at offset zero
if unsafe buffer.data.isEmpty { return 0 }
var offset = 0
while true {
let (rawComponent, optNextType) = unsafe buffer.next()
switch unsafe rawComponent.header.kind {
case .struct:
unsafe offset += rawComponent._structOrClassOffset
case .class, .computed, .optionalChain, .optionalForce, .optionalWrap, .external:
return .none
}
if optNextType == nil { return .some(offset) }
}
}
#else
// compiler optimizes _storedInlineOffset into a direct offset computation,
// and in embedded Swift we don't allow runtime keypaths, so this fatalError
// is unreachable at runtime
fatalError()
#endif
}
}
@_unavailableInEmbedded
extension AnyKeyPath: Hashable {
/// 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 = unsafe $0
if unsafe buffer.data.isEmpty { return }
while true {
let (component, type) = unsafe buffer.next()
unsafe hasher.combine(component.value)
if let type = type {
unsafe 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 = unsafe $0
return b.withBuffer {
var bBuffer = unsafe $0
// Two equivalent key paths should have the same reference prefix
if unsafe aBuffer.hasReferencePrefix != bBuffer.hasReferencePrefix {
return false
}
// Identity is equal to identity
if unsafe aBuffer.data.isEmpty {
return unsafe bBuffer.data.isEmpty
}
while true {
let (aComponent, aType) = unsafe aBuffer.next()
let (bComponent, bType) = unsafe bBuffer.next()
if unsafe aComponent.header.endOfReferencePrefix
!= bComponent.header.endOfReferencePrefix
|| aComponent.value != bComponent.value
|| aType != bType {
return false
}
if aType == nil {
return true
}
}
}
}
}
}
/// 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.
///
/// The most common way to make an instance of this type
/// is by using a key-path expression like `\SomeClass.someProperty`.
/// For more information,
/// see [Key-Path Expressions][keypath] in *[The Swift Programming Language][tspl]*.
///
/// [keypath]: https://docs.swift.org/swift-book/ReferenceManual/Expressions.html#ID563
/// [tspl]: https://docs.swift.org/swift-book/
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
@_unavailableInEmbedded
internal final func _projectReadOnly(from root: Root) -> Value {
let (rootType, valueType) = Self._rootAndValueType
// One performance improvement is to skip right to Value
// if this keypath traverses through structs only.
if let offset = getOffsetFromStorage() {
return unsafe _withUnprotectedUnsafeBytes(of: root) {
let pointer = unsafe $0.baseAddress._unsafelyUnwrappedUnchecked + offset
return unsafe pointer.assumingMemoryBound(to: Value.self).pointee
}
}
return withBuffer {
var buffer = unsafe $0
if unsafe _slowPath(buffer.data.isEmpty) {
return Builtin.reinterpretCast(root)
}
if unsafe _fastPath(buffer.isSingleComponent) {
var isBreak = false
let (rawComponent, _) = unsafe buffer.next()
return Builtin.emplace {
unsafe rawComponent._projectReadOnly(
root,
to: Value.self,
endingWith: Value.self,
&isBreak,
pointer: UnsafeMutablePointer<Value>($0)
)
}
}
let maxSize = unsafe buffer.maxSize
let roundedMaxSize = 1 &<< (Int.bitWidth &- maxSize.leadingZeroBitCount)
// 16 is the max alignment allowed on practically every platform we deploy
// to.
return unsafe _withUnprotectedUnsafeTemporaryAllocation(
byteCount: roundedMaxSize,
alignment: 16
) {
let currentValueBuffer = unsafe $0
unsafe currentValueBuffer.withMemoryRebound(to: Root.self) {
unsafe $0.initializeElement(at: 0, to: root)
}
var currentType = rootType
while true {
let (rawComponent, optNextType) = unsafe buffer.next()
let newType = optNextType ?? valueType
let isLast = optNextType == nil
var isBreak = false
func projectCurrent<Current>(_: Current.Type) {
func projectNew<New>(_: New.Type) {
let base = unsafe currentValueBuffer.withMemoryRebound(
to: Current.self
) {
unsafe $0.moveElement(from: 0)
}
unsafe currentValueBuffer.withMemoryRebound(to: New.self) {
unsafe rawComponent._projectReadOnly(
base,
to: New.self,
endingWith: Value.self,
&isBreak,
pointer: $0.baseAddress._unsafelyUnwrappedUnchecked
)
}
// If we've broken from the projection, it means we found nil
// while optional chaining.
guard _fastPath(!isBreak) else {
return
}
currentType = newType
if isLast {
_internalInvariant(
New.self == Value.self,
"key path does not terminate in correct type"
)
}
}
_openExistential(newType, do: projectNew(_:))
}
_openExistential(currentType, do: projectCurrent(_:))
if isLast || isBreak {
return unsafe currentValueBuffer.withMemoryRebound(to: Value.self) {
unsafe $0.moveElement(from: 0)
}
}
}
}
}
}
deinit {
#if !$Embedded
withBuffer { unsafe $0.destroy() }
#else
fatalError() // unreachable, keypaths in embedded Swift are compile-time
#endif
}
}
/// 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
@_unavailableInEmbedded
internal func _projectMutableAddress(from base: UnsafePointer<Root>)
-> (pointer: UnsafeMutablePointer<Value>, owner: AnyObject?) {
// One performance improvement is to skip right to Value
// if this keypath traverses through structs only.
// Don't declare "p" above this if-statement; it may slow things down.
if let offset = getOffsetFromStorage()
{
let p = unsafe UnsafeRawPointer(base).advanced(by: offset)
return unsafe (pointer: UnsafeMutablePointer(
mutating: p.assumingMemoryBound(to: Value.self)), owner: nil)
}
var p = unsafe UnsafeRawPointer(base)
var type: Any.Type = Root.self
var keepAlive: AnyObject?
return withBuffer {
var buffer = unsafe $0
unsafe _internalInvariant(!buffer.hasReferencePrefix,
"WritableKeyPath should not have a reference prefix")
if unsafe buffer.data.isEmpty {
return unsafe (
UnsafeMutablePointer<Value>(
mutating: p.assumingMemoryBound(to: Value.self)),
nil)
}
while true {
let (rawComponent, optNextType) = unsafe buffer.next()
let nextType = optNextType ?? Value.self
func project<CurValue>(_: CurValue.Type) {
func project2<NewValue>(_: NewValue.Type) {
unsafe p = unsafe 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 = unsafe p.assumingMemoryBound(to: Value.self)
return unsafe (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 }
@usableFromInline
@_unavailableInEmbedded
internal final func _projectMutableAddress(from origBase: Root)
-> (pointer: UnsafeMutablePointer<Value>, owner: AnyObject?) {
var keepAlive: AnyObject?
let address: UnsafeMutablePointer<Value> = withBuffer {
var buffer = unsafe $0
// Project out the reference prefix.
let maxSize = unsafe buffer.maxSize
let roundedMaxSize = 1 &<< (Int.bitWidth &- maxSize.leadingZeroBitCount)
// 16 is the max alignment allowed on practically every platform we deploy
// to.
let base: Any = unsafe _withUnprotectedUnsafeTemporaryAllocation(
byteCount: roundedMaxSize,
alignment: 16
) {
var currentType: Any.Type = Root.self
let currentValueBuffer = unsafe $0
unsafe currentValueBuffer.withMemoryRebound(to: Root.self) {
unsafe $0.initializeElement(at: 0, to: origBase)
}
while unsafe buffer.hasReferencePrefix {
let (rawComponent, optNextType) = unsafe buffer.next()
_internalInvariant(optNextType != nil,
"reference prefix should not go to end of buffer")
let nextType = optNextType._unsafelyUnwrappedUnchecked
func projectNew<New>(_: New.Type) {
func projectCurrent<Current>(_: Current.Type) {
var isBreak = false
let base = unsafe currentValueBuffer.withMemoryRebound(
to: Current.self
) {
unsafe $0.moveElement(from: 0)
}
unsafe currentValueBuffer.withMemoryRebound(to: New.self) {
unsafe rawComponent._projectReadOnly(
base,
to: New.self,
endingWith: Value.self,
&isBreak,
pointer: $0.baseAddress._unsafelyUnwrappedUnchecked
)
}
guard _fastPath(!isBreak) else {
_preconditionFailure("should not have stopped key path projection")
}
currentType = nextType
}
_openExistential(currentType, do: projectCurrent(_:))
}
_openExistential(nextType, do: projectNew(_:))
}
func projectCurrent<Current>(_: Current.Type) -> Any {
return unsafe currentValueBuffer.withMemoryRebound(to: Current.self) {
unsafe $0.moveElement(from: 0)
}
}
return _openExistential(currentType, do: projectCurrent(_:))
}
// Start formal access to the mutable value, based on the final base
// value.
func formalMutation<MutationRoot>(_ base: MutationRoot)
-> UnsafeMutablePointer<Value> {
var base2 = base
return unsafe withUnsafeBytes(of: &base2) { baseBytes in
var p = unsafe baseBytes.baseAddress.unsafelyUnwrapped
var curType: Any.Type = MutationRoot.self
while true {
let (rawComponent, optNextType) = unsafe buffer.next()
let nextType = optNextType ?? Value.self
func project<CurValue>(_: CurValue.Type) {
func project2<NewValue>(_: NewValue.Type) {
unsafe p = unsafe 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 = unsafe p.assumingMemoryBound(to: Value.self)
return unsafe UnsafeMutablePointer(mutating: typedPointer)
}
}
return _openExistential(base, do: unsafe formalMutation(_:))
}
return unsafe (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)
}
}
@_unavailableInEmbedded
@unsafe
internal struct ComputedAccessorsPtr {
#if INTERNAL_CHECKS_ENABLED
internal let header: RawKeyPathComponent.Header
#endif
internal let _value: UnsafeRawPointer
init(header: RawKeyPathComponent.Header, value: UnsafeRawPointer) {
#if INTERNAL_CHECKS_ENABLED
unsafe self.header = unsafe header
#endif
unsafe self._value = unsafe value
}
@_transparent
static var getterPtrAuthKey: UInt64 {
return UInt64(_SwiftKeyPath_ptrauth_Getter)
}
@_transparent
static var nonmutatingSetterPtrAuthKey: UInt64 {
return UInt64(_SwiftKeyPath_ptrauth_NonmutatingSetter)
}
@_transparent
static var mutatingSetterPtrAuthKey: UInt64 {
return UInt64(_SwiftKeyPath_ptrauth_MutatingSetter)
}
internal typealias Getter<CurValue, NewValue> = @convention(thin)
(CurValue, UnsafeRawPointer, Int) -> NewValue
internal typealias NonmutatingSetter<CurValue, NewValue> = @convention(thin)
(NewValue, CurValue, UnsafeRawPointer, Int) -> ()
internal typealias MutatingSetter<CurValue, NewValue> = @convention(thin)
(NewValue, inout CurValue, UnsafeRawPointer, Int) -> ()
internal var getterPtr: UnsafeRawPointer {
#if INTERNAL_CHECKS_ENABLED
unsafe _internalInvariant(header.kind == .computed,
"not a computed property")
#endif
return unsafe _value
}
internal var setterPtr: UnsafeRawPointer {
#if INTERNAL_CHECKS_ENABLED
unsafe _internalInvariant(header.isComputedSettable,
"not a settable property")
#endif
return unsafe _value + MemoryLayout<Int>.size
}
internal func getter<CurValue, NewValue>()
-> Getter<CurValue, NewValue> {
return unsafe getterPtr._loadAddressDiscriminatedFunctionPointer(
as: Getter.self,
discriminator: ComputedAccessorsPtr.getterPtrAuthKey)
}
internal func nonmutatingSetter<CurValue, NewValue>()
-> NonmutatingSetter<CurValue, NewValue> {
#if INTERNAL_CHECKS_ENABLED
unsafe _internalInvariant(header.isComputedSettable && !header.isComputedMutating,
"not a nonmutating settable property")
#endif
return unsafe setterPtr._loadAddressDiscriminatedFunctionPointer(
as: NonmutatingSetter.self,
discriminator: ComputedAccessorsPtr.nonmutatingSetterPtrAuthKey)
}
internal func mutatingSetter<CurValue, NewValue>()
-> MutatingSetter<CurValue, NewValue> {
#if INTERNAL_CHECKS_ENABLED
unsafe _internalInvariant(header.isComputedSettable && header.isComputedMutating,
"not a mutating settable property")
#endif
return unsafe setterPtr._loadAddressDiscriminatedFunctionPointer(
as: MutatingSetter.self,
discriminator: ComputedAccessorsPtr.mutatingSetterPtrAuthKey)
}
}
@_unavailableInEmbedded
@unsafe
internal struct ComputedArgumentWitnessesPtr {
internal let _value: UnsafeRawPointer
init(_ value: UnsafeRawPointer) {
unsafe self._value = unsafe value
}
@_transparent
static var destroyPtrAuthKey: UInt64 {
return UInt64(_SwiftKeyPath_ptrauth_ArgumentDestroy)
}
@_transparent
static var copyPtrAuthKey: UInt64 {
return UInt64(_SwiftKeyPath_ptrauth_ArgumentCopy)
}
@_transparent
static var equalsPtrAuthKey: UInt64 {
return UInt64(_SwiftKeyPath_ptrauth_ArgumentEquals)
}
@_transparent
static var hashPtrAuthKey: UInt64 {
return UInt64(_SwiftKeyPath_ptrauth_ArgumentHash)
}
@_transparent
static var layoutPtrAuthKey: UInt64 {
return UInt64(_SwiftKeyPath_ptrauth_ArgumentLayout)
}
@_transparent
static var initPtrAuthKey: UInt64 {
return UInt64(_SwiftKeyPath_ptrauth_ArgumentInit)
}
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
// The witnesses are stored as address-discriminated authenticated
// pointers.
internal var destroy: Destroy? {
return unsafe _value._loadAddressDiscriminatedFunctionPointer(
as: Optional<Destroy>.self,
discriminator: ComputedArgumentWitnessesPtr.destroyPtrAuthKey)
}
internal var copy: Copy {
return unsafe _value._loadAddressDiscriminatedFunctionPointer(
fromByteOffset: MemoryLayout<UnsafeRawPointer>.size,
as: Copy.self,
discriminator: ComputedArgumentWitnessesPtr.copyPtrAuthKey)
}
internal var equals: Equals {
return unsafe _value._loadAddressDiscriminatedFunctionPointer(
fromByteOffset: 2*MemoryLayout<UnsafeRawPointer>.size,
as: Equals.self,
discriminator: ComputedArgumentWitnessesPtr.equalsPtrAuthKey)
}
internal var hash: Hash {
return unsafe _value._loadAddressDiscriminatedFunctionPointer(
fromByteOffset: 3*MemoryLayout<UnsafeRawPointer>.size,
as: Hash.self,
discriminator: ComputedArgumentWitnessesPtr.hashPtrAuthKey)
}
}
@_unavailableInEmbedded
@unsafe
internal enum KeyPathComponent {
@unsafe
internal struct ArgumentRef {
internal var data: UnsafeRawBufferPointer
internal var witnesses: ComputedArgumentWitnessesPtr
internal var witnessSizeAdjustment: Int
internal init(
data: UnsafeRawBufferPointer,
witnesses: ComputedArgumentWitnessesPtr,
witnessSizeAdjustment: Int
) {
unsafe self.data = unsafe data
unsafe self.witnesses = unsafe witnesses
unsafe self.witnessSizeAdjustment = witnessSizeAdjustment
}
}
/// 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,
accessors: ComputedAccessorsPtr,
argument: ArgumentRef?)
/// The keypath projects using a getter/setter pair. The setter can mutate
/// the base value in-place.
case mutatingGetSet(id: ComputedPropertyID,
accessors: ComputedAccessorsPtr,
argument: ArgumentRef?)
/// The keypath projects using a getter/setter pair that does not mutate its
/// base.
case nonmutatingGetSet(id: ComputedPropertyID,
accessors: ComputedAccessorsPtr,
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
}
@_unavailableInEmbedded
extension KeyPathComponent: @unsafe Hashable {
internal static func ==(a: KeyPathComponent, b: KeyPathComponent) -> Bool {
switch unsafe (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, accessors: _, argument: let argument1),
.get(id: let id2, accessors: _, argument: let argument2)),
(.mutatingGetSet(id: let id1, accessors: _, argument: let argument1),
.mutatingGetSet(id: let id2, accessors: _, argument: let argument2)),
(.nonmutatingGetSet(id: let id1, accessors: _, argument: let argument1),
.nonmutatingGetSet(id: let id2, accessors: _, argument: let argument2)):
if id1 != id2 {
return false
}
if let arg1 = unsafe argument1, let arg2 = unsafe argument2 {
return unsafe arg1.witnesses.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 = unsafe argument {
let hash = unsafe argument.witnesses.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 unsafe 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, accessors: _, argument: let argument):
hasher.combine(5)
hasher.combine(id)
unsafe appendHashFromArgument(argument)
case .mutatingGetSet(id: let id, accessors: _, argument: let argument):
hasher.combine(6)
hasher.combine(id)
unsafe appendHashFromArgument(argument)
case .nonmutatingGetSet(id: let id, accessors: _, argument: let argument):
hasher.combine(7)
hasher.combine(id)
unsafe 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 exclusive 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 {