rust-lang / rust

Empowering everyone to build reliable and efficient software.
https://www.rust-lang.org
Other
97.41k stars 12.59k forks source link

Incorrect dead_code warning on a function that is being called #103686

Open RalfJung opened 1 year ago

RalfJung commented 1 year ago

To reproduce, check out this branch, do ./rustup-toolchain && ./miri check:

warning: associated function `uint` is never used
   --> src/machine.rs:318:12
    |
318 |     pub fn uint(&self, size: Size) -> Option<TyAndLayout<'tcx>> {
    |            ^^^^
    |
    = note: `#[warn(dead_code)]` on by default

However, that warning is just wrong! Indeed, removing this function leads to a build error:

error[E0599]: no method named `uint` found for struct `PrimitiveLayouts` in the current scope
   --> src/shims/windows/sync.rs:22:43
    |
22  |         let layout = this.machine.layouts.uint(size).unwrap();
    |                                           ^^^^ method not found in `PrimitiveLayouts<'tcx>`
    |
   ::: src/machine.rs:274:1
    |
274 | pub struct PrimitiveLayouts<'tcx> {
    | --------------------------------- method `uint` not found for this struct
RalfJung commented 1 year ago

This is probably related to the fact that the function calling uint is itself dead code? But the warning as-is is very confusing. If anything it should point at the first unused function at the top of the call chain, not the last one at the bottom.

RalfJung commented 1 year ago

Here's a self-contained reproducer:

pub fn lib() {}

trait Ext {
    fn unused(&self) { unused2() }
}

fn unused2() {}
Noratrieb commented 1 year ago

The warning is technically correct, as the method is indeed never called and the dead_code lint is transitive (it works correctly when only free functions are involved here).

I think it should also complain that fn unused in the trait isn't used here. As long as the trait is private and the method is truly never called, it should be safe to mark it as dead code as well. I think that would fix the issue here.

RalfJung commented 1 year ago

(it works correctly when only free functions are involved here).

Indeed. But with a trait in the mix, I think the warning is misleading at best.

Somehow it does seem to notice that unused is dead code, but doesn't warn about it.