Skip to content

[stdlib] fix an accidental recursion bug involving Collection #38161

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jul 1, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions stdlib/public/core/Collection.swift
Original file line number Diff line number Diff line change
Expand Up @@ -1044,6 +1044,18 @@ extension Collection where SubSequence == Slice<Self> {
}
}

extension Collection {
// This unavailable default implementation of `subscript(bounds: Range<_>)`
// prevents incomplete Collection implementations from satisfying the
// protocol through the use of the generic convenience implementation
// `subscript<R: RangeExpression>(r: R)`. If that were the case, at
// runtime the generic implementation would call itself
// in an infinite recursion because of the absence of a better option.
@available(*, unavailable)
@_alwaysEmitIntoClient
public subscript(bounds: Range<Index>) -> SubSequence { fatalError() }
}

extension Collection where SubSequence == Self {
/// Removes and returns the first element of the collection.
///
Expand Down
19 changes: 19 additions & 0 deletions validation-test/stdlib/CollectionDiagnostics.swift
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,25 @@ struct RangeReplaceableCollection_SubSequence_IsDefaulted : RangeReplaceableColl
}
}

//
// A Collection that does not use `Slice<Self>` as its SubSequence should
// require its own implementation of the Range<Index> subscript getter.
// The only valid default implementation of that Collection requirement
// returns `Slice<Self>`.
//

// expected-error@+2 {{type 'CollectionWithNonDefaultSubSequence' does not conform to protocol 'Collection'}}
// expected-error@+1 {{unavailable subscript 'subscript(_:)' was used to satisfy a requirement of protocol 'Collection'}}
struct CollectionWithNonDefaultSubSequence: Collection {
public var startIndex: Int
public var endIndex: Int

public typealias SubSequence = Self

public func index(after i: Int) -> Int { i+1 }
public subscript(position: Int) -> Int { position }
}

// FIXME: Remove -verify-ignore-unknown.
// <unknown>:0: error: unexpected note produced: possibly intended match
// <unknown>:0: error: unexpected note produced: possibly intended match