Skip to content

Auto-fix for new_without_default ignores conditional compilation #14552

@mtkennerly

Description

@mtkennerly

Summary

If fn new is conditionally compiled (e.g., #[cfg(test)]), then cargo clippy --fix adds an impl Default for Foo without that condition applied.

I did see that the help text for --fix says it implies --no-deps and --all-targets, so I can understand how it would take test-only code into account, but it still caught me off guard. Is it feasible for Clippy to preserve the conditional compilation or disable the auto-fix when conditional compilation is being used?

Reproducer

I tried this code:

pub struct Foo {
    pub bar: usize,
}

impl Foo {
    #[cfg(test)]
    pub fn new() -> Self {
        Self { bar: 1 }
    }
}

fn main() {
    println!("Hello, world!");
}

#[cfg(test)]
mod tests {
    use super::*;
 
    #[test]
    fn foo() {
        Foo::new();
    }
}

I expected to see this happen:

#[cfg(test)]
impl Default for Foo {
    fn default() -> Self {
        Self::new()
    }
}

Instead, this happened:

impl Default for Foo {
    fn default() -> Self {
        Self::new()
    }
}
error[E0599]: no function or associated item named `new` found for struct `Foo` in the current scope
 --> src\main.rs:8:15
  |
2 | pub struct Foo {
  | -------------- function or associated item `new` not found for this struct
...
8 |         Self::new()
  |               ^^^ function or associated item not found in `Foo`

Version

rustc 1.86.0 (05f9846f8 2025-03-31)
binary: rustc
commit-hash: 05f9846f893b09a1be1fc8560e33fc3c815cfecb
commit-date: 2025-03-31
host: x86_64-pc-windows-msvc
release: 1.86.0
LLVM version: 19.1.7

Additional Labels

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-bugCategory: Clippy is not doing the correct thing

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions