Never consider raw pointer casts to be trival by Noratrieb · Pull Request #113262 · rust-lang/rust (original) (raw)
@Nilstrieb can you open an issue that we stop emitting the trivial_casts
lint for pointers with an example?
going to nominate for @rust-lang/lang. I consider this to be a pure bugfix.
We currently do not generate any MIR for pointer casts which only transmute lifetimes. This happens as HIR typeck does not consider the source and target to have distinct types. This causes the following snippet to error:
struct Foo<'a>(&'a ());
fn foo<'a>(v: *const Foo<'a>) -> *const Foo<'static> { v as *const Foo<'static> //~^ ERROR lifetime may not live long enough }
This can already be avoided by first casting to an unrelated type:
struct Foo<'a>(&'a ());
fn foo<'a>(v: *const Foo<'a>) -> *const Foo<'static> { v as *const () as *const Foo<'static> }
With this PR both snippets now compile. Unfortunately this means that we now don't emit the trivial_casts
lint when casting raw pointers as we don't know whether the cast is trivial during HIR typeck:
#![warn(trivial_casts)]
struct Foo<'a>(&'a ());
fn foo<'a>(v: *const Foo<'a>) -> *const Foo<'a> {
v as *const Foo<'a>
//~^ WARN trivial cast: *const Foo<'a>
as *const **Foo<'a>
}
We could check raw pointer casts during MIR borrowck and lint there, but that may not be worth it 🤷 I think it's fine to open an issue for it and merge this as is, as it does not seem too important to me.