language icon indicating copy to clipboard operation
language copied to clipboard

Should struct types work with `Expando` and `Finalizer`?

Open lrhn opened this issue 3 years ago • 3 comments

Some objects are more object than other. There are classes where we do fiddle with identity, and we don't allow you to use those with features that depend on identity (currently Expando, Finalizer and WeakReference).

The problem so far has been that it's possible to have two separate objects with the same "identity". Even worse, it's possible to reintroduce an identical value after an old object has been GC'ed (for strings). That's such a mess that we just disallowed using those objects in places where identity and GC both matter.

Struct types, with their lax identity requirements, are different. It's not that we can introduce an identical struct later, it's more that we can't even know that we can present the same struct twice. It's a safe and correct implementation to throw away anything attached to a struct with an Expando immediately, because we don't even promise that the value has the same identity across calling Expando.[]=.

Should we disallow using struct types with Expando, Finalizer and WeakReference?

(Extension structs do not have their own identity, that belongs to the underlying object, so whatever we do should depend on the wrapped object, not the extension struct type.)

lrhn avatar Aug 03 '22 13:08 lrhn

This would be a run-time error, plus a compile-time error in the cases where the situation can be detected statically?

For WeakReference, could we allow the usage? Having extra copies of a given struct instance does not seem to conflict with the purpose of a weak reference: It is still OK to garbage collect a heap representation of a given struct instance if there are no other references to it than the weak one(s).

eernstg avatar Aug 03 '22 16:08 eernstg

It's not that we can introduce an identical struct later, it's more that we can't even know that we can present the same struct twice.

I don't point this out (and I should), but actually, we can introduce an identical struct later. Two struct allocations of the same type guaranteed to contain the same values can legitimately be turned into a single allocation at a dominating location, and the variable re-used (which would appear to the end user as an identical struct being introduced later). This is likely to (desired to) happen when the structs contain constant values (including post inlining/constant folding), but can in principle even happen for non-constant values.

leafpetersen avatar Aug 03 '22 19:08 leafpetersen

I'd be fine with saying you can't use structs with Expando and friends. Likewise records.

munificent avatar Aug 04 '22 00:08 munificent