]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/disallowed_method.rs
Auto merge of #77727 - thomcc:mach-info-order, r=Amanieu
[rust.git] / src / tools / clippy / clippy_lints / src / disallowed_method.rs
1 use crate::utils::span_lint;
2
3 use rustc_data_structures::fx::FxHashSet;
4 use rustc_hir::{Expr, ExprKind};
5 use rustc_lint::{LateContext, LateLintPass};
6 use rustc_session::{declare_tool_lint, impl_lint_pass};
7 use rustc_span::Symbol;
8
9 declare_clippy_lint! {
10     /// **What it does:** Lints for specific trait methods defined in clippy.toml
11     ///
12     /// **Why is this bad?** Some methods are undesirable in certain contexts,
13     /// and it would be beneficial to lint for them as needed.
14     ///
15     /// **Known problems:** None.
16     ///
17     /// **Example:**
18     ///
19     /// ```rust,ignore
20     /// // example code where clippy issues a warning
21     /// foo.bad_method(); // Foo::bad_method is disallowed in the configuration
22     /// ```
23     /// Use instead:
24     /// ```rust,ignore
25     /// // example code which does not raise clippy warning
26     /// goodStruct.bad_method(); // GoodStruct::bad_method is not disallowed
27     /// ```
28     pub DISALLOWED_METHOD,
29     nursery,
30     "use of a disallowed method call"
31 }
32
33 #[derive(Clone, Debug)]
34 pub struct DisallowedMethod {
35     disallowed: FxHashSet<Vec<Symbol>>,
36 }
37
38 impl DisallowedMethod {
39     pub fn new(disallowed: &FxHashSet<String>) -> Self {
40         Self {
41             disallowed: disallowed
42                 .iter()
43                 .map(|s| s.split("::").map(|seg| Symbol::intern(seg)).collect::<Vec<_>>())
44                 .collect(),
45         }
46     }
47 }
48
49 impl_lint_pass!(DisallowedMethod => [DISALLOWED_METHOD]);
50
51 impl<'tcx> LateLintPass<'tcx> for DisallowedMethod {
52     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
53         if let ExprKind::MethodCall(_path, _, _args, _) = &expr.kind {
54             let def_id = cx.typeck_results().type_dependent_def_id(expr.hir_id).unwrap();
55
56             let method_call = cx.get_def_path(def_id);
57             if self.disallowed.contains(&method_call) {
58                 let method = method_call
59                     .iter()
60                     .map(|s| s.to_ident_string())
61                     .collect::<Vec<_>>()
62                     .join("::");
63
64                 span_lint(
65                     cx,
66                     DISALLOWED_METHOD,
67                     expr.span,
68                     &format!("use of a disallowed method `{}`", method),
69                 );
70             }
71         }
72     }
73 }