Skip to content

Missing trait error for type (used as a type parameter) containing a trait object can have a broader span than expected #103547

Open
@Imberflur

Description

@Imberflur

Given the following code: https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=7a574fab349d3be4d4574b12df5a9932

struct TypeCombiner<A, B>(A, B);

trait MyTrait {
    type Assoc;
}

trait OtherTrait {}

struct A;
struct B;
struct C {
    a: A,
    b: B,
}

impl MyTrait for A {
    type Assoc = ();
}

// missing implementation for B

impl MyTrait for C {
    // span for error output of missing MyTrait for the `Box<T>` type is taken
    // from the whole `TypeCombiner<...>` when `T` is a trait object 
    type Assoc = TypeCombiner<
        <A as MyTrait>::Assoc,
        <Box<dyn OtherTrait> as MyTrait>::Assoc,
    >;
}

The current output is:

error[[E0277]](https://doc.rust-lang.org/stable/error-index.html#E0277): the trait bound `Box<(dyn OtherTrait + 'static)>: MyTrait` is not satisfied
  --> src/lib.rs:25:18
   |
25 |       type Assoc = TypeCombiner<
   |  __________________^
26 | |         <A as MyTrait>::Assoc,
27 | |         <Box<dyn OtherTrait> as MyTrait>::Assoc,
28 | |     >;
   | |_____^ the trait `MyTrait` is not implemented for `Box<(dyn OtherTrait + 'static)>`
   |
   = help: the following other types implement trait `MyTrait`:
             A
             C

Ideally the output should look like:

error[[E0277]](https://doc.rust-lang.org/stable/error-index.html#E0277): the trait bound `Box<(dyn OtherTrait + 'static)>: MyTrait` is not satisfied
  --> src/lib.rs:27:9
   |
27 |         <Box<dyn OtherTrait> as MyTrait>::Assoc,
   |         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `MyTrait` is not implemented for `Box<(dyn OtherTrait + 'static)>: MyTrait`
   |
   = help: the following other types implement trait `MyTrait`:
             A
             C

Note that replacing dyn OtherTrait with a non trait object type like u8 yields the desired error output. My first guess would be that this is related to expanding dyn OtherTrait to (dyn OtherTrait + 'static) (but this is just a random guess).

In my case, this causes error output in custom derive macro generated code to not point back to the original fields. Normally, the proc macro can give each type parameter the span info for the field it is derived from and then error output will show that field.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsA-dyn-traitArea: trait objects, vtable layoutA-trait-systemArea: Trait systemD-imprecise-spansDiagnostics: spans don't point to exactly the erroneous codeT-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