Ergonomics: generic types conforming "in more than one way"

It is. I just never quite realized until recently how serious the consequences are for generic programming. Namely, you have to learn one or both of these lessons:

  1. You can't reliably provide a specialized implementation of a base protocol requirement in a derived protocol extension. It will seem to work in many scenarios, but will break down in corners as described here:
  2. Conditionally conforming a generic type to a more refined protocol than the one it already conforms to doesn't work if any of the base protocol's requirements have been specialized in the more refined protocol. Those specializations become shadowing overloads that are not used in all contexts.

Me too; I think if you do any algorithm specialization mistakes are unavoidable (unless you resort to beautiful/horrifying hacks like the one described by @Nevin here, which don't currently optimize well). My take on it is:

  • Protocol extensions as they exist today are an inappropriate mechanism for specialization of public protocols in libraries.

  • You can use them for requirement specialization privately if you're very careful about the lessons cited above

  • To avoid changing the semantics of existing code, fixing this will require:

    • New language features to describe requirement specializations explicitly
    • Warnings to be issued whenever something in a protocol extension could match a requirement from a less-refined protocol.
    • An annotation that you can add to such a protocol extension to denote, “yes, that's OK, I intended to shadow that requirement and I know it's not going to provide an implementation of the requirement”

Fortunately I have been advised that there's room in the ABI for the things needed to fix the problem, so there's hope for the future at least. I think any reasonable solution to these problems could easily also address this one.

3 Likes