]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/disallowed_method.rs
5ecdcc0e08aa1d21051b2979a0eab39a2378355e
[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_lint::{LateLintPass, LateContext};
5 use rustc_session::{impl_lint_pass, declare_tool_lint};
6 use rustc_hir::*;
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.iter()
42                 .map(|s| {
43                     s.split("::").map(|seg| Symbol::intern(seg)).collect::<Vec<_>>()
44                 })
45                 .collect(),
46         }
47     }
48 }
49
50 impl_lint_pass!(DisallowedMethod => [DISALLOWED_METHOD]);
51
52 impl <'tcx> LateLintPass<'tcx> for DisallowedMethod {
53     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
54         if let ExprKind::MethodCall(_path, _, _args, _) = &expr.kind {
55             let def_id = cx.typeck_results().type_dependent_def_id(expr.hir_id).unwrap();
56
57             let method_call = cx.get_def_path(def_id);
58             if self.disallowed.contains(&method_call) {
59                 span_lint(
60                     cx,
61                     DISALLOWED_METHOD,
62                     expr.span,
63                     &format!(
64                         "Use of a disallowed method `{}`",
65                         method_call
66                             .iter()
67                             .map(|s| s.to_ident_string())
68                             .collect::<Vec<_>>()
69                             .join("::"),
70                     )
71                 );
72             }
73         }
74     }
75 }