How to deny/ban the use of certain external functions

Viewed 264

I have a rust project which multiple people work on. There are certain problematic functions defined by external crates we use, that is the source of a lot of confusion and errors. I want to totally deny/ban the use of these functions crate-wide at compile time. Is there any way to do this?

1 Answers

You can use the disallowed_method Clippy lint to accomplish this. (There's also disallowed_type for types.)

For example, to disallow Box::new:

#![deny(clippy::disallowed_method)]

fn main() {
    let my_box = Box::new(123);
}

Add this to clippy.toml in the workspace root:

disallowed-methods = [
    # fully qualified function/method name:
    "std::boxed::Box::new",
]

When you then run cargo clippy, you will get an error about the usage of the disallowed function:

error: use of a disallowed method `alloc::boxed::Box::new`
 --> src/main.rs:4:16
  |
4 |   let my_box = Box::new(123);
  |                ^^^^^^^^^^^^^
  |
Related