Skip to content

Verify trait impls’ signatures before checking dyn compatibility #65256

Open
@nagisa

Description

@nagisa

Given a code like this:

mod obj_unsafe {
    pub trait Serialize {
        fn serialize<T>(&self, t: T);
    }
}

mod obj_safe {
    pub trait Serialize {
        fn serialize(&self);
    }
}

trait DoSomething {
    fn foo(&self) -> Box<dyn obj_safe::Serialize>;
}

impl DoSomething for () {
    fn foo(&self) -> Box<dyn obj_unsafe::Serialize> {
        unimplemented!()
    }
}

We emit an error like this:

error[E0038]: the trait `obj_unsafe::Serialize` cannot be made into an object
  --> src/lib.rs:18:5
   |
18 |     fn foo(&self) -> Box<dyn obj_unsafe::Serialize> {
   |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `obj_unsafe::Serialize` cannot be made into an object
   |
   = note: method `serialize` has generic type parameters

This error is something that was encountered by someone who read documentation and saw they needed to implement a method returning Box<dyn Serialize>, An obvious assumption is that this refers to serde::Serialize, so that’s what they specified in their return type when implementing DoSomething.

The error they got does not point them at the problem at all. Sure, Serialize from serde is not object safe, but that is irrelevant, because they are trying to make an object of an entirely wrong trait in the first place.

Instead we should be emitting error[E0053]: method foo has an incompatible type for trait first.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsA-dyn-compatibilityArea: Dyn compatibility (formerly: object safety)A-dyn-traitArea: trait objects, vtable layoutA-trait-systemArea: Trait systemC-enhancementCategory: An issue proposing an enhancement or a PR with one.T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions