1 use if_chain::if_chain;
2 use rustc_hir::def::Res;
3 use rustc_hir::intravisit::{walk_path, NestedVisitorMap, Visitor};
4 use rustc_hir::{HirId, Impl, ImplItem, ImplItemKind, ItemKind, Path};
5 use rustc_lint::{LateContext, LateLintPass};
6 use rustc_middle::hir::map::Map;
7 use rustc_session::{declare_lint_pass, declare_tool_lint};
9 use crate::utils::span_lint_and_help;
11 declare_clippy_lint! {
12 /// **What it does:** Checks methods that contain a `self` argument but don't use it
14 /// **Why is this bad?** It may be clearer to define the method as an associated function instead
15 /// of an instance method if it doesn't require `self`.
17 /// **Known problems:** None.
23 /// fn method(&self) {}
37 "methods that contain a `self` argument but don't use it"
40 declare_lint_pass!(UnusedSelf => [UNUSED_SELF]);
42 impl<'tcx> LateLintPass<'tcx> for UnusedSelf {
43 fn check_impl_item(&mut self, cx: &LateContext<'tcx>, impl_item: &ImplItem<'_>) {
44 if impl_item.span.from_expansion() {
47 let parent = cx.tcx.hir().get_parent_item(impl_item.hir_id);
48 let parent_item = cx.tcx.hir().expect_item(parent);
49 let def_id = cx.tcx.hir().local_def_id(impl_item.hir_id);
50 let assoc_item = cx.tcx.associated_item(def_id);
52 if let ItemKind::Impl(Impl { of_trait: None, .. }) = parent_item.kind;
53 if assoc_item.fn_has_self_parameter;
54 if let ImplItemKind::Fn(.., body_id) = &impl_item.kind;
55 let body = cx.tcx.hir().body(*body_id);
56 if !body.params.is_empty();
58 let self_param = &body.params[0];
59 let self_hir_id = self_param.pat.hir_id;
60 let mut visitor = UnusedSelfVisitor {
63 self_hir_id: &self_hir_id,
65 visitor.visit_body(body);
66 if !visitor.uses_self {
71 "unused `self` argument",
73 "consider refactoring to a associated function",
82 struct UnusedSelfVisitor<'a, 'tcx> {
83 cx: &'a LateContext<'tcx>,
85 self_hir_id: &'a HirId,
88 impl<'a, 'tcx> Visitor<'tcx> for UnusedSelfVisitor<'a, 'tcx> {
91 fn visit_path(&mut self, path: &'tcx Path<'_>, _id: HirId) {
93 // This function already uses `self`
96 if let Res::Local(hir_id) = &path.res {
97 self.uses_self = self.self_hir_id == hir_id
99 walk_path(self, path);
102 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
103 NestedVisitorMap::OnlyBodies(self.cx.tcx.hir())