«where» clauses on contextually generic declarations

Introduction

The objective is to lift the restriction on attaching where clauses to declarations that themselves do not carry a generic parameter list explicitly, but inherit the surrounding generic environment. Simply put, this means you no longer have to worry about the 'where' clause cannot be attached error within a generic context.

struct Box<Wrapped> {
    func sequence() -> [Box<Wrapped.Element>] where Wrapped: Sequence { ... }
}

Note: Only declarations that can already be generic and support being constrained via a conditional
extension are covered by this enhancement. Properties and new constraint kinds are out
of scope for this document. For example, the following remains an error:

protocol P {
    // error: Instance method requirement 'foo(arg:)' cannot add constraint 'Self: Equatable' on 'Self'
    func foo() where Self: Equatable  
}

Motivation

Today, where clauses on contextually generic declarations can only be expressed indirectly by placing them on conditional extensions. Unless the constraints are identical, every such declaration requires a separate extension. This apparent dependence on extensions is an obstacle to stacking up constraints or grouping semantically related APIs and usually becomes a pain point in heavily generic code that unnecessarily complicates the structure of a program for the developer and the compiler.

Leaving ergonomic shortcomings behind, it is only natural for a where clause to work anywhere a constraint can be meaningfully imposed, meaning both of these layout variants should be possible:

// 'Foo' can be any kind of nominal type declaration. For a protocol,
// 'T' would be an associatedtype.
struct Foo<T> {}  

extension Foo where T: Sequence, T.Element: Equatable {
    func slowFoo() { ... }
}
extension Foo where T: Sequence, T.Element: Hashable {
    func optimizedFoo() { ... }
}
extension Foo where T: Sequence, T.Element == Character {
    func specialCaseFoo() { ... }
}

extension Foo where T: Sequence, T.Element: Equatable {
    func slowFoo() { ... }

    func optimizedFoo() where T.Element: Hashable { ... }

    func specialCaseFoo() where T.Element == Character { ... }
}

A move towards «untying» generic parameter lists and where clauses is an obvious and farsighted improvement to the generics system with numerous future applications, including contextually generic computed properties, opaque types, generalized existentials and constrained protocol requirements.

Source compatibility and ABI stability

This is an additive change with no impact on the ABI and existing code.

Effect on API resilience

For public declarations in resilient libraries, switching between a constrained extension and a «direct» where clause will not be source-breaking, but will break the ABI due to subtle mangling differences.

21 Likes

I like the idea of lifting this restriction. The decision to use a where clause or constrained extension should be a stylistic choice left up to the programmer.

That is correct.

5 Likes

The proposal says that constraints like this will still remain invalid. Is this a general restriction or something that can be lifted in the future as well? Even though this example seems invalid in its nature, I think it shouldn't be (in the future).

If you would re-write it differently it can start to make sense. Let's say we don't have the foo method as a protocol requirement to simplify things a bit.

// Conditional extension where `foo` will become visible/available on
// conforming types that also conform to `Equatable`. This pattern
// is already known and well understood by the Swift community.
extension P where Self: Equatable {
  func foo() { ... }
  func bar() { ... }
}
// If we did not had any conditional conformances then I assume we
// would instead duplicate 'where' clause conditions on a lot of type
// members.
extension P {
  // Always visible to `P` conforming types, but is rejected by the
  // compiler when `Self` does not conform to `Equatable`. This
  // behavior is slightly different from the above as it exposes the
  // type members regardless their constraints.
  // The only thing we did here was 
  func foo() where Self: Equatable { ... }
  func bar() where Self: Equatable { ... }
}
// Analogous example (with parameterized extensions in mind):
extension<T> Optional where Wrapped == T? {
  // Is not visible/available through `Optional` until `Wrapped` is 
  // identified as `T?`.
  func bar() { ... }
}

extension Optional {
  // Always visible from `Optional` but is rejected by the compiler
  // when `Wrapped` is not `T?` with an error: 'Generic parameter
  // 'T' could not be inferred'
  func foo<T>() where Wrapped == T? {}
}

With that in mind I think allowing the original invalid example in the future would be okay. I'm not arguing that we should do that as I don't quite see any good use-cases for this, because by the end of the day we're talking about the expressiveness of the same constraint just in a different way.


+1 for the original proposal.

Semantically, a conditional extension and a direct where clause are equivalent. When the compiler is capable of knowing whether the constraints are satisfied beforehand, foo must only be visible when the receiver satisfies those constraints. As you demonstrate with foo<T>() where Wrapped == T?, sometimes this isn't possible, so you are allowed to access the member and specialize any generic parameters before the compiler can jump to any conclusions on whether you can actually use it.

The key difference in placing constraints on a requirement is that we can dynamically dispatch to a constrained declaration. Answering your first question, it is also a limitation we can pass through Evolution and implement in the future.

Asking from a developer perspective, is it necessary to mangle these differently, that is, is it possible to make this an ABI-compatible change?

It would be possible but I don't think we want to do that. Mangling for nested entities intentionally reflects the lexical structure, so that, for example, Demangle::getTypeForMangling() can easily find the declaration. If you mangle declarations with a where clause as if they were part of a fake constrained extension it would complicate code like that.

Also, we already mangle generic declarations with where clauses that reference outer parameters differently from constrained extension members, so introducing a special case here is even more error prone.

Terms of Service

Privacy Policy

Cookie Policy