Skip to content

Provide more context on ? where the error type can't be converted to the expected one #137238

Closed
@estebank

Description

@estebank

Code

struct E;

fn foo() -> Result<(), Box<dyn std::error::Error>> {
    Ok(bar()?)
}
fn bar() -> Result<(), E> {
    Err(E)
}
fn main() {}

Current output

error[E0277]: the trait bound `E: std::error::Error` is not satisfied
 --> bad.rs:4:13
  |
4 |     Ok(bar()?)
  |             ^ the trait `std::error::Error` is not implemented for `E`
  |
  = help: the trait `FromResidual<Result<Infallible, E>>` is implemented for `Result<T, F>`
  = note: required for `Box<dyn std::error::Error>` to implement `From<E>`

Desired output

error[E0277]: the trait bound `E: std::error::Error` is not satisfied
 --> bad.rs:4:13
  |
X | struct E;
  |        - doesn't implement trait `std::error::Error`
...
X | fn foo() -> Result<(), Box<dyn std::error::Error>> {
  |             -------------------------------------- requires that `Box<dyn std::error::Error>` implements `From<E>`
X |     Ok(bar()?)
  |             ^ the trait `From<E>` is not implemented for `Box<dyn std::error::Error>`
  |
  = note: the question mark operation (`?`) implicitly performs a conversion on the error value using the `From` trait

Rationale and extra context

As far as the (stable) end user is concerned, ? is a little more than a compiler intrinsic. We shouldn't mention FromResidual. We also should provide extra context on where the obligation comes from, and we should point at the return type of the enclosing function, and ideally also point at the type that couldn't be converted which is missing a From or Into impl.

Other cases

Rust Version

rustc 1.86.0-dev
binary: rustc
commit-hash: unknown
commit-date: unknown
host: x86_64-unknown-linux-gnu
release: 1.86.0-dev
LLVM version: 19.1.7

Anything else?

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsD-newcomer-roadblockDiagnostics: Confusing error or lint; hard to understand for new users.D-papercutDiagnostics: An error or lint that needs small tweaks.D-terseDiagnostics: An error or lint that doesn't give enough information about the problem at hand.D-verboseDiagnostics: Too much output caused by a single piece of incorrect code.F-try_trait_v2Tracking issue for RFC#3058T-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