SF-0011 and existentials

I've tried to migrate some of the notifications in our codebase to SF-0011 and faced a challenge.

We often erase specific classes to protocols for unit testing purposes. I.e. you often get in a batch:

protocol Foo: AnyObject {}
class FooImpl: Foo {}
class FooMock: Foo {}

And if this entity can post notifications, then notifications are part of the contract of the protocol, so I would put FooEventMessage: NotificationCenter.MainActorMessage next to the the protocol Foo and would use any Foo as Subject.

But it does not work, because NotificationCenter methods have Message.Subject: AnyObject requirement and (any Foo) does not satisfy it.

The intention behind Message.Subject: AnyObject is valid, so IMO it is a language issue. And conformance (any P): AnyObject should be valid when P conforms to AnyObject. Or there should be some other protocol that covers this functionality.

As a workaround, it might be possible to remove the constraint from NotificationCenter methods and instead check for stable identity at the runtime. @Philippe_Hausler, @cthielen, WDYT?

I believe Jordan's reply here answers the question as to the language issue:

Basically, as I understand it, the 'meaning' of conforming to AnyObject is that under the hood you're a single reference. But any (ha) existential any P, even if protocol P: AnyObject, is not laid out that way so doesn't actually fulfill the layout constraint required by conformance to AnyObject.

It would have to be explicitly opt-in on an ABI-stable platform to change that, non-backward deployable, and in any case carry runtime performance penalties.

Perhaps you could make Subject a generic parameter:

struct FooEventMessage<Subject: Foo>: NotificationCenter.MainActorMessage

This builds fine but I didn't test it thoroughly.

Maybe we could extend meaning of AnyObject conformance to "first word is a reference, and the rest are bitwise copiable bits". From the first glance, it does sound reasonably backwards-compatible. But maybe there are some challenges with co-/contra-variance.

I was thinking about it. It does not work for use cases that want to observe messages regardless of the posting instance. If ObjC bridging is fully implemented, then FooEventMessage<A> can be converted to Notification and then parsed as FooEventMessage<B>. But this bridging is optional. And for cases without any ObjC usages, I would prefer to skip it.

I see. Another option - mock (in this case) with a class instead of a protocol and make the Subject of that common base class.