rust-clippy/clippy_lints/src/unused_self.rs

68 lines
2.1 KiB
Rust
Raw Normal View History

use clippy_utils::diagnostics::span_lint_and_help;
use clippy_utils::visitors::is_local_used;
2019-10-03 19:09:32 +00:00
use if_chain::if_chain;
use rustc_hir::{Impl, ImplItem, ImplItemKind, ItemKind};
2020-01-12 06:08:41 +00:00
use rustc_lint::{LateContext, LateLintPass};
2020-01-11 11:37:08 +00:00
use rustc_session::{declare_lint_pass, declare_tool_lint};
2019-10-03 19:09:32 +00:00
declare_clippy_lint! {
/// ### What it does
/// Checks methods that contain a `self` argument but don't use it
2019-10-03 19:09:32 +00:00
///
/// ### Why is this bad?
/// It may be clearer to define the method as an associated function instead
2019-10-03 19:09:32 +00:00
/// of an instance method if it doesn't require `self`.
///
/// ### Example
2019-10-03 19:09:32 +00:00
/// ```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"]
2019-10-03 19:09:32 +00:00
pub UNUSED_SELF,
2019-10-04 17:18:52 +00:00
pedantic,
2019-10-03 19:09:32 +00:00
"methods that contain a `self` argument but don't use it"
}
declare_lint_pass!(UnusedSelf => [UNUSED_SELF]);
impl<'tcx> LateLintPass<'tcx> for UnusedSelf {
fn check_impl_item(&mut self, cx: &LateContext<'tcx>, impl_item: &ImplItem<'_>) {
if impl_item.span.from_expansion() {
2019-10-03 19:09:32 +00:00
return;
}
let parent = cx.tcx.hir().get_parent_item(impl_item.hir_id());
2020-03-29 20:22:28 +00:00
let parent_item = cx.tcx.hir().expect_item(parent);
let assoc_item = cx.tcx.associated_item(impl_item.def_id);
2020-03-29 20:22:28 +00:00
if_chain! {
if let ItemKind::Impl(Impl { of_trait: None, .. }) = parent_item.kind;
if assoc_item.fn_has_self_parameter;
2020-03-29 20:22:28 +00:00
if let ImplItemKind::Fn(.., body_id) = &impl_item.kind;
let body = cx.tcx.hir().body(*body_id);
if let [self_param, ..] = body.params;
if !is_local_used(cx, body, self_param.pat.hir_id);
2020-03-29 20:22:28 +00:00
then {
span_lint_and_help(
cx,
UNUSED_SELF,
self_param.span,
"unused `self` argument",
None,
"consider refactoring to a associated function",
);
2019-10-03 19:09:32 +00:00
}
2020-03-29 20:22:28 +00:00
}
2019-10-03 19:09:32 +00:00
}
}