Skip to content

Misleading error message involving blanket implementations and associated types #55591

@jturner314

Description

@jturner314

Under some circumstances involving blanket implementations and associated types, the compiler gives a misleading error message describing the wrong trait bound.

I tried this code:

pub trait IntoProducer {
    type Output: Producer;
}

impl<P: Producer> IntoProducer for P {
    type Output = Self;
}

impl<'a, T> IntoProducer for &'a Vec<T> {
    type Output = &'a [T];
}

pub trait Producer {}

impl<'a, T> Producer for &'a [T] {}

fn dostuff<IP, P>(arg: IP)
where
    IP: IntoProducer<Output = P>,
    P: Producer,
{
    unimplemented!()
}

fn main() {
    dostuff(Vec::<i32>::new());
}

(Playground)

I expected to see an error message like this (the correct bound is IntoProducer):

error[E0277]: the trait bound `std::vec::Vec<i32>: IntoProducer` is not satisfied
  --> src/main.rs:26:5
   |
26 |     dostuff(Vec::<i32>::new());
   |     ^^^^^^^ the trait `IntoProducer` is not implemented for `std::vec::Vec<i32>`
   |
note: required by `dostuff`
  --> src/main.rs:17:1
   |
17 | / fn dostuff<IP, P>(arg: IP)
18 | | where
19 | |     IP: IntoProducer<Output = P>,
20 | |     P: Producer,
21 | | {
22 | |     unimplemented!()
23 | | }
   | |_^

Instead, the compiler gave this error message (the bound is Producer):

error[E0277]: the trait bound `std::vec::Vec<i32>: Producer` is not satisfied
  --> src/main.rs:26:5
   |
26 |     dostuff(Vec::<i32>::new());
   |     ^^^^^^^ the trait `Producer` is not implemented for `std::vec::Vec<i32>`
   |
note: required by `dostuff`
  --> src/main.rs:17:1
   |
17 | / fn dostuff<IP, P>(arg: IP)
18 | | where
19 | |     IP: IntoProducer<Output = P>,
20 | |     P: Producer,
21 | | {
22 | |     unimplemented!()
23 | | }
   | |_^

This occurs on stable (1.30.0), beta (1.31.0-beta.3), and nightly (1.31.0-nightly) on the Rust Playground.

What appears to be happening is that the compiler sees the impl<P: Producer> IntoProducer for P implementation and assumes that this implementation that will always be used, even though it has a P: Producer constraint and other implementations of IntoProducer exist.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsA-trait-systemArea: Trait systemC-enhancementCategory: An issue proposing an enhancement or a PR with one.D-confusingDiagnostics: Confusing error or lint that should be reworked.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