rust-lang / rust-lang/rust

`invalid_value` does not warn when transmuting from a unit struct to an uninhabited type

Open
#126,529 0 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

A-lints C-bug L-invalid_value T-compiler
Dominant language
Rust
Stars
119k
Forks
16.1k
PR merge metrics
PR metrics pending

Description

I tried this code:

struct T;
enum U {}

pub fn ub() {
    unsafe { std::mem::transmute::<T, U>(T) };
}

fn main() {}

I expected to see this happen: warning that the transmute is invalid/UB.

Instead, this happened: no warning :(

A similar example, but with () instead of a unit structure does warn:

pub fn ub() {
    unsafe { std::mem::transmute::<(), U>(()) };
}

fn main() {}
warning: the type `U` does not permit zero-initialization
  --> tests/ui/never_type/never_transmute_never.rs:12:14
   |
12 |     unsafe { std::mem::transmute::<(), U>(()) };
   |              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ this code causes undefined behavior when executed
   |
note: enums with no inhabited variants have no valid value
  --> tests/ui/never_type/never_transmute_never.rs:9:1
   |
9  | enum U {}
   | ^^^^^^
   = note: `#[warn(invalid_value)]` on by default
Meta

rustc --version --verbose:

rustc 1.80.0-nightly (98489f248 2024-06-06)
binary: rustc
commit-hash: 98489f2487465f3765e5dd28d7305ebfd40f0865
commit-date: 2024-06-06
host: x86_64-unknown-linux-gnu
release: 1.80.0-nightly
LLVM version: 18.1.7

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 compiling the provided unit-struct and empty-enum example, then compare it with the () variant that emits a warning. Use tests/ui/never_type/never_transmute_never.rs as the reference test and verify that the unit-struct transmute produces the expected invalid-value warning without regressing the existing case.

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
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.