1 //! lint on inherent implementations
3 use crate::utils::{in_macro, span_lint_and_then};
5 use rustc::impl_lint_pass;
6 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
7 use rustc_data_structures::fx::FxHashMap;
8 use rustc_session::declare_tool_lint;
11 declare_clippy_lint! {
12 /// **What it does:** Checks for multiple inherent implementations of a struct
14 /// **Why is this bad?** Splitting the implementation of a type makes the code harder to navigate.
16 /// **Known problems:** None.
38 pub MULTIPLE_INHERENT_IMPL,
40 "Multiple inherent impl that could be grouped"
43 #[allow(clippy::module_name_repetitions)]
45 pub struct MultipleInherentImpl {
46 impls: FxHashMap<def_id::DefId, Span>,
49 impl_lint_pass!(MultipleInherentImpl => [MULTIPLE_INHERENT_IMPL]);
51 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MultipleInherentImpl {
52 fn check_item(&mut self, _: &LateContext<'a, 'tcx>, item: &'tcx Item) {
53 if let ItemKind::Impl(_, _, _, ref generics, None, _, _) = item.kind {
54 // Remember for each inherent implementation encoutered its span and generics
55 // but filter out implementations that have generic params (type or lifetime)
56 // or are derived from a macro
57 if !in_macro(item.span) && generics.params.len() == 0 {
58 self.impls.insert(item.hir_id.owner_def_id(), item.span);
63 fn check_crate_post(&mut self, cx: &LateContext<'a, 'tcx>, krate: &'tcx Crate) {
64 if let Some(item) = krate.items.values().nth(0) {
65 // Retrieve all inherent implementations from the crate, grouped by type
68 .crate_inherent_impls(item.hir_id.owner_def_id().krate)
72 // Filter out implementations that have generic params (type or lifetime)
73 let mut impl_spans = impls.iter().filter_map(|impl_def| self.impls.get(impl_def));
74 if let Some(initial_span) = impl_spans.nth(0) {
75 impl_spans.for_each(|additional_span| {
78 MULTIPLE_INHERENT_IMPL,
80 "Multiple implementations of this structure",
82 db.span_note(*initial_span, "First implementation here");