Skip to content

False positive: missing structure fields, on structure fields behind #cfg #16947

@tyrypyrking

Description

@tyrypyrking

minimal code snippet to reproduce:

//Cargo.toml
[package]
name = "minissue"
version = "0.1.0"
edition = "2021"

[dependencies]
serde = { version = "1.0.197", features = ["derive"] }

[features]
default = ["hello", "bye"]
hello = []
bye = []

//main.rs
use serde::Deserialize;

//Both lines display as two errors each.
#[derive(Deserialize)]
struct SomeStruct { //Error: missing structure field:  - hello
    #[cfg(feature = "hello")]
    pub hello: String,
    #[cfg(not(feature = "bye"))]
    pub bye: String, //Error: no such field
}

fn main() {
    #[cfg(feature = "hello")]
    println!(
        "{}",
        SomeStruct {
            hello: "hello".to_owned(),
        }
        .hello
    );
}

Only requires #[derive(Deserialize)], other derives such as Serialize, Debug, etc, are working fine.
cargo check doesn't show any errors.
We can avoid the rust-analyzer false flags by adding redundant code. Something like the following:

#[cfg(not(feature = "hello"))]
#[allow(dead_code)]
#[serde(skip_deserializing)]
pub hello: (),

Previously we were tracking this behavior with #11657 as it was the same error we had in this snippet. But as of recently the issue was marked resolved.

rust-analyzer version: 2024-03-25

rustc version:
rustc 1.74.0 (79e9716c9 2023-11-13)

Metadata

Metadata

Assignees

Labels

A-nameresname, path and module resolutionA-proc-macroproc macroC-bugCategory: bug

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions