Changing lint configuration based on Cargo profile

So I tried a few things with version 1.78.0-nightly (c475e2303 2024-02-28).

1. Conditional lint in Cargo.toml

I tried adding something like this to Cargo.toml:

[target.'cfg(debug_assertions)'.lints.rust]
dead_code = { level = "allow", priority = 2 }

It didn’t work. The allow rule was ignored and Cargo complained:

warning: Cargo.toml: Found debug_assertions in target.'cfg(...)'.dependencies. This value is not supported for selecting dependencies and will not work as expected. To learn more visit https://doc.rust-lang.org/cargo/reference/specifying-dependencies.html#platform-specific-dependencies

2. Conditional lint in .cargo/config.toml

On the other hand, trying to conditionally set rustflags in .cargo/config.toml causes Cargo to unconditionally use the flags for both dev and release builds.

[target.'cfg(debug_assertions)']
rustflags = ["-A", "dead-code"]

3. include! macro

I also tried including a snippet like this in the crate’s root source file (main.rs or lib.rs) using the include! macro. That didn’t work because apparently inner attributes like #![cfg_attr()] cannot be included (see issues rfc#752 and rust#66920).

#![cfg_attr(debug_assertions, allow(dead_code))]

Code generation?

So I’m out of options to eliminate the code duplication in the main.rs and lib.rs files. My actual list of allow rules contains more than just dead_code and keeps growing:

#![cfg_attr(
    debug_assertions,
    allow(
        dead_code,
        missing_docs,
        unreachable_code,
        unused_imports,
        unused_variables,
        clippy::missing_docs_in_private_items,
    )
)]

Keeping this list in sync across many crates is error-prone. One remaining solution would be setting up a build script to generate the main.rs and lib.rs files from templates before starting the build process.

If anyone has more ideas, please let me know!

1 Like