Lint against transmutes which could be as casts.

f1b9f09
Opened by Eduard-Mihai Burtescu at 2025-03-27 18:32:11

The relevant casts are at least those between pointers and integers, or between two pointers. There's probably also some likelihood of same-type transmutes arising, which keep working after changing the types (of FFI signatures, for example) but could be removed because they're noops.

Clippy might be interested, if they don't already have this (cc @Manishearth).

  1. Unnecessary transmutes are so common that I would encourage making this a warning lint in rustc itself. It could really help to cut down on the number of transmutes in the crates.io ecosystem.

    Having transmutes when they aren't actually doing things that require transmute leads to a boy-who-cried-wolf problem, making people easily miss transmutes that are more dangerous.

    Scott Olson at 2016-06-13 00:37:35

  2. AFAIK Clippy doesn't have this yet, although useless_transmute warns for same-type case.

    Seo Sanghyeon at 2016-06-13 07:15:07

  3. Clippy also has crosspointer_transmute (transmute between T and *T, ~~“between pointers and integers above~~ EDIT: it's more limited actually) and transmute_ptr_to_ref (transmute from *T to &T) in addition to useless_transmute (transmute from T to T itself, “same-type transmutes” above).

    Martin Carton at 2016-06-13 23:19:16

  4. @mcarton To clarify, with "between pointers and integers" I meant casts that can be done with as between pointers and usize, nothing to do with *usize in particular.

    Eduard-Mihai Burtescu at 2016-06-13 23:25:35

  5. Triage: no changes

    Steve Klabnik at 2018-10-31 20:12:08

  6. Related to this: https://github.com/rust-lang/rust/pull/34609 added documentation to transmute that suggests replacing reference-to-reference transmutes with pointer as casts, but the documentation doesn't explain why that's better.

    • Is that advice still valid?
    • If yes, can someone tell me why? should be in scope of this issue?
    • If not, should we remove it?

    cc @y86-dev

    Tamir Duberstein at 2025-03-26 17:51:56

  7. Copying my comment from Zulip:

    The context I remember around the original PR, all those years ago: at the time, there was a lot of anxiety around unnecessary unsafe usage. The short and long of it was roughly "as is safe, transmute is unsafe, we should be encouraging use of as where possible."

    I also think that since all those years ago, as's favorability has gone down, and tolerance for unsafe has gone up a little, so I'm not even sure that the original justification would still be a good one today.

    Steve Klabnik at 2025-03-27 18:31:43