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