-
Notifications
You must be signed in to change notification settings - Fork 2k
Expand file tree
/
Copy pathunused_self.rs
More file actions
80 lines (75 loc) · 2.48 KB
/
unused_self.rs
File metadata and controls
80 lines (75 loc) · 2.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
use clippy_config::Conf;
use clippy_utils::diagnostics::span_lint_and_help;
use clippy_utils::usage::is_todo_unimplemented_stub;
use clippy_utils::visitors::is_local_used;
use rustc_hir::{Impl, ImplItem, ImplItemKind, ItemKind};
use rustc_lint::{LateContext, LateLintPass};
use rustc_session::impl_lint_pass;
declare_clippy_lint! {
/// ### What it does
/// Checks methods that contain a `self` argument but don't use it
///
/// ### Why is this bad?
/// It may be clearer to define the method as an associated function instead
/// of an instance method if it doesn't require `self`.
///
/// ### Example
/// ```rust,ignore
/// struct A;
/// impl A {
/// fn method(&self) {}
/// }
/// ```
///
/// Could be written:
///
/// ```rust,ignore
/// struct A;
/// impl A {
/// fn method() {}
/// }
/// ```
#[clippy::version = "1.40.0"]
pub UNUSED_SELF,
pedantic,
"methods that contain a `self` argument but don't use it"
}
impl_lint_pass!(UnusedSelf => [UNUSED_SELF]);
pub struct UnusedSelf {
avoid_breaking_exported_api: bool,
}
impl UnusedSelf {
pub fn new(conf: &'static Conf) -> Self {
Self {
avoid_breaking_exported_api: conf.avoid_breaking_exported_api,
}
}
}
impl<'tcx> LateLintPass<'tcx> for UnusedSelf {
fn check_impl_item(&mut self, cx: &LateContext<'tcx>, impl_item: &ImplItem<'_>) {
if impl_item.span.from_expansion() {
return;
}
let parent = cx.tcx.hir_get_parent_item(impl_item.hir_id()).def_id;
let parent_item = cx.tcx.hir_expect_item(parent);
let assoc_item = cx.tcx.associated_item(impl_item.owner_id);
if let ItemKind::Impl(Impl { of_trait: None, .. }) = parent_item.kind
&& assoc_item.is_method()
&& let ImplItemKind::Fn(.., body_id) = &impl_item.kind
&& (!cx.effective_visibilities.is_exported(impl_item.owner_id.def_id) || !self.avoid_breaking_exported_api)
&& let body = cx.tcx.hir_body(*body_id)
&& let [self_param, ..] = body.params
&& !is_local_used(cx, body, self_param.pat.hir_id)
&& !is_todo_unimplemented_stub(cx, body.value)
{
span_lint_and_help(
cx,
UNUSED_SELF,
self_param.span,
"unused `self` argument",
None,
"consider refactoring to an associated function",
);
}
}
}