Skip to content

Confusing diagnostic for invalid casts of pointers to trait objects #130030

Closed

Description

Code

fn main() {
    let ptr: *const dyn Fn() = &|| ();
    _ = ptr as *const dyn Fn(u8);
}

Current output

error[E0308]: mismatched types
 --> src/main.rs:3:9
  |
3 |     _ = ptr as *const dyn Fn(u8);
  |         ^^^^^^^^^^^^^^^^^^^^^^^^ expected `()`, found `(u8,)`
  |
  = note: expected trait object `dyn Fn()`
             found trait object `dyn Fn(u8)`

Desired output

error[E0308]: invalid cast from `*const dyn Fn()` to `*const dyn Fn(u8)`
 --> src/main.rs:3:9
  |
3 |     _ = ptr as *const dyn Fn(u8);
  |         ^^^^^^^^^^^^^^^^^^^^^^^^ expected `()`, found `(u8,)`
  |
  = note: `Fn()` and `Fn(u8)` might have different vtables, leading to unsoundness
  = note: if you are absolutely sure you are using the resulting value safely, use `transmute`

Rationale and extra context

In #120248 I made checks for casting pointers to trait objects more strict: now they need to have the same generic arguments (this is due to the fact that for the cast to be safe, we need vtables to match).

The check is however made in a bit of a crude way, which results in this "mismatched types" diagnostic.

We should modify it so that the intent of the error is clear.

Rust Version

Reproduces on both stable 1.81.0 and 1.83.0-nightly (2024-09-05 9c01301).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsArea: Messages for errors, warnings, and lintsA-raw-pointersArea: raw pointers, MaybeUninit, NonNullArea: raw pointers, MaybeUninit, NonNullA-trait-objectsArea: trait objects, vtable layoutArea: trait objects, vtable layoutD-confusingDiagnostics: Confusing error or lint that should be reworked.Diagnostics: Confusing error or lint that should be reworked.D-terseDiagnostics: An error or lint that doesn't give enough information about the problem at hand.Diagnostics: An error or lint that doesn't give enough information about the problem at hand.T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.Relevant to the compiler team, which will review and decide on the PR/issue.T-typesRelevant to the types team, which will review and decide on the PR/issue.Relevant to the types 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