]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/disallowed_methods.rs
Auto merge of #8210 - guerinoni:master, r=Manishearth
[rust.git] / clippy_lints / src / disallowed_methods.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     /// 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<Option<String>>,
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 conf in &self.conf_disallowed {
79             let (path, reason) = match conf {
80                 conf::DisallowedMethod::Simple(path) => (path, None),
81                 conf::DisallowedMethod::WithReason { path, reason } => (
82                     path,
83                     reason.as_ref().map(|reason| format!("{} (from clippy.toml)", reason)),
84                 ),
85             };
86             let segs: Vec<_> = path.split("::").collect();
87             if let Res::Def(_, id) = clippy_utils::path_to_res(cx, &segs) {
88                 self.disallowed.insert(id, reason);
89             }
90         }
91     }
92
93     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
94         let def_id = match fn_def_id(cx, expr) {
95             Some(def_id) => def_id,
96             None => return,
97         };
98         let reason = match self.disallowed.get(&def_id) {
99             Some(reason) => reason,
100             None => return,
101         };
102         let func_path = cx.tcx.def_path_str(def_id);
103         let msg = format!("use of a disallowed method `{}`", func_path);
104         span_lint_and_then(cx, DISALLOWED_METHODS, expr.span, &msg, |diag| {
105             if let Some(reason) = reason {
106                 diag.note(reason);
107             }
108         });
109     }
110 }