rust-lang / rust-lang/rust-clippy

New lint: `disallowed-trait-usage`

Open
#15,765 1 comment 5 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

A-lint
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

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. 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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.