Description
Code
util.rs
:
pub fn get_random_number() -> i32 {
return 4;
}
lib.rs
:
#[path = "util.rs"] mod util_lib;
mod util;
pub fn run() -> i32 {
return util_lib::get_random_number();
}
Current output
warning: function `get_random_number` is never used
--> src/util.rs:1:8
|
1 | pub fn get_random_number() -> i32 {
| ^^^^^^^^^^^^^^^^^
|
= note: `#[warn(dead_code)]` on by default
Desired output
Option 1: Disable dead code warning if code is used in any module
From this point of view, code that is used somewhere is not considered dead code, regardless of the module that uses it. However, if loading separate modules from the same source file was a mistake, this may make finding the issue harder.
Option 2: Enhance the dead code warning with module information
- Instead of
warning: function `get_random_number` is never used
, we could havewarning: function `util::get_random_number` is never used
orwarning: function `get_random_number` in module `util` is never used
- In the specific case where the function is used as part as another module, mention it as extra context for the warning, e.g.
note: function `get_random_number` was used as part of other modules: `util_lib`
Option 3: Disable dead code warning if code is used in any module, warn about separate modules using different names
warning: file `src/util.rs` is used as the source to more than one module
--> src/lib.rs:4:1
|
1 | #[path = "util.rs"] mod util_lib;
| --------- module `util_lib` is based on `src/util.rs`
...
3 | mod util;
| ^^^^^^^^^ `src/util.rs` used again here for module `util`
|
This is the most obvious way to detect 2 modules mistakenly using the same file. But if there are many legitimate use case for using the same file for 2+ modules, something like #[allow(mod_use_same_source)]
will need to be added to these existing projects to avoid the warning, which may be cumbersome.
Rationale and extra context
The current warning is misleading, as the function is actually used. This is not dead code, just "dead code in the context of a specific module", but the warning doesn't indicate that.
In some cases it's easy to miss that the module is loaded twice under different names. If the module was loaded twice under the same name, cargo check
would have returned error[E0428]: the name util is defined multiple times
, which is very helpful.
Other cases
The same warning is displayed if #[cfg_attr(unix, path = "util.rs")]
is used instead of #[path = "util.rs"]
.
Rust Version
$ rustc --version --verbose
rustc 1.82.0 (f6e511eec 2024-10-15)
binary: rustc
commit-hash: f6e511eec7342f59a25f7c0534f1dbea00d01b14
commit-date: 2024-10-15
host: x86_64-unknown-linux-gnu
release: 1.82.0
LLVM version: 19.1.1
Anything else?
Minimal reproduction: https://github.com/ilai-deutel/cfg-attr-dead-code/blob/main/src/lib.rs
Real occurrence: ilai-deutel/kibi#330