1 use clippy_utils::diagnostics::span_lint_and_then;
2 use clippy_utils::fn_def_id;
4 use rustc_hir::{def::Res, def_id::DefIdMap, Expr};
5 use rustc_lint::{LateContext, LateLintPass};
6 use rustc_session::{declare_tool_lint, impl_lint_pass};
8 use crate::utils::conf;
10 declare_clippy_lint! {
12 /// Denies the configured methods and functions in clippy.toml
14 /// Note: Even though this lint is warn-by-default, it will only trigger if
15 /// methods are defined in the clippy.toml file.
17 /// ### Why is this bad?
18 /// Some methods are undesirable in certain contexts, and it's beneficial to
19 /// lint for them as needed.
22 /// An example clippy.toml configuration:
25 /// disallowed-methods = [
26 /// # Can use a string as the path of the disallowed method.
27 /// "std::boxed::Box::new",
28 /// # Can also use an inline table with a `path` key.
29 /// { path = "std::time::Instant::now" },
30 /// # When using an inline table, can add a `reason` for why the method
32 /// { path = "std::vec::Vec::leak", reason = "no leaking memory" },
37 /// // Example code where clippy issues a warning
38 /// let xs = vec![1, 2, 3, 4];
39 /// xs.leak(); // Vec::leak is disallowed in the config.
40 /// // The diagnostic contains the message "no leaking memory".
42 /// let _now = Instant::now(); // Instant::now is disallowed in the config.
44 /// let _box = Box::new(3); // Box::new is disallowed in the config.
49 /// // Example code which does not raise clippy warning
50 /// let mut xs = Vec::new(); // Vec::new is _not_ disallowed in the config.
51 /// xs.push(123); // Vec::push is _not_ disallowed in the config.
53 #[clippy::version = "1.49.0"]
54 pub DISALLOWED_METHODS,
56 "use of a disallowed method call"
59 #[derive(Clone, Debug)]
60 pub struct DisallowedMethods {
61 conf_disallowed: Vec<conf::DisallowedMethod>,
62 disallowed: DefIdMap<usize>,
65 impl DisallowedMethods {
66 pub fn new(conf_disallowed: Vec<conf::DisallowedMethod>) -> Self {
69 disallowed: DefIdMap::default(),
74 impl_lint_pass!(DisallowedMethods => [DISALLOWED_METHODS]);
76 impl<'tcx> LateLintPass<'tcx> for DisallowedMethods {
77 fn check_crate(&mut self, cx: &LateContext<'_>) {
78 for (index, conf) in self.conf_disallowed.iter().enumerate() {
79 let segs: Vec<_> = conf.path().split("::").collect();
80 if let Res::Def(_, id) = clippy_utils::path_to_res(cx, &segs) {
81 self.disallowed.insert(id, index);
86 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
87 let def_id = match fn_def_id(cx, expr) {
88 Some(def_id) => def_id,
91 let conf = match self.disallowed.get(&def_id) {
92 Some(&index) => &self.conf_disallowed[index],
95 let msg = format!("use of a disallowed method `{}`", conf.path());
96 span_lint_and_then(cx, DISALLOWED_METHODS, expr.span, &msg, |diag| {
97 if let conf::DisallowedMethod::WithReason {
98 reason: Some(reason), ..
101 diag.note(&format!("{} (from clippy.toml)", reason));