1 //! lint on inherent implementations
3 use crate::utils::{in_macro, span_lint_and_then};
4 use rustc_data_structures::fx::FxHashMap;
5 use rustc_hir::{def_id, Crate, Item, ItemKind};
6 use rustc_lint::{LateContext, LateLintPass};
7 use rustc_session::{declare_tool_lint, impl_lint_pass};
10 declare_clippy_lint! {
11 /// **What it does:** Checks for multiple inherent implementations of a struct
13 /// **Why is this bad?** Splitting the implementation of a type makes the code harder to navigate.
15 /// **Known problems:** None.
37 pub MULTIPLE_INHERENT_IMPL,
39 "Multiple inherent impl that could be grouped"
42 #[allow(clippy::module_name_repetitions)]
44 pub struct MultipleInherentImpl {
45 impls: FxHashMap<def_id::DefId, Span>,
48 impl_lint_pass!(MultipleInherentImpl => [MULTIPLE_INHERENT_IMPL]);
50 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MultipleInherentImpl {
51 fn check_item(&mut self, _: &LateContext<'a, 'tcx>, item: &'tcx Item<'_>) {
52 if let ItemKind::Impl {
58 // Remember for each inherent implementation encoutered its span and generics
59 // but filter out implementations that have generic params (type or lifetime)
60 // or are derived from a macro
61 if !in_macro(item.span) && generics.params.is_empty() {
62 self.impls.insert(item.hir_id.owner.to_def_id(), item.span);
67 fn check_crate_post(&mut self, cx: &LateContext<'a, 'tcx>, krate: &'tcx Crate<'_>) {
68 if let Some(item) = krate.items.values().next() {
69 // Retrieve all inherent implementations from the crate, grouped by type
72 .crate_inherent_impls(item.hir_id.owner.to_def_id().krate)
76 // Filter out implementations that have generic params (type or lifetime)
77 let mut impl_spans = impls.iter().filter_map(|impl_def| self.impls.get(impl_def));
78 if let Some(initial_span) = impl_spans.next() {
79 impl_spans.for_each(|additional_span| {
82 MULTIPLE_INHERENT_IMPL,
84 "Multiple implementations of this structure",
86 diag.span_note(*initial_span, "First implementation here");