1 use if_chain::if_chain;
2 use rustc::hir::map::Map;
3 use rustc_hir::def::Res;
4 use rustc_hir::intravisit::{walk_path, NestedVisitorMap, Visitor};
5 use rustc_hir::{AssocItemKind, HirId, ImplItem, ImplItemKind, ImplItemRef, ItemKind, Path};
6 use rustc_lint::{LateContext, LateLintPass};
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<'a, 'tcx> LateLintPass<'a, 'tcx> for UnusedSelf {
43 fn check_impl_item(&mut self, cx: &LateContext<'a, '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 item = cx.tcx.hir().expect_item(parent);
49 if let ItemKind::Impl {
51 items: impl_item_refs,
55 for impl_item_ref in impl_item_refs {
58 kind: AssocItemKind::Method { has_self: true },
61 if let ImplItemKind::Method(_, body_id) = &impl_item.kind;
62 let body = cx.tcx.hir().body(*body_id);
63 if !body.params.is_empty();
65 let self_param = &body.params[0];
66 let self_hir_id = self_param.pat.hir_id;
67 let mut visitor = UnusedSelfVisitor {
70 self_hir_id: &self_hir_id,
72 visitor.visit_body(body);
73 if !visitor.uses_self {
78 "unused `self` argument",
79 "consider refactoring to a associated function",
90 struct UnusedSelfVisitor<'a, 'tcx> {
91 cx: &'a LateContext<'a, 'tcx>,
93 self_hir_id: &'a HirId,
96 impl<'a, 'tcx> Visitor<'tcx> for UnusedSelfVisitor<'a, 'tcx> {
99 fn visit_path(&mut self, path: &'tcx Path<'_>, _id: HirId) {
101 // This function already uses `self`
104 if let Res::Local(hir_id) = &path.res {
105 self.uses_self = self.self_hir_id == hir_id
107 walk_path(self, path);
110 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
111 NestedVisitorMap::OnlyBodies(self.cx.tcx.hir())