Skip to content

Missing parentheses in invalid cast suggestion with multiple chained casts #89497

Closed
@pr2502

Description

@pr2502

Suggestions for invalid casts don't take precedence into account.

Ideally I think it should detect an attempted *const T to &T and/or *mut T to &mut T cast and suggest replacing it with the dereferencing and reborrowing.

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

fn main() {
    let pointer: usize = &1_i32 as *const i32 as usize;
    let reference: &'static i32 = unsafe { pointer as *const i32 as &'static i32 };
}

The current output is:

error[E0605]: non-primitive cast: `*const i32` as `&'static i32`
 --> src/main.rs:3:44
  |
3 |     let reference: &'static i32 = unsafe { pointer as *const i32 as &'static i32 };
  |                                            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ invalid cast
  |
help: consider borrowing the value
  |
3 |     let reference: &'static i32 = unsafe { &*pointer as *const i32 as &'static i32 };
  |                                            ^^

Ideally the output should look like:

error[E0605]: non-primitive cast: `*const i32` as `&'static i32`
 --> src/main.rs:3:44
  |
3 |     let reference: &'static i32 = unsafe { pointer as *const i32 as &'static i32 };
  |                                            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ invalid cast
  |
help: raw pointer cannot be cast to a reference, consider dereferencing and borrowing it
  |
3 |     let reference: &'static i32 = unsafe { &*(pointer as *const i32) };
  |                                            ^^^                     ^

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsT-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