1 //! lint on inherent implementations
2
3 use clippy_utils::diagnostics::span_lint_and_note;
4 use clippy_utils::is_lint_allowed;
5 use rustc_data_structures::fx::FxHashMap;
6 use rustc_hir::{def_id::LocalDefId, Item, ItemKind, Node};
7 use rustc_lint::{LateContext, LateLintPass};
8 use rustc_session::{declare_lint_pass, declare_tool_lint};
9 use rustc_span::Span;
10 use std::collections::hash_map::Entry;
11
12 declare_clippy_lint! {
13 /// ### What it does
14 /// Checks for multiple inherent implementations of a struct
15 ///
16 /// ### Why is this bad?
17 /// Splitting the implementation of a type makes the code harder to navigate.
18 ///
19 /// ### Example
20 /// ```rust
21 /// struct X;
22 /// impl X {
23 /// fn one() {}
24 /// }
25 /// impl X {
26 /// fn other() {}
27 /// }
28 /// ```
29 ///
30 /// Could be written:
31 ///
32 /// ```rust
33 /// struct X;
34 /// impl X {
35 /// fn one() {}
36 /// fn other() {}
37 /// }
38 /// ```
39 #[clippy::version = "pre 1.29.0"]
40 pub MULTIPLE_INHERENT_IMPL,
41 restriction,
42 "Multiple inherent impl that could be grouped"
43 }
44
45 declare_lint_pass!(MultipleInherentImpl => [MULTIPLE_INHERENT_IMPL]);
46
47 impl<'tcx> LateLintPass<'tcx> for MultipleInherentImpl {
check_crate_post(&mut self, cx: &LateContext<'tcx>)48 fn check_crate_post(&mut self, cx: &LateContext<'tcx>) {
49 // Map from a type to it's first impl block. Needed to distinguish generic arguments.
50 // e.g. `Foo<Bar>` and `Foo<Baz>`
51 let mut type_map = FxHashMap::default();
52 // List of spans to lint. (lint_span, first_span)
53 let mut lint_spans = Vec::new();
54
55 let inherent_impls = cx
56 .tcx
57 .with_stable_hashing_context(|hcx| cx.tcx.crate_inherent_impls(()).inherent_impls.to_sorted(&hcx, true));
58
59 for (_, impl_ids) in inherent_impls.into_iter().filter(|(&id, impls)| {
60 impls.len() > 1
61 // Check for `#[allow]` on the type definition
62 && !is_lint_allowed(
63 cx,
64 MULTIPLE_INHERENT_IMPL,
65 cx.tcx.hir().local_def_id_to_hir_id(id),
66 )
67 }) {
68 for impl_id in impl_ids.iter().map(|id| id.expect_local()) {
69 let impl_ty = cx.tcx.type_of(impl_id).subst_identity();
70 match type_map.entry(impl_ty) {
71 Entry::Vacant(e) => {
72 // Store the id for the first impl block of this type. The span is retrieved lazily.
73 e.insert(IdOrSpan::Id(impl_id));
74 },
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,
79 IdOrSpan::Id(id) => {
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);
83 s
84 } else {
85 // The first impl block isn't considered by the lint. Replace it with the
86 // current one.
87 *e.get_mut() = IdOrSpan::Span(span);
88 continue;
89 }
90 },
91 };
92 lint_spans.push((span, first_span));
93 }
94 },
95 }
96 }
97
98 // Switching to the next type definition, no need to keep the current entries around.
99 type_map.clear();
100 }
101
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 {
105 span_lint_and_note(
106 cx,
107 MULTIPLE_INHERENT_IMPL,
108 span,
109 "multiple implementations of this structure",
110 Some(first_span),
111 "first implementation here",
112 );
113 }
114 }
115 }
116
117 /// Gets the span for the given impl block unless it's not being considered by the lint.
get_impl_span(cx: &LateContext<'_>, id: LocalDefId) -> Option<Span>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(impl_item),
122 span,
123 ..
124 }) = cx.tcx.hir().get(id)
125 {
126 (!span.from_expansion()
127 && impl_item.generics.params.is_empty()
128 && !is_lint_allowed(cx, MULTIPLE_INHERENT_IMPL, id))
129 .then_some(span)
130 } else {
131 None
132 }
133 }
134
135 enum IdOrSpan {
136 Id(LocalDefId),
137 Span(Span),
138 }
139