From bfbb0f605e6b38113daaa431714fe06c075a6445 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Sun, 1 Sep 2024 20:40:04 -0700 Subject: [PATCH] =?UTF-8?q?[Future]=20Bovine=20=E2=86=92=20Shared?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Sources/Future/CMakeLists.txt | 2 +- Sources/Future/Containers/Bovine.swift | 128 -------------- Sources/Future/Containers/NewArray.swift | 8 +- Sources/Future/Containers/Shared.swift | 186 ++++++++++++++++++++ Sources/Future/LifetimeOverride.swift | 4 +- Xcode/Collections.xcodeproj/project.pbxproj | 8 +- 6 files changed, 198 insertions(+), 138 deletions(-) delete mode 100644 Sources/Future/Containers/Bovine.swift create mode 100644 Sources/Future/Containers/Shared.swift diff --git a/Sources/Future/CMakeLists.txt b/Sources/Future/CMakeLists.txt index 4767db1d..6ade7dbd 100644 --- a/Sources/Future/CMakeLists.txt +++ b/Sources/Future/CMakeLists.txt @@ -15,7 +15,7 @@ add_library(Future "LifetimeOverride.swift" "RawSpan.swift" "Span.swift" - "Containers/Bovine.swift" + "Containers/Shared.swift" "Containers/Container.swift" "Containers/DynamicArray.swift" "Containers/NewArray.swift" diff --git a/Sources/Future/Containers/Bovine.swift b/Sources/Future/Containers/Bovine.swift deleted file mode 100644 index fdc582c5..00000000 --- a/Sources/Future/Containers/Bovine.swift +++ /dev/null @@ -1,128 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift Collections open source project -// -// Copyright (c) 2024 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 -// -//===----------------------------------------------------------------------===// - -import Builtin // For Bovine.isIdentical - -/// A utility adapter that wraps a noncopyable storage type in a copy-on-write -/// struct, enabling efficient implementation of value semantics. The type -/// allows safe borrowing and mutating access to its storage, with minimal fuss. -/// -/// Like `ManagedBufferPointer`, this type is intended to be used within the -/// internal implementation of public types. Instances of it aren't designed -/// to be exposed as public. -/// -/// (The placeholder name `Bovine` is hinting at the common abbreviation of the -/// copy-on-write optimization.) -@frozen -public struct Bovine { - @usableFromInline - internal var _box: _Box - - @inlinable - public init(_ storage: consuming Storage) { - self._box = _Box(storage) - } -} - -extension Bovine: @unchecked Sendable where Storage: Sendable & ~Copyable {} - -#if true // FIXME: Silent error on class definition nested in noncopyable struct -@usableFromInline -internal final class _BovineBox { - @exclusivity(unchecked) - @usableFromInline - internal var storage: Storage - - @inlinable - internal init(_ storage: consuming Storage) { - self.storage = storage - } -} - -extension Bovine where Storage: ~Copyable { - @usableFromInline - internal typealias _Box = _BovineBox -} -#else -extension Bovine where Storage: ~Copyable { - @usableFromInline - internal final class _Box { - @exclusivity(unchecked) - @usableFromInline - internal var storage: Storage - - @inlinable - internal init(_ storage: consuming Storage) { - self.storage = storage - } - } -} -#endif - -extension Bovine where Storage: ~Copyable { - @inlinable - @inline(__always) - public mutating func isUnique() -> Bool { - isKnownUniquelyReferenced(&_box) - } - - @inlinable - public mutating func ensureUnique( - cloner: (borrowing Storage) -> Storage - ) { - if isUnique() { return } - _box = _Box(cloner(_box.storage)) - } -} - -extension Bovine where Storage: ~Copyable { - @inlinable - @inline(__always) - public var value: Storage { - _read { - yield _box.storage - } - _modify { - precondition(isUnique()) - yield &_box.storage - } - } - - @inlinable - @inline(__always) - public func read( - _ body: (borrowing Storage) throws(E) -> R - ) throws(E) -> R { - try body(_box.storage) - } - - @inlinable - @inline(__always) - public mutating func update( - _ body: (inout Storage) throws(E) -> R - ) throws(E) -> R { - precondition(isUnique()) - return try body(&_box.storage) - } -} - -extension Bovine where Storage: ~Copyable { - @inlinable - public func isIdentical(to other: Self) -> Bool { - if #available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *) { - return self._box === other._box - } else { - let a = Builtin.bridgeToRawPointer(self._box) - let b = Builtin.bridgeToRawPointer(other._box) - return Bool(Builtin.cmp_eq_RawPointer(a, b)) - } - } -} diff --git a/Sources/Future/Containers/NewArray.swift b/Sources/Future/Containers/NewArray.swift index 26a62be3..4e89aeb5 100644 --- a/Sources/Future/Containers/NewArray.swift +++ b/Sources/Future/Containers/NewArray.swift @@ -13,11 +13,11 @@ @frozen public struct NewArray { @usableFromInline - internal var _storage: Bovine> + internal var _storage: Shared> @inlinable public init(minimumCapacity: Int) { - self._storage = Bovine(RigidArray(capacity: minimumCapacity)) + self._storage = Shared(RigidArray(capacity: minimumCapacity)) } } @@ -34,9 +34,9 @@ extension NewArray { internal mutating func _ensureUnique(minimumCapacity: Int) { if !_storage.isUnique() { let c = Swift.max(count, minimumCapacity) - _storage = Bovine(_storage.read { $0._copy(capacity: c) }) + _storage = Shared(_storage.read { $0._copy(capacity: c) }) } else if minimumCapacity > self.capacity { - _storage = Bovine(_storage.update { $0._move(capacity: minimumCapacity) }) + _storage = Shared(_storage.update { $0._move(capacity: minimumCapacity) }) } } diff --git a/Sources/Future/Containers/Shared.swift b/Sources/Future/Containers/Shared.swift new file mode 100644 index 00000000..1df697b5 --- /dev/null +++ b/Sources/Future/Containers/Shared.swift @@ -0,0 +1,186 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2024 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 +// +//===----------------------------------------------------------------------===// + +import Builtin // For Shared.isIdentical + +/// A utility adapter that wraps a noncopyable storage type in a copy-on-write +/// struct, enabling efficient implementation of value semantics. The type +/// allows safe borrowing and mutating access to its storage, with minimal fuss. +/// +/// Like `ManagedBufferPointer`, this type is intended to be used within the +/// internal implementation of public types. Instances of it aren't designed +/// to be exposed as public. +@frozen +public struct Shared { + @usableFromInline + internal var _box: _Box + + @inlinable + public init(_ storage: consuming Storage) { + self._box = _Box(storage) + } +} + +extension Shared: @unchecked Sendable where Storage: Sendable & ~Copyable {} + +#if true // FIXME: Silent error on class definition nested in noncopyable struct +@usableFromInline +internal final class _SharedBox { + @exclusivity(unchecked) + @usableFromInline + internal var storage: Storage + + @inlinable + internal init(_ storage: consuming Storage) { + self.storage = storage + } +} + +extension Shared where Storage: ~Copyable { + @usableFromInline + internal typealias _Box = _SharedBox +} +#else +extension Shared where Storage: ~Copyable { + @usableFromInline + internal final class _Box { + @exclusivity(unchecked) + @usableFromInline + internal var storage: Storage + + @inlinable + internal init(_ storage: consuming Storage) { + self.storage = storage + } + } +} +#endif + +extension Shared where Storage: ~Copyable { + @inlinable + @inline(__always) + public mutating func isUnique() -> Bool { + isKnownUniquelyReferenced(&_box) + } + + @inlinable + public mutating func ensureUnique( + cloner: (borrowing Storage) -> Storage + ) { + if isUnique() { return } + _box = _Box(cloner(_box.storage)) + } +} + +import struct SwiftShims.HeapObject + +extension Shared where Storage: ~Copyable { + // FIXME: Can we avoid hacks like this? If not, perhaps `_Box.storage` should be tail-allocated. + @inlinable + internal var _address: UnsafePointer { + // Adapted from _getUnsafePointerToStoredProperties + let p = ( + UnsafeRawPointer(Builtin.bridgeToRawPointer(_box)) + + MemoryLayout.size) + return p.alignedUp(for: Storage.self).assumingMemoryBound(to: Storage.self) + } + + @inlinable + internal var _mutableAddress: UnsafeMutablePointer { + // Adapted from _getUnsafePointerToStoredProperties + let p = ( + UnsafeMutableRawPointer(Builtin.bridgeToRawPointer(_box)) + + MemoryLayout.size) + return p.alignedUp(for: Storage.self).assumingMemoryBound(to: Storage.self) + } +} + +extension Shared where Storage: ~Copyable { + @inlinable + @inline(__always) + public var value: /*FIXME: dependsOn(self)*/ Storage { + // FIXME: This implements the wrong shape. + // FIXME: Semantically it yields a borrow scoped to an access of this `value` variable, + // FIXME: not the much wider borrow of `self`, which we'd actually want. + _read { + yield _box.storage + } + _modify { + precondition(isUnique()) + yield &_box.storage + } + } + + // FIXME: This builds, but attempts to use it don't: they fail with an unexpected exclusivity violation. + @inlinable + public subscript() -> dependsOn(self) Storage { + //@_transparent + unsafeAddress { + _address + } + + //@_transparent + unsafeMutableAddress { + precondition(isUnique()) + return _mutableAddress + } + } + + @inlinable + @inline(__always) + public func read( + _ body: (borrowing Storage) throws(E) -> R + ) throws(E) -> R { + // FIXME: This also implements the wrong shape. + // FIXME: The borrow of `Storage` isn't tied to `self` at all, and + // FIXME: it obviously cannot legally escape the `read` call. + try body(_box.storage) + } + + @inlinable + @inline(__always) + public mutating func update( + _ body: (inout Storage) throws(E) -> R + ) throws(E) -> R { + precondition(isUnique()) + return try body(&_box.storage) + } +} + +#if false // FIXME: Use it or lose it +extension Shared where Storage: ~Copyable { + // This is the actual shape we want. There is currently no way to express it. + @inlinable + public borrowing func read() -> dependsOn(self) Borrow { + // This is gloriously (and very explicitly) unsafe, as it should be. + // `Shared` is carefully constructed to guarantee that + // lifetime(self) == lifetime(_box.storage); but we have not + // (cannot) explain this to the compiler. + Borrow(unsafeAddress: _address, owner: self) + } +} +#endif + +extension Shared where Storage: ~Copyable { + @inlinable + public func isIdentical(to other: Self) -> Bool { + if #available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *) { + return self._box === other._box + } else { + // To call the standard `===`, we need to do `_SharedBox` -> AnyObject conversions + // that are only supported in the Swift 6+ runtime. + let a = Builtin.bridgeToRawPointer(self._box) + let b = Builtin.bridgeToRawPointer(other._box) + return Bool(Builtin.cmp_eq_RawPointer(a, b)) + } + } +} + diff --git a/Sources/Future/LifetimeOverride.swift b/Sources/Future/LifetimeOverride.swift index e7b8d8da..4a19ca73 100644 --- a/Sources/Future/LifetimeOverride.swift +++ b/Sources/Future/LifetimeOverride.swift @@ -13,8 +13,10 @@ import Builtin @_unsafeNonescapableResult +@inlinable @inline(__always) public func unsafelyOverrideLifetime< - T: ~Copyable & ~Escapable, U: ~Copyable & ~Escapable + T: ~Copyable & ~Escapable, + U: ~Copyable & ~Escapable >( of dependent: consuming T, to source: borrowing U diff --git a/Xcode/Collections.xcodeproj/project.pbxproj b/Xcode/Collections.xcodeproj/project.pbxproj index 6b03b415..cdb159e1 100644 --- a/Xcode/Collections.xcodeproj/project.pbxproj +++ b/Xcode/Collections.xcodeproj/project.pbxproj @@ -9,7 +9,7 @@ /* Begin PBXBuildFile section */ 7D380E052C6ABF6800AD8F58 /* NewArray.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D380E042C6ABF6000AD8F58 /* NewArray.swift */; }; 7D380E072C6BFB9B00AD8F58 /* LifetimeOverride.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D380E062C6BFB9500AD8F58 /* LifetimeOverride.swift */; }; - 7D380E0D2C6D565300AD8F58 /* Bovine.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D380E0C2C6D565000AD8F58 /* Bovine.swift */; }; + 7D380E0D2C6D565300AD8F58 /* Shared.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D380E0C2C6D565000AD8F58 /* Shared.swift */; }; 7D9B859729E4F74400B291CD /* BitArray+Shifts.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D9B859129E4F74400B291CD /* BitArray+Shifts.swift */; }; 7D9B859829E4F74400B291CD /* BitArray+Descriptions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D9B859229E4F74400B291CD /* BitArray+Descriptions.swift */; }; 7D9B859929E4F74400B291CD /* BitArray+LosslessStringConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D9B859329E4F74400B291CD /* BitArray+LosslessStringConvertible.swift */; }; @@ -442,7 +442,7 @@ /* Begin PBXFileReference section */ 7D380E042C6ABF6000AD8F58 /* NewArray.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NewArray.swift; sourceTree = ""; }; 7D380E062C6BFB9500AD8F58 /* LifetimeOverride.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LifetimeOverride.swift; sourceTree = ""; }; - 7D380E0C2C6D565000AD8F58 /* Bovine.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Bovine.swift; sourceTree = ""; }; + 7D380E0C2C6D565000AD8F58 /* Shared.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Shared.swift; sourceTree = ""; }; 7D5A64D229CCE8CC00CB2595 /* README.md */ = {isa = PBXFileReference; lastKnownFileType = net.daringfireball.markdown; path = README.md; sourceTree = ""; }; 7D5A64D329CCEE9A00CB2595 /* README.md */ = {isa = PBXFileReference; lastKnownFileType = net.daringfireball.markdown; path = README.md; sourceTree = ""; }; 7D5A64D429CCEF1500CB2595 /* generate-sources.sh */ = {isa = PBXFileReference; lastKnownFileType = text.script.sh; path = "generate-sources.sh"; sourceTree = ""; }; @@ -1803,7 +1803,7 @@ isa = PBXGroup; children = ( 7DEBEC182C5AE43C00A1BF15 /* Container.swift */, - 7D380E0C2C6D565000AD8F58 /* Bovine.swift */, + 7D380E0C2C6D565000AD8F58 /* Shared.swift */, 7DEBEC192C5AE43C00A1BF15 /* DynamicArray.swift */, 7DEBEC1A2C5AE43C00A1BF15 /* RigidArray.swift */, 7D380E042C6ABF6000AD8F58 /* NewArray.swift */, @@ -2171,7 +2171,7 @@ 7DE9207A29CA70F4004483EB /* BigString+UTF8View.swift in Sources */, 7DE9201329CA70F3004483EB /* OrderedDictionary+CustomReflectable.swift in Sources */, 7DE9201C29CA70F3004483EB /* OrderedDictionary+Partial MutableCollection.swift in Sources */, - 7D380E0D2C6D565300AD8F58 /* Bovine.swift in Sources */, + 7D380E0D2C6D565300AD8F58 /* Shared.swift in Sources */, 7DE9202729CA70F3004483EB /* OrderedSet+Insertions.swift in Sources */, 7DE9205B29CA70F3004483EB /* Deque+ExpressibleByArrayLiteral.swift in Sources */, 7DE9208729CA70F4004483EB /* BigString+Sequence.swift in Sources */,