I think embedded Swift is a bit of a red herring. Another good reason to use typed throws in a protocol is that type substitution with Never is the most expressive way we have for the protocol to allow for both throwing and nonthrowing implementations.
I don't think there's anything special regarding Error vs. any Error here. It's the same as any arbitrary P vs. any P and whether the upcoming feature ExistentialAny is enabled. Some people just prefer to write the explicit any.
That seems to be in tension with @xwu’s comment above:
…unless the guidelines are really speaking of throws(Error) rather than “untyped throws.”
For what it’s worth, I disagree with the subsequent opinion:
I think Embedded Swift is acting as a forcing function for the overall Swift language to confront the practical realities of living up to its stated mission as a universal systems language. Until now, Swift’s design ethos has been molded in the context of apps with access to effectively infinite VRAM, atomic integers, and tolerably fast allocators. Embedded Swift challenges the implicit assumptions that this environment may have silently influenced many language decisions.
They're in tension because I'm pushing back against that—irrespective of other guidelines, using an error associated type is the way we have for a protocol to encompass nonthrowing and throwing implementations, and that's the reason this protocol uses one. As others noted, embedded Swift does support untyped throws now, and so we can apply the usual guidelines in other situations to decide whether an API should adopt it.
I guess I’m suggesting resolving the tension a slightly different way: consider all throws to be typed throws and reformulate the guidance around whether the call site uses any Error. Consider untyped throws a syntactic shortcut for throws(any Error). This influences the design of protocol requirements toward carrying a generic or associated Failure type by default.
I guess I’m suggesting resolving the tension a slightly different way: consider all
throwsto be typedthrowsand reformulate the guidance around whether the call site usesany Error. Consider untyped throws a syntactic shortcut forthrows(any Error). This influences the design of protocol requirements toward carrying a generic or associatedFailuretype by default.
Sure, but my question was why we would want to do that: @Joe_Groff's point that it gives us a way to enable generic programming that can distinguish throwing and non-throwing with a single protocol is a good point. I found the Embedded argument not so convincing, so it's good that we have an independent other rationale.
Thanks for your feedback, @FranzBusch! I've updated the proposal to fix that missing throws(Failure), and added a paragraph about expected iterator behavior, copied here:
As with
Sequence, once an iterator returns an emptySpan, every subsequent call tonextSpan()must return an emptySpanas well. An iterator's behavior after throwing an error is undefined: some iterators may treat that as the end of the sequence, some may continue to throw the same error or a different error, and some may resume iteration on the next call. Generic code should therefore not assume any particular behavior, with a recommendation that the error be propagated to the caller.
In addition, here is the remainder of the proposal sections that didn't fit in the original post:
Source compatibility
This proposal introduces the new protocols Iterable and IterableIteratorProtocol, as well as additional supporting types. Existing conformers to Sequence can also implement Iterable by simply declaring their conformance. This is entirely source compatible.
ABI compatibility
This proposal adds two new protocols, the SpanIterator and IterableIteratorAdapter types, and conformances for the span and InlineArray types to the standard library ABI.
Future directions
Other forms of iteration
While this proposal focuses on borrowing iteration, there are multiple other kinds of iteration that are equally important. Future proposals may take up alternative designs for the following kinds of iteration:
- Consuming iteration: A container may want to provide consuming iteration of its elements. For example, a container of noncopyable elements would need to be consumed when appended to a different container.
- "Draining" iteration: Similar to consuming iteration, but preserving the existence and allocation of the original container. This can be thought of as consuming the elements, but not the container itself.
- Mutating iteration: A mutable collection or a container of noncopyable elements may want to provide in-place mutation of its elements during iteration.
- Generative iteration: Certain types generate their elements during iteration, rather than storing them in memory, like iterating an
UnfoldSequenceor the key-value pairs in a dictionary. For those types, particularly those that generate noncopyable values, a different iteration model would be more performant than the borrowing iteration proposed here.
Container and other protocols
As prototyped in the swift-collections package, a future Container protocol models types that store their elements in memory. In the same way Iterable functions like a generalized Sequence, Container functions like a generalized Collection, providing indexed access to its elements. Importantly, because Container types store their elements in memory, the element accesses can have lifetimes that are borrowed against the container that stores them, a much broader lifetime than accesses via the Iterable protocol.
The following is a draft of the Container protocol and its requirements:
protocol Container<Element>: Iterable, ~Copyable, ~Escapable {
associatedtype Element: ~Copyable & ~Escapable
associatedtype Index: Equatable, Hashable
var count: Int { get }
var startIndex: Index { get }
var endIndex: Index { get }
func index(after index: Index) -> Index
func formIndex(after index: inout Index)
func index(_ index: Index, offsetBy n: Int) -> Index
func formIndex(
_ index: inout Index, offsetBy n: inout Int, limitedBy limit: Index
)
func index(alignedDown index: Index) -> Index
func index(alignedUp index: Index) -> Index
func distance(from start: Index, to end: Index) -> Int
@_lifetime(borrow self)
func nextSpan(after index: inout Index, maximumCount: Int) -> Span<Element>
subscript(index: Index) -> Element {
@_lifetime(borrow self) borrow { get }
}
}
Other protocols support some of the different kinds of iteration described above, enabling the consuming behavior required for moving noncopyable elements from container to container.
- The
Producerprotocol models types that supply their values by populating a client-supplied series ofOutputSpaninstances. - The
Drainprotocol models types that can provide an in-place consumable sequence through a series ofInputSpaninstances, allowing direct consumption of elements from some container's storage, in bulk, without requiring them to be moved into any temporary buffer.
Alternatives considered
BorrowingSequence naming
A previous version of this proposal used BorrowingSequence and similar names for a less universal version of iteration functionality. The Iterable name was selected instead, to help communicate the goal of providing iterative access to as broad a range of types as possible.
Modifying Sequence to extend Iterable
A previous version of this proposal described allowing the re-parenting of the existing Sequence protocol to make it extend the new Iterable protocol proposed here. The insertion of Iterable into the existing Sequence protocol hierarchy would allow for algorithms that target both copyable and noncopyable sequences. While re-parenting at this time is not directly planned, usage and future evaluation may lead to a proposal to make this change.
Only support sequences with direct storage
The current proposal allows any type that conforms to the current Sequence protocol to conform to the new Iterable protocol. Sequences can conform to the new protocol in basically one of two ways:
- a sequence that directly stores all of its elements can yield one or more spans providing access to those directly stored elements, and
- a sequence that does not store its elements can generate one or more elements as needed, store them in the iterator, and yield a span providing access to the elements stored in the iterator.
In order to support this second method of conformance, the span returned by a borrowing iterator's nextSpan() method has a lifetime that depends on the iterator (using the @_lifetime(&self) annotation). This places a limitation on what algorithms can be written for Iterable, since the borrow of the sequence's elements does persist beyond the lifetime of the iterator, which is typically created and used within a sequence method. For example, a first(where:) method can't return a borrow of an individual element; that borrow would only be valid inside the body of the function.
As an alternative, Iterable could only support sequences that directly store their elements. In that case, the iterator would only be in charge of managing access to the sequence's storage, not storing and yielding elements itself. The spans returned from nextSpan() could have a lifetime dependent on the sequence instead of the iterator (in which case the nextSpan() method would be marked with @_lifetime(copy self)). With the spans of elements tied to the lifetime of the sequence, a borrow of an element can outlive the iterator, and be returnable from a method like first(where:).
Future refinements of Iterable could help resolve this limitation by adding Collection-like indices, allowing referential access to elements.
Basing ~Copyable iteration on IteratorProtocol
Another direction for enabling borrowing iteration, and other kinds of iteration in the future, is to move to using iterators as the primary type for iterative algorithms. With this direction, IteratorProtocol would be generalized to allow both noncopyable/nonescapable types and elements, and instead of the proposed Iterable design, the new protocol could look like the following:
public protocol BorrowingSequence<BorrowedElement>: ~Copyable & ~Escapable {
associatedtype BorrowedElement: ~Copyable & ~Escapable
associatedtype BorrowingIterator: IteratorProtocol<BorrowedElement>
& ~Copyable & ~Escapable
@_lifetime(borrow self)
borrowing func makeBorrowingIterator() -> BorrowingIterator
}
With this approach, the BorrowedElement type that a sequence would declare as the element iterated over during borrowing iteration is not constrained to be equal to the sequence's "actual" element type. A type that can only provide borrowing access to its elements could therefore have Ref<Element> as the iterated element type, like Span, for example:
extension Span: BorrowingSequence where Self: ~Escapable, Element: ~Copyable {
@_lifetime(borrow self)
borrowing func makeBorrowingIterator() -> BorrowingIterator { ... }
struct BorrowingIterator: IteratorProtocol {
@_lifetime(copy self)
mutating func next() -> Ref<Element> { ... }
}
}
Iterative algorithms would then be written for IteratorProtocol, and be accessible whether the BorrowedElement type is the expected Element type (as for types like Array) or Ref<Element> (for types that support iteration of noncopyable elements). Because the BorrowedElement type has its lifetime linked to the iterator-providing sequence (copied from the iterator), iterative algorithms can return those elements without issue.
extension IteratorProtocol
where Self: ~Copyable & ~Escapable, Element: ~Copyable & ~Escapable
{
@_lifetime(copy self)
consuming func first(
where predicate: (borrowing Element) -> Bool
) -> Element? {
while let el = next() {
if predicate(el) { return el }
}
return nil
}
}
After prototyping this model, we still feel that the proposed direction is the best way forward for Swift. Primarily, the bulk iteration aspect of the proposed Iterable protocol is a critical part of improving performance when working with a wide variety of collections. Our experience with the existing Sequence and Collection protocol hierarchy has been instructive in how having fundamental functionality defined in the most basic, underlying protocol is important for predictable performance as the protocol hierarchy grows. We expect Iterable to play a similar role as Sequence in an upcoming hierarchy of container protocols, in which bulk iteration will continue to be a critical feature.
In addition, the different element types used in this alternative design lead to awkward usage at the call site. For example, when used with a Span<NoncopyableInt>, the first(where:) method declared above would have a signature like the following, with a (borrowing Ref<NoncopyableInt>) -> Bool predicate parameter. Forcing interaction with the element a user actually wants work with to go through a wrapper type in such a common case doesn't meet our usability expectations.
Adding noncopyable support to Sequence
Another approach for providing iteration and sequential algorithms to noncopyable types added defaulted requirements to the existing Sequence protocol. However, this design requires several Sequence-specific workarounds in the compiler, as well as additional undesirable API.
Different lifetime relationships
For some types that implement Iterable, it would be possible to have the spans returned from their iterator's nextSpan method to tie their lifetime to the overlying sequence type instead of the iterator. For example, the spans provided by a deque implementation would be memory-managed by the deque, not its iterator.
However, for sequence types that generate their elements as needed, the iterator must store the element as it's being borrowed, which requires the lifetime dependency on the iterator. This is the design chosen in order to allow maximum flexibility for conforming sequence types.
Using an opaque iterator type
As a way to mitigate the challenge of customizing the borrowing iterator in ABI-stable frameworks, Iterable could declare makeIterableIterator() as returning an opaque iterator type instead of giving the protocol an associated type. However, using an opaque type in this position creates barriers to optimization that render this approach unworkable.
Using Span as an iterator
An earlier version of this proposal used Span as a self-consuming iterator type. This added API that seemed out of place on Span (e.g. nextSpan()) and limited the flexibility of types to provide bidirectional or random-access iteration in the future.
Using borrowing iteration for all for-in loops
In the case of collections with contiguous storage, notably Array, the new iteration model results in much less overhead the optimizer to eliminate. Iterating over a Span is a lot closer to the "ideal" model of advancing a pointer over a buffer and accessing elements directly. It is therefore expected that this design will result in better performance in some cases where today the optimizer is unable to eliminate the collection type's overhead.
However, there are performance and semantic caveats to switching all iteration to the new model.
For an example of potential performance issues, imagine using UnfoldSequence to generate strings that are being streamed into an Array<String>:
- with
Sequence, the strings are produced by theUnfoldSequence, returned bynext(), and consumed into theArraywith no logical copies - with
Iterable, the strings are produced, stored in thecurrentValuevariable, copied out of theSpanof that variable into theArray, and then the value incurrentValueis destroyed.
From the perspective of semantics, changing to a borrowing access of the collection type while iterating would change the meaning of some existing code, in particular in cases where an array is modified during iteration. (While this is usually ill-advised, this code is perfectly valid.) Such cases could fail to compile if converted to borrowing iteration, or, in some cases, continue to compile but result in a runtime exclusivity violation.
For these reasons, this proposal chooses to only use borrowing iteration in cases where Sequence-based iteration is not available: in Iterable-constrained generic contexts and for types that conform only to Iterable, but not Sequence. Any switch from this default is left to future proposals.
Acknowledgments
Many thanks to Karoy Lorentey, Kavon Favardin, Joe Groff, Tony Parker, and Alejandro Alonso, for their input into this proposal.
An iterator's behavior after throwing an error is undefined
IMO this should match AsyncSequence, i.e., throwing an error must end iteration, and each subsequent call must return nil.
Is it correct that with this proposal the for e in s syntax can only be used where s is an Iterable? Was there consideration to allowing s itself to alternatively be an IterableIteratorProtocol and have using it with the loop be a consuming operation?
It seems that without this it can often force you to make 2 separate types, one to be an Iterable, then a second to be an associated IterableIteratorProtocol , when really the former is going to end up being non-escapable (non-owning) and effectively a duplicate of the first in terms of stored members, or close to it. For example let's say I want to make an iterator which goes over a UniqueArray in reverse order. My core iterator might look like this (consider it pseudocode, I'm sure missing stuff):
struct ReverseIterator<Element: ~Copyable, ~Escapable>: IterableIteratorProtocol, ~Copyable, ~Escapable {
let storage: Span<Element>
var nextIndex: Int
mutating func nextSpan(maximumCount: Int) -> Span<Element> {
if nextIndex < 0 { return Span() }
let ret = storage.extracting(nextIndex..<nextIndex + 1)
nextIndex -= 1
return ret
}
}
Then it'd be nice to simply extend UniqueArray like:
extension UniqueArray where Element: ~Copyable & ~Escapable {
var reversed: ReverseIterator<Element> {
ReverseIterator(storage: self.span, nextIndex: self.count - 1)
}
}
However if for in syntax cannot be used with an IterableIteratorProtocol directly, it seems this would require me to actually make another type like:
struct ReverseIterable<Element: ~Copyable, ~Escapable>: Iterable, ~Copyable, ~Escapable {
let storage: Span<Element>
func makeIterableIterator() -> IterableIterator {
ReverseIterator(storage: storage, nextIndex: storage.count - 1)
}
}
This type seems like extra boilerplate that needs to be written without much of a purpose.
As a relative outsider to this topic, it seems to me that the main distinction between this API and that of Sequence is that it iterates over Spans rather than Elements. Was the name SpanSequence ever considered?
SpanSequence would have several conceptual advantages over both BorrowingSequence and Iterable:
-
It tells you what the protocol actually does (or needs you to do): yield a series of
Spans.BorrowingSequenceis clear about intention but not about what that actually entails. -
Iterablesuggests a whole alternative Iteration 2.0 system running in parallel toSequence. But that isn't really true;Iterablein its current form actually sticks pretty closely to the model ofSequence, albeit with a variety of subtle enhancements. And reading between the lines, it seems like the system as a whole is intended to build onSequencerather than to replace it per se. Calling the new entitySpanSequencemakes that relationship clear and avoids creating the impression that there are now two separate iteration systems. -
"Span" is short and specific enough that it can be inserted into names without creating confusion or excessive verbiage.
-
"Span" is also semantically load-bearing in that a
Spanis a simple, well-understood entity: it's a transient view into someone else's storage. The nameSpanSequencetells you immediately that your access will be momentary, borrowing, and cheap. And it also tells you that this magic will be implemented through the use ofSpanobjects.
To flesh this out a bit more, here are the specific naming changes that might be involved:
IterablebecomesSpanSequenceIterableIteratorbecomesSpanIteratorIterableIteratorProtocolbecomesSpanIteratorProtocolmakeIterableIterator()becomesmakeSpanIterator()IterableIteratorAdapterbecomesIteratorSpanAdapterSpanIteratorbecomesSpanIteratorAdapter
Note that there's still a SpanIterator, but the name is now promoted to be the general name for iterators that yieldSpans, by analogy to Sequence's Iterator. (In the original proposal above, SpanIterator is the name of a struct that adapts existing Span types to themselves be span iterators--formerly IterableIterators, now SpanIterators.)
The existence of both IteratorSpanAdapter and SpanIteratorAdapter may raise some hackles. But the names are consistent and make sense. To begin with, both objects are in fact adapters. (That is, wrapper structs that convert from one API convention to another.) The struct originally proposed as SpanIterator is in fact an iterator, but it is also an adapter.
Second, both names (IteratorSpanAdapterand SpanIteratorAdapter)follow the logic of <thing being adapted><thing being adapted to>Adapter. An IteratorSpanAdapter adapts an Iterator (not a Sequence!) to produce Spans. A SpanIteratorAdapter adapts a Span to act as a (span) iterator.
Below is a condensed version of the name changes above shown in context. No new information here, just a different view.
public protocol SpanSequence<Element, Failure>: ~Copyable, ~Escapable {
...
/// A type that provides the iteration interface and
/// encapsulates its iteration state.
associatedtype SpanIterator: SpanIteratorProtocol<Element, Failure> & ~Copyable & ~Escapable
/// Returns a borrowing iterator over the elements of this sequence.
@_lifetime(borrow self)
func makeSpanIterator() -> SpanIterator
...
}
public protocol SpanIteratorProtocol<Element, Failure>: ~Copyable, ~Escapable {
...
}
public struct IteratorSpanAdapter<Iterator: IteratorProtocol>: SpanIteratorProtocol {
public typealias Failure = Never
var iterator: Iterator
var currentValue: Iterator.Element? = nil
public init(iterator: Iterator) {
self.iterator = iterator
}
@_lifetime(&self)
public mutating func nextSpan(maximumCount: Int) -> Span<Iterator.Element> {
// It may be surprising to some readers not used to Swift's ownership
// model that currentValue is a stored property, not just a local variable.
// This is because currentValue must be storage owned by the adapter
// instance, in order to return a span of its contents with the specified lifetime.
currentValue = iterator.next()
// note Optional._span is a private method in the standard library
// that creates an empty or 1-element span of the optional
return currentValue._span
}
}
extension Sequence {
public func makeSpanIterator() -> IteratorSpanAdapter<Iterator> {
IteratorSpanAdapter(iterator: makeIterator())
}
}
/// A borrowing iterator type that provides (potentially chunked) access
/// to the contents of a single span of elements.
public struct SpanIteratorAdapter<Element>: SpanIteratorProtocol, ~Copyable, ~Escapable
where Element: ~Copyable & ~Escapable
{
...
}
extension Span: SpanSequence
where Self: ~Copyable & ~Escapable, Element: ~Copyable
{
@_lifetime(borrow self)
func makeSpanIterator() -> SpanIteratorAdapter<Element>
}
extension MutableSpan: SpanSequence
where Self: ~Copyable & ~Escapable, Element: ~Copyable
{
@_lifetime(borrow self)
func makeSpanIterator() -> SpanIteratorAdapter<Element>
}
extension RawSpan: SpanSequence {
@_lifetime(borrow self)
func makeSpanIterator() -> SpanIteratorAdapter<UInt8>
}
extension MutableRawSpan: SpanSequence {
@_lifetime(borrow self)
func makeSpanIterator() -> SpanIteratorAdapter<UInt8>
}
extension InlineArray: SpanSequence
where Self: ~Copyable & ~Escapable, Element: ~Copyable
{
@_lifetime(borrow self)
func makeSpanIterator() -> SpanIteratorAdapter<Element>
}
That's a good point, @ben-lev. This situation is relatively common in Sequence wrapper types, as well. If you remove the ~Copyable constraint on your ReverseIterator type, it can conform to both the Iterable and IterableIteratorProtocol protocols by returning itself from makeIterableIterator():
struct ReverseIterator<Element: ~Copyable, ~Escapable>: Iterable, IterableIteratorProtocol, ~Escapable {
typealias IterableIterator = Self
func makeIterableIterator() -> Self { self }
// ...
}
I think SpanSequence and friends leans too far toward how the protocol does what it does, instead of focusing on what it does. The vast majority of users for Iterable types will only interact with the name, via generic constraints or extensions, or the behavior, when using for-in to iterate over an Iterable type. Even most authors of algorithms shouldn't need to deal directly with the Spans generated by an Iterable type.
Note: I've removed the ~Escapable elements generalization from this proposal, and moved it to the proposal to enable ~Escapable elements in Span and Ref, pitched here:
Hello again! I'm sharing a pitch for allowing nonescapable elements in the Span and Ref types, to help fill out the ownership story and to directly support ~Escapable elements in Iterable types. The PR for the proposal is here in case you have edits or other minor suggestions. Thanks for your feedback! Proposal: SE-NNNN Authors: Nate Cook, Andrew Trick, Alejandro Alonso Review Manager: TBD Status: Pitch Implementation: swiftlang/swift#89213 and swiftlang/swift#88990 Related Proposals: SE-0…
The PR is updated, and I'll update the text of the proposal at the top of this thread.