]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/unused_self.rs
Merge remote-tracking branch 'upstream/master' into rustup
[rust.git] / clippy_lints / src / unused_self.rs
1 use if_chain::if_chain;
2 use rustc_hir::{Impl, ImplItem, ImplItemKind, ItemKind};
3 use rustc_lint::{LateContext, LateLintPass};
4 use rustc_session::{declare_lint_pass, declare_tool_lint};
5
6 use crate::utils::span_lint_and_help;
7 use crate::utils::visitors::LocalUsedVisitor;
8
9 declare_clippy_lint! {
10     /// **What it does:** Checks methods that contain a `self` argument but don't use it
11     ///
12     /// **Why is this bad?** It may be clearer to define the method as an associated function instead
13     /// of an instance method if it doesn't require `self`.
14     ///
15     /// **Known problems:** None.
16     ///
17     /// **Example:**
18     /// ```rust,ignore
19     /// struct A;
20     /// impl A {
21     ///     fn method(&self) {}
22     /// }
23     /// ```
24     ///
25     /// Could be written:
26     ///
27     /// ```rust,ignore
28     /// struct A;
29     /// impl A {
30     ///     fn method() {}
31     /// }
32     /// ```
33     pub UNUSED_SELF,
34     pedantic,
35     "methods that contain a `self` argument but don't use it"
36 }
37
38 declare_lint_pass!(UnusedSelf => [UNUSED_SELF]);
39
40 impl<'tcx> LateLintPass<'tcx> for UnusedSelf {
41     fn check_impl_item(&mut self, cx: &LateContext<'tcx>, impl_item: &ImplItem<'_>) {
42         if impl_item.span.from_expansion() {
43             return;
44         }
45         let parent = cx.tcx.hir().get_parent_item(impl_item.hir_id);
46         let parent_item = cx.tcx.hir().expect_item(parent);
47         let def_id = cx.tcx.hir().local_def_id(impl_item.hir_id);
48         let assoc_item = cx.tcx.associated_item(def_id);
49         if_chain! {
50             if let ItemKind::Impl(Impl { of_trait: None, .. }) = parent_item.kind;
51             if assoc_item.fn_has_self_parameter;
52             if let ImplItemKind::Fn(.., body_id) = &impl_item.kind;
53             let body = cx.tcx.hir().body(*body_id);
54             if !body.params.is_empty();
55             then {
56                 let self_param = &body.params[0];
57                 let self_hir_id = self_param.pat.hir_id;
58                 if !LocalUsedVisitor::new(cx, self_hir_id).check_body(body) {
59                     span_lint_and_help(
60                         cx,
61                         UNUSED_SELF,
62                         self_param.span,
63                         "unused `self` argument",
64                         None,
65                         "consider refactoring to a associated function",
66                     );
67                     return;
68                 }
69             }
70         }
71     }
72 }