rust-lang / rust-lang/rust-clippy

clippy::borrowed_box gives a a wrongly suggestion with std::mem::transmute

Open
#12,602 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

Summary

wrong behavior on std::mem::transmute

Lint Name

clippy::borrowed_box

Reproducer

I tried this code:

fn main() {
    use std::mem::transmute;
    let boc = Box::new(1);

    unsafe {
        let reflect: Box<()> = transmute(boc);

        let reference1: &Box<i32> = transmute(&reflect);
        println!("{}", reference1);

        let reference2: &i32 = transmute(&reflect);
        println!("{}", reference2);
    }
}

clippy says:

warning: you seem to be trying to use `&Box<T>`. Consider using just `&T`
 --> src/main.rs:8:25
  |
8 |         let reference1: &Box<i32> = transmute(&reflect);
  |                         ^^^^^^^^^ help: try: `&i32`
  |
  = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#borrowed_box
  = note: `#[warn(clippy::borrowed_box)]` on by default

but its a UB! &reflect is a reference to Box<()> and actually a reference to Box<i32>

the suggestion turn transmute::<&Box::<()>, &Box::<i32>> into transmute::<&Box::<()>, &i32

Version
rustc 1.79.0-nightly (0824b300e 2024-03-24)
binary: rustc
commit-hash: 0824b300eb0dae5d9ed59719d3f2732016683d66
commit-date: 2024-03-24
host: x86_64-unknown-linux-gnu
release: 1.79.0-nightly
LLVM version: 18.1.2
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 by locating the implementation and tests for the clippy::borrowed_box lint, then reproduce the supplied Rust example involving std::mem::transmute. Trace how the lint builds its suggestion for the two reference types. Done means the reproducer no longer receives the misleading suggestion, with regression coverage for this case.

Written by the indexing model from the issue text.

Assessment

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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.