]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/disallowed_methods.rs
Simplify `clippy` fix.
[rust.git] / clippy_lints / src / disallowed_methods.rs
1 use clippy_utils::diagnostics::span_lint_and_then;
2 use clippy_utils::{fn_def_id, get_parent_expr, path_def_id};
3
4 use rustc_hir::{def::Res, def_id::DefIdMap, Expr, ExprKind};
5 use rustc_lint::{LateContext, LateLintPass};
6 use rustc_session::{declare_tool_lint, impl_lint_pass};
7
8 use crate::utils::conf;
9
10 declare_clippy_lint! {
11     /// ### What it does
12     /// Denies the configured methods and functions in clippy.toml
13     ///
14     /// Note: Even though this lint is warn-by-default, it will only trigger if
15     /// methods are defined in the clippy.toml file.
16     ///
17     /// ### Why is this bad?
18     /// Some methods are undesirable in certain contexts, and it's beneficial to
19     /// lint for them as needed.
20     ///
21     /// ### Example
22     /// An example clippy.toml configuration:
23     /// ```toml
24     /// # clippy.toml
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
31     ///     # is disallowed.
32     ///     { path = "std::vec::Vec::leak", reason = "no leaking memory" },
33     /// ]
34     /// ```
35     ///
36     /// ```rust,ignore
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".
41     ///
42     /// let _now = Instant::now(); // Instant::now is disallowed in the config.
43     ///
44     /// let _box = Box::new(3); // Box::new is disallowed in the config.
45     /// ```
46     ///
47     /// Use instead:
48     /// ```rust,ignore
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.
52     /// ```
53     #[clippy::version = "1.49.0"]
54     pub DISALLOWED_METHODS,
55     style,
56     "use of a disallowed method call"
57 }
58
59 #[derive(Clone, Debug)]
60 pub struct DisallowedMethods {
61     conf_disallowed: Vec<conf::DisallowedMethod>,
62     disallowed: DefIdMap<usize>,
63 }
64
65 impl DisallowedMethods {
66     pub fn new(conf_disallowed: Vec<conf::DisallowedMethod>) -> Self {
67         Self {
68             conf_disallowed,
69             disallowed: DefIdMap::default(),
70         }
71     }
72 }
73
74 impl_lint_pass!(DisallowedMethods => [DISALLOWED_METHODS]);
75
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::def_path_res(cx, &segs) {
81                 self.disallowed.insert(id, index);
82             }
83         }
84     }
85
86     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
87         let uncalled_path = if let Some(parent) = get_parent_expr(cx, expr)
88             && let ExprKind::Call(receiver, _) = parent.kind
89             && receiver.hir_id == expr.hir_id
90         {
91             None
92         } else {
93             path_def_id(cx, expr)
94         };
95         let def_id = match uncalled_path.or_else(|| fn_def_id(cx, expr)) {
96             Some(def_id) => def_id,
97             None => return,
98         };
99         let conf = match self.disallowed.get(&def_id) {
100             Some(&index) => &self.conf_disallowed[index],
101             None => return,
102         };
103         let msg = format!("use of a disallowed method `{}`", conf.path());
104         span_lint_and_then(cx, DISALLOWED_METHODS, expr.span, &msg, |diag| {
105             if let conf::DisallowedMethod::WithReason {
106                 reason: Some(reason), ..
107             } = conf
108             {
109                 diag.note(&format!("{} (from clippy.toml)", reason));
110             }
111         });
112     }
113 }