Adding any trait to any type is a breaking change

While reading through When matching on enums, read the discriminant even if there's only a single variant by meithecatte · Pull Request #154756 · rust-lang/rust · GitHub, I noticed that it mentioned that in current Rust, there is a semver compatibility hazard in which removing #[non_exhaustive] could cause a downstream library to stop compiling. The intent of that pull request is to remove the hazard.

However, it made me realise that the same principle could be used to determine during const-eval, from a downstream crate, whether any particular type implements any particular trait. The basic idea is that a closure like || drop(t) will capture t by value if its type is not provably Copy, but by reference if its type is provably Copy. In the former case, the closure will have the same type as t, but in the latter case, the closure will be pointer-sized, and it's possible to use size_of_val to distinguish the two cases. By using a type that conditionally implements Copy based on whether another type implements another trait, you can expand the technique to work on any type (even pointer-sized types), and any trait (not just Copy).

I wrote an example program that defines a macro that exploits this difference to return true if a specified type provably implements a given trait and false if this can't be proven.

Unlike with specialization, I don't think this is unsound: the unsoundnesses with specialization happen when it changes the definition of a generic item depending on a generic that got monomorphized into that item, whereas this code runs pre-monomorphization (thus, if you run provably_implements! on a type parameter, you get a true return only if all possible values for that type parameter would implement the trait).

However, this nonetheless makes me very uncomfortable and seems like a potentially serious problem, even if there's no actual unsoundness. Using a conditional Copy impl is a little contrived, but even without those, it implies that adding an implementation of Copy to a type could well end up breaking a downstream crate (because the Copy version of the closure has a shorter lifetime in addition to a different size, something which could break programs even if they aren't doing anything weird).

I'm not sure whether anything actually can or should be changed about this. (Perhaps there should be some way to explicitly move a Copy type, so that at least it would be possible for downstreams to defend against this sort of thing without needing to place all upstream types into a non-Copy wrapper.) But I thought I'd flag up the potential problem in case people have comments and/or want to suggest changes as a consequence (or in case it's worse than I thought).

2 Likes

You can break a downstream crate in many ways, most commonly by changing inference (e.g. changing a parameter from a specific type to impl Trait where PrevType: Trait can cause code to stop compiling). Nonetheless this is not a breaking change, even for std, because the language specifies it not to be. This code is even more contrived (and FWIW, the size of types is explicitly not guaranteed and if you're relying on it that's Your Problem. It should be possible to make it stop passing the borrow checker though).

I do support providing tools for downstream crates to detect when they're relying on unspecified details like this.

4 Likes

for Copy closure captures: Cromulent `Copy` closure captures by Jules-Bertholet · Pull Request #4011 · rust-lang/rfcs · GitHub

This is similar to what the unstable try_as_dyn allows. The differences are that try_as_dyn only gives you an answer if you have an actual value of that type, and that try_as_dyn allows using the trait impl you tested for. Both are violations of parametricity — the fundamental language design question is whether we want to keep the limited amount of parametricity we currently have.

But in both cases, the pragmatic answer is “don’t do that”.

  • Your code shouldn’t be depending on the specific size of any type, except one you fully control or which is documented to have a reliable size.
  • If you use try_as_dyn, it’s your responsibility to use it in reasonable ways, like choosing a more efficient but equivalent implementation, or printing more information in Debug (which is not guaranteed to do anything, and thus changing it is not a breaking change).
4 Likes

you don't need a value for try_as_dyn to work, you can always create a new trait implemented for PhantomData<T>, e.g.:

pub fn is_known_to_impl_copy<T>() -> bool {
    trait Trait {}
    impl<T: Copy> Trait for PhantomData<T> {}
    let v: Option<&dyn Trait> = try_as_dyn(&PhantomData::<T>);
    v.is_some()
}
8 Likes

You might be interested in autoref specialization, which is a similar technique used in real code. case-studies/autoref-specialization/README.md at master · dtolnay/case-studies · GitHub

3 Likes

Also relevant:

So indeed there are (and "always have been") ways to have compilation fail if a type were to implement a trait.

  • The above macro uses inference;
  • the OP post uses a const panicking snippet:
    • exploiting size_of being able to depend on a Copy predicate through closure sugar,
    • though more generally the "poorman's specialization" (be it through deref coërcions or, to make it const compatible, through inherent > trait associated consts) have also been a "long known" technique for these.
    • With try_as_dyn, this will indeed be exacerbated.

For now, the approach of stating that this falls outside of the guarantees of SemVer seem to have worked out decently well, at least because the various macros did scream "here be sketchy dragons".

It may remain important however, specially with dry_as_dyn(), to properly teach, document or even warn about this pitfall, since we might otherwise end up with instances of innocuous-looking code running into this Semver hazard indeed

1 Like

Parametricity in runtime behavior in general is long gone, if ever it existsed in Rust, I don't think it's the major argument here. The standard library did Clone/Copy elision for a long time, still does it but much more limited now by soundness. FusedIterator is a hint with the entire purpose of Fuse<I> not being fully parametric. There's may be more specialization points. We have stable post-mono const blocks since a while, and we really should count const_eval_select to as well¹. The fundamental problem instead is soundness in that removing lifetimes during lowering relies on aspects related to parametricity; aspect that size_of and align_of (and very topically, needs_drop and Drop itself) etc happen to uphold only by being compiler builtins but which do not generalize to arbitrary other type-level computation.

A downstream crate deriving a const that answers I: trait in general is just as unsound as specialization in the first place. The assembly lowering of generic functions is necessarily the same for every type family I<'lifetime>, even if there is no for<'lifetime> quantifier in its bounds, and in many cases we have I<'static>: Trait but I<'anything_else>: !Trait. But since we're required to compile those functions the same there is no sound and correct answer to the question of T:? Trait if T is instantiated with I<'_>.

try_as_dyn attempts to work around that rejecting, in the sense of None, both type families with lifetimes and not giving you a const answer in the first place. Doing both in all cases is an steeply approximate answer, maybe we could do better but it's up to proposer to figure out how.


¹While the documentation says the answer should be indistinguishable, iirc floats and non-deterministic operations builtins might behave angelical or devilish locally at compile time in a way that could never actually happen globally at runtime. (Such as, iirc a pointer being apparently unaligned with every possible alignment, I'm not up to date on this particular example though).