rust-clippy/clippy_lints/src/inherent_impl.rs

91 lines
3 KiB
Rust
Raw Normal View History

//! lint on inherent implementations
2019-09-28 01:46:55 +00:00
use crate::utils::{in_macro, span_lint_and_then};
use rustc::hir::*;
2019-12-03 23:16:03 +00:00
use rustc::impl_lint_pass;
use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
use rustc_data_structures::fx::FxHashMap;
2019-12-03 23:16:03 +00:00
use rustc_session::declare_tool_lint;
2019-12-31 00:17:56 +00:00
use rustc_span::Span;
declare_clippy_lint! {
/// **What it does:** Checks for multiple inherent implementations of a struct
///
/// **Why is this bad?** Splitting the implementation of a type makes the code harder to navigate.
///
/// **Known problems:** None.
///
/// **Example:**
/// ```rust
/// struct X;
/// impl X {
/// fn one() {}
/// }
/// impl X {
/// fn other() {}
/// }
/// ```
///
/// Could be written:
///
/// ```rust
/// struct X;
/// impl X {
/// fn one() {}
/// fn other() {}
/// }
/// ```
pub MULTIPLE_INHERENT_IMPL,
2018-05-29 08:19:16 +00:00
restriction,
"Multiple inherent impl that could be grouped"
}
2019-04-08 20:43:55 +00:00
#[allow(clippy::module_name_repetitions)]
#[derive(Default)]
pub struct MultipleInherentImpl {
impls: FxHashMap<def_id::DefId, Span>,
}
2019-04-08 20:43:55 +00:00
impl_lint_pass!(MultipleInherentImpl => [MULTIPLE_INHERENT_IMPL]);
2019-04-08 20:43:55 +00:00
impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MultipleInherentImpl {
2019-12-22 14:42:41 +00:00
fn check_item(&mut self, _: &LateContext<'a, 'tcx>, item: &'tcx Item<'_>) {
2019-09-27 15:16:06 +00:00
if let ItemKind::Impl(_, _, _, ref generics, None, _, _) = item.kind {
// Remember for each inherent implementation encoutered its span and generics
// but filter out implementations that have generic params (type or lifetime)
2019-09-28 01:46:55 +00:00
// or are derived from a macro
if !in_macro(item.span) && generics.params.len() == 0 {
self.impls.insert(item.hir_id.owner_def_id(), item.span);
}
}
}
2019-12-22 14:42:41 +00:00
fn check_crate_post(&mut self, cx: &LateContext<'a, 'tcx>, krate: &'tcx Crate<'_>) {
if let Some(item) = krate.items.values().nth(0) {
// Retrieve all inherent implementations from the crate, grouped by type
for impls in cx
.tcx
.crate_inherent_impls(item.hir_id.owner_def_id().krate)
.inherent_impls
.values()
{
// Filter out implementations that have generic params (type or lifetime)
let mut impl_spans = impls.iter().filter_map(|impl_def| self.impls.get(impl_def));
if let Some(initial_span) = impl_spans.nth(0) {
impl_spans.for_each(|additional_span| {
2018-08-28 11:13:42 +00:00
span_lint_and_then(
cx,
MULTIPLE_INHERENT_IMPL,
*additional_span,
"Multiple implementations of this structure",
2018-08-28 11:13:42 +00:00
|db| {
2018-11-27 20:14:15 +00:00
db.span_note(*initial_span, "First implementation here");
2018-08-28 11:13:42 +00:00
},
)
})
}
}
}
}
}