Skip to content

New lint: disallowed-trait-usage #15765

@emilk

Description

@emilk

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-lintArea: New lints

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions