]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/disallowed_method.rs
run cargo dev fmt
[rust.git] / clippy_lints / src / disallowed_method.rs
1 use crate::utils::span_lint;
2
3 use rustc_data_structures::fx::FxHashSet;
4 use rustc_hir::*;
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
20     /// // example code where clippy issues a warning
21     /// foo.bad_method(); // Foo is disallowed
22     /// ```
23     /// Use instead:
24     /// ```rust
25     /// // example code which does not raise clippy warning
26     /// GoodStruct.bad_method(); // not disallowed
27     /// ```
28     pub DISALLOWED_METHOD,
29     nursery,
30     "used 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                 span_lint(
59                     cx,
60                     DISALLOWED_METHOD,
61                     expr.span,
62                     &format!(
63                         "Use of a disallowed method `{}`",
64                         method_call
65                             .iter()
66                             .map(|s| s.to_ident_string())
67                             .collect::<Vec<_>>()
68                             .join("::"),
69                     ),
70                 );
71             }
72         }
73     }
74 }