]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/disallowed_methods.rs
Auto merge of #107843 - bjorn3:sync_cg_clif-2023-02-09, r=bjorn3
[rust.git] / src / tools / clippy / 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_id::DefIdMap;
5 use rustc_hir::{Expr, ExprKind};
6 use rustc_lint::{LateContext, LateLintPass};
7 use rustc_session::{declare_tool_lint, impl_lint_pass};
8
9 use crate::utils::conf;
10
11 declare_clippy_lint! {
12     /// ### What it does
13     /// Denies the configured methods and functions in clippy.toml
14     ///
15     /// Note: Even though this lint is warn-by-default, it will only trigger if
16     /// methods are defined in the clippy.toml file.
17     ///
18     /// ### Why is this bad?
19     /// Some methods are undesirable in certain contexts, and it's beneficial to
20     /// lint for them as needed.
21     ///
22     /// ### Example
23     /// An example clippy.toml configuration:
24     /// ```toml
25     /// # clippy.toml
26     /// disallowed-methods = [
27     ///     # Can use a string as the path of the disallowed method.
28     ///     "std::boxed::Box::new",
29     ///     # Can also use an inline table with a `path` key.
30     ///     { path = "std::time::Instant::now" },
31     ///     # When using an inline table, can add a `reason` for why the method
32     ///     # is disallowed.
33     ///     { path = "std::vec::Vec::leak", reason = "no leaking memory" },
34     /// ]
35     /// ```
36     ///
37     /// ```rust,ignore
38     /// // Example code where clippy issues a warning
39     /// let xs = vec![1, 2, 3, 4];
40     /// xs.leak(); // Vec::leak is disallowed in the config.
41     /// // The diagnostic contains the message "no leaking memory".
42     ///
43     /// let _now = Instant::now(); // Instant::now is disallowed in the config.
44     ///
45     /// let _box = Box::new(3); // Box::new is disallowed in the config.
46     /// ```
47     ///
48     /// Use instead:
49     /// ```rust,ignore
50     /// // Example code which does not raise clippy warning
51     /// let mut xs = Vec::new(); // Vec::new is _not_ disallowed in the config.
52     /// xs.push(123); // Vec::push is _not_ disallowed in the config.
53     /// ```
54     #[clippy::version = "1.49.0"]
55     pub DISALLOWED_METHODS,
56     style,
57     "use of a disallowed method call"
58 }
59
60 #[derive(Clone, Debug)]
61 pub struct DisallowedMethods {
62     conf_disallowed: Vec<conf::DisallowedPath>,
63     disallowed: DefIdMap<usize>,
64 }
65
66 impl DisallowedMethods {
67     pub fn new(conf_disallowed: Vec<conf::DisallowedPath>) -> Self {
68         Self {
69             conf_disallowed,
70             disallowed: DefIdMap::default(),
71         }
72     }
73 }
74
75 impl_lint_pass!(DisallowedMethods => [DISALLOWED_METHODS]);
76
77 impl<'tcx> LateLintPass<'tcx> for DisallowedMethods {
78     fn check_crate(&mut self, cx: &LateContext<'_>) {
79         for (index, conf) in self.conf_disallowed.iter().enumerate() {
80             let segs: Vec<_> = conf.path().split("::").collect();
81             for id in clippy_utils::def_path_def_ids(cx, &segs) {
82                 self.disallowed.insert(id, index);
83             }
84         }
85     }
86
87     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
88         let uncalled_path = if let Some(parent) = get_parent_expr(cx, expr)
89             && let ExprKind::Call(receiver, _) = parent.kind
90             && receiver.hir_id == expr.hir_id
91         {
92             None
93         } else {
94             path_def_id(cx, expr)
95         };
96         let Some(def_id) = uncalled_path.or_else(|| fn_def_id(cx, expr)) else {
97             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 Some(reason) = conf.reason() {
106                 diag.note(reason);
107             }
108         });
109     }
110 }