Skip to content

dead_code lint incorrectly warns about struct fields that aren't dead due to transmuting #15102

Closed
@lilyball

Description

@lilyball

The dead_code lint was recently (#14696) modified to detect dead struct fields. Unfortunately, it warns about fields even when it can't be 100% certain they're dead.

One case where this happens was filed as #15101, where the struct is used as C FFI. That case has the (undocumented) solution of using #[repr(C)] (even though #[repr(C)] hasn't been implemented to actually do anything yet).

Another case that doesn't have a clear solution beyond turning off the warning is a struct that contains fields for the purpose of being memory-layout-compatible with another struct.

Notably, in lilyball/rust-lua@be46e268c0, the file lib.rs defines 3 structs with identical layout. Two of the structs properly use all defined fields, but one of the structs does not use one field (beyond initialization). However, there are methods that use men::transmute() to convert between the struct types. If this method is used, then the allegedly-dead field becomes live, as the destination struct uses that field.

I recognize that this is a bit of an edge case, but this isn't the only one. Besides C FFI, a quick test demonstrates that a supposedly-unused struct field that is in fact printed via a format!("{:?}", foo) directive is also considered dead. I wouldn't be surprised to find out that there are more edge cases either. The basic point here is that the dead_code lint is making an unqualified statement that the field is never used, but it doesn't actually have 100% certainty of that fact. It should be modified to recognize cases where the struct is used in ways the lint can't see into. So far the list of cases includes:

  1. Being passed as a *mut to a C FFI function
  2. Being passed to mem::transmute()
  3. Being passed to ::debug::fmt::secret_poly

And we can probably add casting *mut StructType to any *mut T (via as, e.g. foo as *mut ()) to the list.

/cc @jakub-

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-lintsArea: Lints (warnings about flaws in source code) such as unused_mut.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions