Reviews are an important part of the Swift evolution process. All review feedback should be either on this forum thread or, if you would like to keep your feedback private, directly to me as the review manager by DM. When contacting the review manager directly, please put "SE-0556" in the subject line.
Trying it out
We have produced the following toolchains to enable reviewers to try out the feature:
The goal of the review process is to improve the proposal under review through constructive criticism and, eventually, determine the direction of Swift. When writing your review, here are some questions you might want to answer in your review:
What is your evaluation of the proposal?
Is the problem being addressed significant enough to warrant a change to Swift?
Does this proposal fit well with the feel and direction of Swift?
If you have used other languages or libraries with a similar feature, how do you feel that this proposal compares to those?
How much effort did you put into your review? A glance, a quick reading, or an in-depth study?
One of the important use cases for Cell is C++ interop, and generally speaking, sharing mutable data. I think it does that well.
On the other hand, Cell and MutableCell are no longer the tools to use to share FullyInhabited values on multiple threads, and that was one of the things I (and several other people who cannot represent their interests here) was the most looking forward to. This is not necessarily an argument against Cell if there are other good reasons to have it, but I am very much looking forward to that functionality.
I don't really agree that Volatile goes in Synchronization because it's only the right tool for synchronization in extremely specific circumstances (running a safe-ish subset of operations on memory that another core is concurrently modifying without using synchronization primitives), and its only other use (making sure you see the latest value of a variable that a signal handler can change) is a single-threaded use case.
In practical terms, that is a single-threaded use case. But conceptually, your code has to synchronize with another thread of execution that can run at any time (even if the “OS” managing the thread is the CPU hardware itself).
A slight tangent from the overall point that @fclout is making here, but I find it interesting to observe that, as proposed, Cell and ConstCell deliberately departs from our Foo/MutableFoo convention.
Granted that 'cell' has precedent as a term-of-art, but for a type that is deliberately optimized for an advanced use case (interop) and exempts itself from a core part of Swift's native ownership model, is it wise or even necessary to be naming it as succinctly as, say, Intand depart from our usual practice of indicating mutability?
The relevance of it being "practically" single-threaded is that Volatile is not sufficient for multi-threaded code except in the narrowest of circumstances.
GitHub's down right now, so please forgive the question if it's redundant. Is the address of an instance of Cell<T> guaranteed to be fixed? It effectively is for the current _Cell (or, fixed so long as anybody can observe it) but I am unsure if this is guaranteed for the proposed API.
I ask because one of the things Swift Testing needs to do is look up Mach-O/ELF section boundaries statically based on "magic" symbols, and we're currently doing so with a potentially fragile combination of @_silgen_name, file-scoped nonisolated(unsafe) var, and ~Copyable. If Cell guarantees its address is fixed, we can start using it instead and reduce the fragility of said code.
TLDR; stable address while being borrowed or mutated, but otherwise can still be moved like any other noncopyable value. That being said, using it in places where noncopyable values can't be moved effectively gives it a stable address always (like as a global or class ivar), but even those can be exchanged with other cell values if exclusive access is available (exchange(&someGlobalCell, with: newCellValue)).
This is one of those features that most devs would never use, but I'd be very happy that it's there for the extra-smart folks to make interoperability with C and C++ libraries safer.
@_silgen_name("...") private let _sectionBegin: Cell<...>
withUnsafePointer(to: _sectionBegin) { sb in
...
}
sb ought to be stable (and equal to the original compiler-emitted address), since the compiler must assume it is concurrently accessible, right? Or could it still potentially give me the address of a temporary copy because it's a let?
(Apologies if I'm derailing! I just really want to use Cell!)
I agree with this point. I don't think changing the names around would affect correctness. So I'd prefer consistency with the rest of Swift if possible.
Are we ruling out a RefCell like type for the time being? It isn't mentioned in future directions. The only way to use the proposed type to add interior mutability to a non-Copyable type is set and replace, but there are legitimately cases where you'd like to check exclusivity at runtime to upgrade to a mutable access from an immutable one and mutate directly... Such a type needs another cell to store the count of borrows, so it would be a new type, built from two of this type.
ConstCell being Sendable but only for FullyInhabited makes me uncomfortable although I can't find a safety issue with it. Either this type shouldn't conform to Sendable (since the underlying data will change) or it shouldn't demand FullyInhabited (since from Swift perspective it won't write and thus won't tear), I think it might surprise people... The motivation in the proposal for this requirement seems like its from the old Cell conformance. Or is the inhabited requirement about Swift readers not observing tearing? If so, really suggests we ought not have this Sendable conformance at all, we can add it later when we understand the uses better but we cannot claw it back.
I'm not arguing that Cell doesn't fill some need. I'm just pointing out that in Swift it's not "the interior mutability type" because we have a different language than Rust.
The link above about reasons to use Cell in Rust gives as the sole concrete example of using Cell itself the following: "Rc<T> maintains its reference counts within a Cell<T>."
Whatever its own merits in Swift, I would say that this particular callout to Rust works against the criterion we're asked to evaluate: "Does this proposal fit well with the feel and direction of Swift?"
We are ignoring OnceCell for caching within non mutable methods? I might be in the minority but I see classes as an Objective-C interop feature, and not the happiest path for using Swift. If you want to have dynamic exclusivity checking for interior mutability of a type with lifetime dependencies, you cannot do that with a class afaik.
This example implies that merely assigning a Volatile value performs a volatile read and write, even if the Volatile.write and Volatile.read methods are not used. Admittedly, I find that weird, because as far as I can tell, no other type's assignment, copy, or move operation has observable side effects.
It has some weird implications; for example, if we have a MutableSpan<Volatile<T>>, and we use a bulk update operation such as MutableSpan.updateElements, it becomes significant how many times, and in what order, the method's implementation writes and reads each individual element, unlike with any non-Volatile type.
Edited to add: It could also prevent some optimizations; in unspecialized generic code, it would no longer be possible to optimize away copy and move operations, in case the type being copied or moved is Volatile.
Also, normally, I would think writing to a Cell implies that we temporarily have exclusive access to the inner value in order to write to it. But it's unclear what that means when Volatile is involved, because Volatile is used to interact with an external system that observes and possibly mutates the volatile memory, which seems contrary to what exclusivity normally implies. If it isn't undefined behavior to form an aliasing mutating access to a Volatile value, then that implies Volatile has semantics similar to UnsafePinned in Rust. UnsafePinned in Rust is still not finalized yet, and I think the Rust community might still be grappling with some unresolved questions around that feature. Presumably, Cell does not have similar semantics, in that forming an aliasing mutating access to a Cell still causes undefined behavior, similar to how aliasing a &mut UnsafeCell<T> in Rust is still unsafe.
A related question is, would it be possible for Volatile to conform to BitwiseCopyable?
If I understand correctly, unlike in Java, where a data race can cause tearing but can't cause undefined behavior, or Go, where a data race can cause tearing but can only cause undefined behavior if pointers are involved, in C and presumably also in Swift, a data race always causes undefined behavior, which tearing is merely a possible symptom of. If so, then the FullyInhabited requirement doesn't actually improve safety; it is still unsound for ConstCell to ever conform to Sendable, because reading from a ConstCell while C code is writing to it from another thread causes a data race, even if the inner value is FullyInhabited.
I think the semantics of Span.unsafeCells() should be clarified. Presumably, a Span<T> guarantees that the memory it points to is never mutated during its lifetime, even if, within its lifetime, it is used to derive a Span<Cell<T>>. So the safety requirement of Span.unsafeCells() is that the returned Span<Cell<T>> should never have its elements mutated, even though the type system allows it, and even if the Span was itself derived from a MutableSpan. This is more restrictive than what C programmers might expect, because in C, it is okay to cast a mutable pointer to a const pointer, then cast that const pointer back to a mutable pointer, then write through that derived mutable pointer.
A RefCell-like type wouldn't necessarily need another cell to store the count of borrows inline. Another approach is to have a thread-local or task-local data structure, called an "access set", that keeps track of all active borrows; the access set would be checked and updated whenever a new borrow is started. As far as I know, the latter approach is used in the dynamic exclusivity checking of class stored properties. Apparently, this approach currently has the unfortunate downside that it is unsound for actor-isolated (instead of task-isolated) variables to participate in the checking (SE-0517: UniqueBox - #102 by John_McCall).
However, as far as I know, this approach does have the upside that dynamic exclusivity checking does not have any runtime impact (namely, it does not take up memory) unless it is actually used. So, it might be possible for Cell to use this approach to have runtime exclusivity checking, while still being zero-cost if the runtime exclusivity checking is not used. What's stopping Cell from having runtime exclusivity checking, though, is that it is possible for C code to read or write the inner value without updating the access set.
But, in my opinion, it would be unfortunate for the "default" interior mutability type to lose a useful feature just because of C interoperability. Perhaps a Cell-like type with runtime exclusivity checking could be "default" for pure Swift code, and a version without runtime exclusivity checking would be used only for C interoperability?
In my opinion, there is a fundamental difference between Cell.unsafeBorrow and withUnsafeBufferPointer on Span and other types. Unlike Cell.unsafeBorrow, if withUnsafeBufferPointer and similar APIs are used correctly, then existing safe operations do not become unsafe.[1]
Array.withUnsafeMutableBufferPointer does not make existing operations on the array unsafe, because the compiler knows that the array is being mutated for the duration of the call. Array.withUnsafeBufferPointer does not make existing operations on the array unsafe, because the elements are not supposed to be mutated through the buffer pointer. Range.init(uncheckedBounds:) does not make existing operations on the range unsafe if it is used correctly, that is, if the given lower bound is not greater than the given upper bound.
One could argue that the non-usage of otherwise-safe Cell APIs is just part of the contract of Cell.unsafeBorrow—part of what it means to "use it correctly"—but I think that would make the contract of Cell.unsafeBorrow non-local and more difficult to check than the contracts of other unsafe APIs like Range.init(uncheckedBounds:). It could require checking all code that is transitively called during the duration of the borrow, even if such code otherwise appears safe.
To put it another way, Cell.unsafeBorrow would become the first unsafe API whose contract depends on which safe APIs are used after the fact.