]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/disallowed_method.rs
Rollup merge of #88860 - nbdd0121:panic, r=m-ou-se
[rust.git] / clippy_lints / src / disallowed_method.rs
1 use clippy_utils::diagnostics::span_lint_and_then;
2 use clippy_utils::fn_def_id;
3
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};
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     /// ### Why is this bad?
15     /// Some methods are undesirable in certain contexts, and it's beneficial to
16     /// lint for them as needed.
17     ///
18     /// ### Example
19     /// An example clippy.toml configuration:
20     /// ```toml
21     /// # clippy.toml
22     /// disallowed-methods = [
23     ///     # Can use a string as the path of the disallowed method.
24     ///     "std::boxed::Box::new",
25     ///     # Can also use an inline table with a `path` key.
26     ///     { path = "std::time::Instant::now" },
27     ///     # When using an inline table, can add a `reason` for why the method
28     ///     # is disallowed.
29     ///     { path = "std::vec::Vec::leak", reason = "no leaking memory" },
30     /// ]
31     /// ```
32     ///
33     /// ```rust,ignore
34     /// // Example code where clippy issues a warning
35     /// let xs = vec![1, 2, 3, 4];
36     /// xs.leak(); // Vec::leak is disallowed in the config.
37     /// // The diagnostic contains the message "no leaking memory".
38     ///
39     /// let _now = Instant::now(); // Instant::now is disallowed in the config.
40     ///
41     /// let _box = Box::new(3); // Box::new is disallowed in the config.
42     /// ```
43     ///
44     /// Use instead:
45     /// ```rust,ignore
46     /// // Example code which does not raise clippy warning
47     /// let mut xs = Vec::new(); // Vec::new is _not_ disallowed in the config.
48     /// xs.push(123); // Vec::push is _not_ disallowed in the config.
49     /// ```
50     pub DISALLOWED_METHOD,
51     nursery,
52     "use of a disallowed method call"
53 }
54
55 #[derive(Clone, Debug)]
56 pub struct DisallowedMethod {
57     conf_disallowed: Vec<conf::DisallowedMethod>,
58     disallowed: DefIdMap<Option<String>>,
59 }
60
61 impl DisallowedMethod {
62     pub fn new(conf_disallowed: Vec<conf::DisallowedMethod>) -> Self {
63         Self {
64             conf_disallowed,
65             disallowed: DefIdMap::default(),
66         }
67     }
68 }
69
70 impl_lint_pass!(DisallowedMethod => [DISALLOWED_METHOD]);
71
72 impl<'tcx> LateLintPass<'tcx> for DisallowedMethod {
73     fn check_crate(&mut self, cx: &LateContext<'_>) {
74         for conf in &self.conf_disallowed {
75             let (path, reason) = match conf {
76                 conf::DisallowedMethod::Simple(path) => (path, None),
77                 conf::DisallowedMethod::WithReason { path, reason } => (
78                     path,
79                     reason.as_ref().map(|reason| format!("{} (from clippy.toml)", reason)),
80                 ),
81             };
82             let segs: Vec<_> = path.split("::").collect();
83             if let Res::Def(_, id) = clippy_utils::path_to_res(cx, &segs) {
84                 self.disallowed.insert(id, reason);
85             }
86         }
87     }
88
89     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
90         let def_id = match fn_def_id(cx, expr) {
91             Some(def_id) => def_id,
92             None => return,
93         };
94         let reason = match self.disallowed.get(&def_id) {
95             Some(reason) => reason,
96             None => return,
97         };
98         let func_path = cx.tcx.def_path_str(def_id);
99         let msg = format!("use of a disallowed method `{}`", func_path);
100         span_lint_and_then(cx, DISALLOWED_METHOD, expr.span, &msg, |diag| {
101             if let Some(reason) = reason {
102                 diag.note(reason);
103             }
104         });
105     }
106 }