Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the compiler to warn me of unused code that is marked pub?

Rust warns for unused private items:

warning: function is never used: `hmm`
   --> src/example.rs:357:1
    |
357 | fn hmm() {
    | ^^^^^^^^
    |
    = note: #[warn(dead_code)] on by default

I have some code marked pub that I know is not being used. How can I get the compiler to warn me of this?

This is in the context of a library and a series of binaries, all in the same workspace. The library is only used by those binaries; the library isn't being consumed by anybody else and I'm not going to upload to crates.io, so I have full knowledge of the code that's being used.

like image 992
Tim Robinson Avatar asked Sep 07 '25 06:09

Tim Robinson


1 Answers

You cannot enable anything to do this. By definition, if something is public outside of your crate, it may be used by the crates that import your crate; there's no way for the compiler to actually tell. This is part of having a public API. Removing something from the public API is a breaking change.

If you have an item that's not exported from your crate, the fact that it's pub won't matter:

mod foo {
    pub fn bar() {}
}

fn main() {}
warning: function is never used: `bar`
 --> src/main.rs:2:5
  |
2 |     pub fn bar() {}
  |     ^^^^^^^^^^^^
  |
  = note: #[warn(dead_code)] on by default

Instead, don't mark things as public to start with. Instead, either leave off pub entirely or use a visibility modifier like pub(crate). Binary crates should basically have no items marked for export from the crate.


In your specific case of a workspace, there's never a time when a single compiler invocation knows "everything". For example, if your library exports fn a() and fn b() and one binary uses a and another binary uses b, then no compilation of the library or either binary would ever see the whole picture. The "best" case would be getting tons of false positives.

In similar situations, I've resorted to removing everything public from the API and compiling to see the errors / used functions.

A tool called warnalyzer might help in this case. It uses some unstable compiler features to save files from intermediate compiler invocations, then aggregates them to identify unused code. It has a number of false positives at the moment, but it might be useful as a guide.

like image 180
Shepmaster Avatar answered Sep 10 '25 08:09

Shepmaster