rust-lang / rust-lang/rust-clippy
New lint: `disallowed-trait-usage`
Nobody has claimed this yet.
- Dominant language
- Rust
- Stars
- 13.5k
- Forks
- 2.2k
- Avg merge
- 2d 10h
- Merged PRs (30d)
- 32
Description
What it does
The lint allows users to forbid using certain types via certain trait interfaces, for instance:
clippy.toml:
disallowed-trait-usage = [
{ type = "std::fs::PathBuf", trait = "std::fmt::Debug", reason = "Use path.display() instead" },
]
Advantage
My use case: forbidding using Debug formatting of certain types.
I am in constant pursuit of improving error messages across the crate eco-system. An easy (and common) mistake is to use Debug formatting {:?} when Display formatting {} would be better, e.g. in log calls and error message formatting. This also applies to GUIs. Usually, if there is a Display implementation, that's what should be used in any user-facing code (arguable everywhere outside of dbg!).
So I'd like to be able to use Clippy to find all these cases, and I think a good way of accomplishing it is to say "I forbid datatype X to be used via the std::fmt::Debug trait".
An example of where I've manually searched for Debug formatting and replacing it with Display (and surely missing many places):
Example
clippy.toml:
disallowed-trait-usage = [
{ type = "std::fs::PathBuf", trait = "std::fmt::Debug", reason = "Use path.display() instead" },
]
anyhow::bail!("No such file: {path:?}");
// Or:
fn print(x: &dyn Debug) { … }
print(&my_path);
->
clippy::disallowed-trait-usage: Not allowed to use `std::fs::PathBuf` as trait `std::fmt::Debug`. Reason: "Use path.display() instead"
Comparison with existing lints
There is not existing lint to cover this, but there is a similar suggestion here:
The difference is that disallowed-trait-usage would forbid all trait methods on a type. I suspect this is actually easier to implement in clippy.
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by tracing how Clippy configures existing disallowed-use lints and how trait usage is analyzed; the issue names no specific files or tests. Use the proposed clippy.toml entry and Rust examples as the acceptance cases, with diagnostics including the configured type, trait, and reason.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- rust
- Domain
- tooling
- Issue type
- Feature
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Quiet
- Clarity
- Mostly clear
- Newbie friendliness
- 45/100