Error in compiler's dead code analysis?

Consider this code sample

#[derive(Debug)] struct PlainStruct { x: i32 }
#[derive(Debug)] struct TupleStruct (    i32 );

impl PlainStruct { fn new(x: i32) -> PlainStruct { PlainStruct { x } } }
impl TupleStruct { fn new(x: i32) -> TupleStruct { TupleStruct ( x ) } }

fn main() {
    println!("{:?}", PlainStruct::new(2));
    println!("{:?}", TupleStruct::new(2));
}

which

  1. defines two almost identical struct types
  2. instantiaties them and
  3. prints them out using the Debug trait.

The only difference between the structs is whether they were implemented as a tuple struct or not.

In the case of the tuple struct, the compiler is happy; in the case of the non-tuple struct it complains that the field is never read, even though it is printed out at run time.

Does this make sense, or is this a bug in the dead code analysis?

Playground.

The tuple struct doesn't have a name referring to the field that is supposedly unused, so maybe that's why behaviour is inconsistent across the two cases. Indeed, in code that really doesn't use the fields

struct PlainStruct { x: i32 }
struct TupleStruct (    i32 );

impl PlainStruct { fn new(x: i32) -> PlainStruct { PlainStruct { x } } }
impl TupleStruct { fn new(x: i32) -> TupleStruct { TupleStruct ( x ) } }

fn main() {
    PlainStruct::new(2);
    TupleStruct::new(2);
}

the compiler also only complains about PlainStruct's field not being used, and doesn't mention TupleStruct.

So

  • In the first case there seems to be an erroneous complaint about x not being read. (It is, when it is printed out via `Debug'.)
  • In the second case there is a lack of warning about an unused 'field'.

[Aside: is there some terminology for non-tuple-struct, i.e. the thing I have called PlainStruct in the code sample?]

1 Like

Derived Clone and Debug impls are explicitly ignored with respect to dead code analysis since rust 1.57. See https://github.com/rust-lang/rust/pull/85200

This is a bug I think.

3 Likes

I don't think so. The Rust Reference's syntax for structs calls them StructStructs, while the explaining text just calls them structs with no extra qualifier.

Implementations themselves are ignored, that's OK, but shouldn't their usage in non-derived code count as non-dead code?

2 Likes

The dead code analysis currently doesn't know how to figure out if a trait impl is used or not.

2 Likes

#92790, and will be fixed in 1.64 looks like.

3 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.