Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

False positive useless_transmute? #3340

Closed
afck opened this issue Oct 19, 2018 · 1 comment · Fixed by #8564
Closed

False positive useless_transmute? #3340

afck opened this issue Oct 19, 2018 · 1 comment · Fixed by #8564

Comments

@afck
Copy link
Contributor

afck commented Oct 19, 2018

If you (ab)use std::mem::transmute like this:

fn convert<'a>(foobar: &mut Foo<'a>) -> *mut Foo<'static> {
    unsafe { transmute(foobar) }
}

Clippy 0.0.212 complains:

warning: transmute from a reference to a pointer
  --> src/main.rs:10:14
   |
10 |     unsafe { transmute(foobar) }
   |              ^^^^^^^^^^^^^^^^^ help: try: `foobar as *mut Foo<'a> as *mut Foo<'static>`
   |
   = note: #[warn(clippy::useless_transmute)] on by default
   = help: for further information visit https://rust-lang-nursery.github.io/rust-clippy/v0.0.212/index.html#useless_transmute

But Clippy's suggestion,

fn convert<'a>(foobar: &mut Foo<'a>) -> *mut Foo<'static> {
    unsafe { foobar as *mut Foo<'a> as *mut Foo<'static> }
}

does not compile:

error[E0308]: mismatched types
 --> src/main.rs:8:14
  |
8 |     unsafe { foobar as *mut Foo<'a> as *mut Foo<'static> }
  |              ^^^^^^^^^^^^^^^^^^^^^^ lifetime mismatch
  |
  = note: expected type `*mut Foo<'static>`
             found type `*mut Foo<'a>`
note: the lifetime 'a as defined on the function body at 7:12...
 --> src/main.rs:7:12
  |
7 | fn convert<'a>(foobar: &mut Foo<'a>) -> *mut Foo<'static> {
  |            ^^
  = note: ...does not necessarily outlive the static lifetime

error: aborting due to previous error

For more information about this error, try `rustc --explain E0308`.

https://play.rust-lang.org/?version=stable&mode=debug&edition=2015&gist=55287e186a312efc65617fbd87ff288a

@HMPerson1
Copy link
Contributor

This could be considered a rustc bug since casting between raw pointers should always succeed.

What happened here was that, in the outer cast, rustc first tried to do the cast as a coercion, which succeeded, so it doesn't bother checking for the other kinds of casts, but the coercion generated the obligation that 'a: 'static, which later caused the compile to fail.

Note that foobar as *mut Foo<'a> as *mut u8 as *mut Foo<'static> works.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants