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