rust-lang / rust-lang/rust-clippy

`transmutes_expressible_as_ptr_casts` shows rustc diagnostics for hypotehtical `as` cast

Open
#17,063 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

C-bug
Dominant language
Rust
Stars
13.5k
Forks
2.2k
Avg merge
2d 10h
Merged PRs (30d)
32

Description

Summary

The clippy lint transmutes_expressible_as_ptr_casts calls into rustc_hir_typeck::cast::check_cast to check if a cast from one type to another would type-check. When the cast is invalid, there shouldn't be any diagnostics from either rustc or clippy. This is mostly ensured by the check_cast helper discards only running the "check" part and not the "report cast error" part, but but there are a few errors and lints that are reported in the "check" phase. Those are shown when the clippy lint considers a transmute that rustc would lint/error on.

Note: I'm reporting this in the clippy issue tracker because it's only user-visible through clippy, but it seems likely that the root cause and fix are in rustc.

Reproducer

Code:

https://play.rust-lang.org/?version=stable&mode=debug&edition=2024&gist=d4303b7bc7f0a6253a61b325976cc185

#[repr(u32)]
enum Foo { A }

impl Drop for Foo {
    fn drop(&mut self) {}
}

pub fn foo() -> u32 {
    unsafe {
        std::mem::transmute::<Foo, u32>(Foo::A)
    }
}

Current output:

    Checking playground v0.0.1 (/playground)
error: cannot cast enum `Foo` into integer `u32` because it implements `Drop`

error: could not compile `playground` (lib) due to 1 previous error

Desired output:

(No diagnostic)

Version

Additional Labels

No response

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start at rustc_hir_typeck::cast::check_cast and trace how its check and report-cast-error phases are used by the transmutes_expressible_as_ptr_casts lint. Reproduce the linked example with the provided Rust Playground code; done means the invalid hypothetical cast produces no rustc or Clippy diagnostic.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Quiet
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.