1 //! lint on inherent implementations
3 use clippy_utils::diagnostics::span_lint_and_note;
4 use clippy_utils::{in_macro, is_lint_allowed};
5 use rustc_data_structures::fx::FxHashMap;
6 use rustc_hir::{def_id::LocalDefId, Crate, Item, ItemKind, Node};
7 use rustc_lint::{LateContext, LateLintPass};
8 use rustc_session::{declare_lint_pass, declare_tool_lint};
10 use std::collections::hash_map::Entry;
12 declare_clippy_lint! {
14 /// Checks for multiple inherent implementations of a struct
16 /// ### Why is this bad?
17 /// Splitting the implementation of a type makes the code harder to navigate.
39 pub MULTIPLE_INHERENT_IMPL,
41 "Multiple inherent impl that could be grouped"
44 declare_lint_pass!(MultipleInherentImpl => [MULTIPLE_INHERENT_IMPL]);
46 impl<'tcx> LateLintPass<'tcx> for MultipleInherentImpl {
47 fn check_crate_post(&mut self, cx: &LateContext<'tcx>, _: &'tcx Crate<'_>) {
48 // Map from a type to it's first impl block. Needed to distinguish generic arguments.
49 // e.g. `Foo<Bar>` and `Foo<Baz>`
50 let mut type_map = FxHashMap::default();
51 // List of spans to lint. (lint_span, first_span)
52 let mut lint_spans = Vec::new();
54 for (_, impl_ids) in cx
56 .crate_inherent_impls(())
59 .filter(|(&id, impls)| {
61 // Check for `#[allow]` on the type definition
64 MULTIPLE_INHERENT_IMPL,
65 cx.tcx.hir().local_def_id_to_hir_id(id),
69 for impl_id in impl_ids.iter().map(|id| id.expect_local()) {
70 match type_map.entry(cx.tcx.type_of(impl_id)) {
72 // Store the id for the first impl block of this type. The span is retrieved lazily.
73 e.insert(IdOrSpan::Id(impl_id));
75 Entry::Occupied(mut e) => {
76 if let Some(span) = get_impl_span(cx, impl_id) {
77 let first_span = match *e.get() {
78 IdOrSpan::Span(s) => s,
80 if let Some(s) = get_impl_span(cx, id) {
81 // Remember the span of the first block.
82 *e.get_mut() = IdOrSpan::Span(s);
85 // The first impl block isn't considered by the lint. Replace it with the
87 *e.get_mut() = IdOrSpan::Span(span);
92 lint_spans.push((span, first_span));
98 // Switching to the next type definition, no need to keep the current entries around.
102 // `TyCtxt::crate_inherent_impls` doesn't have a defined order. Sort the lint output first.
103 lint_spans.sort_by_key(|x| x.0.lo());
104 for (span, first_span) in lint_spans {
107 MULTIPLE_INHERENT_IMPL,
109 "multiple implementations of this structure",
111 "first implementation here",
117 /// Gets the span for the given impl block unless it's not being considered by the lint.
118 fn get_impl_span(cx: &LateContext<'_>, id: LocalDefId) -> Option<Span> {
119 let id = cx.tcx.hir().local_def_id_to_hir_id(id);
120 if let Node::Item(&Item {
121 kind: ItemKind::Impl(ref impl_item),
124 }) = cx.tcx.hir().get(id)
126 (!in_macro(span) && impl_item.generics.params.is_empty() && !is_lint_allowed(cx, MULTIPLE_INHERENT_IMPL, id))