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::{AssocItemKind, HirId, ImplItemKind, ImplItemRef, Item, ItemKind, Path};
5 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
6 use rustc::{declare_lint_pass, declare_tool_lint};
8 use crate::utils::span_help_and_lint;
10 declare_clippy_lint! {
11 /// **What it does:** Checks methods that contain a `self` argument but don't use it
13 /// **Why is this bad?** It may be clearer to define the method as an associated function instead
14 /// of an instance method if it doesn't require `self`.
16 /// **Known problems:** None.
22 /// fn method(&self) {}
36 "methods that contain a `self` argument but don't use it"
39 declare_lint_pass!(UnusedSelf => [UNUSED_SELF]);
41 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnusedSelf {
42 fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &Item) {
43 if item.span.from_expansion() {
46 if let ItemKind::Impl(_, _, _, _, None, _, ref impl_item_refs) = item.kind {
47 for impl_item_ref in impl_item_refs {
50 kind: AssocItemKind::Method { has_self: true },
53 let impl_item = cx.tcx.hir().impl_item(impl_item_ref.id);
54 if let ImplItemKind::Method(_, body_id) = &impl_item.kind;
56 let body = cx.tcx.hir().body(*body_id);
57 let self_param = &body.params[0];
58 let self_hir_id = self_param.pat.hir_id;
59 let mut visitor = UnusedSelfVisitor {
62 self_hir_id: &self_hir_id,
64 visitor.visit_body(body);
65 if !visitor.uses_self {
70 "unused `self` argument",
71 "consider refactoring to a associated function",
81 struct UnusedSelfVisitor<'a, 'tcx> {
82 cx: &'a LateContext<'a, 'tcx>,
84 self_hir_id: &'a HirId,
87 impl<'a, 'tcx> Visitor<'tcx> for UnusedSelfVisitor<'a, 'tcx> {
88 fn visit_path(&mut self, path: &'tcx Path, _id: HirId) {
90 // This function already uses `self`
93 if let Res::Local(hir_id) = &path.res {
94 self.uses_self = self.self_hir_id == hir_id
96 walk_path(self, path);
99 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
100 NestedVisitorMap::OnlyBodies(&self.cx.tcx.hir())