1 //! lint on inherent implementations
3 use crate::utils::span_lint_and_then;
5 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
6 use rustc::{declare_tool_lint, lint_array};
7 use rustc_data_structures::fx::FxHashMap;
8 use std::default::Default;
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 declare_clippy_lint! {
38 pub MULTIPLE_INHERENT_IMPL,
40 "Multiple inherent impl that could be grouped"
44 impls: FxHashMap<def_id::DefId, (Span, Generics)>,
47 impl Default for Pass {
48 fn default() -> Self {
50 impls: FxHashMap::default(),
55 impl LintPass for Pass {
56 fn get_lints(&self) -> LintArray {
57 lint_array!(MULTIPLE_INHERENT_IMPL)
61 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
62 fn check_item(&mut self, _: &LateContext<'a, 'tcx>, item: &'tcx Item) {
63 if let ItemKind::Impl(_, _, _, ref generics, None, _, _) = item.node {
64 // Remember for each inherent implementation encoutered its span and generics
66 .insert(item.hir_id.owner_def_id(), (item.span, generics.clone()));
70 fn check_crate_post(&mut self, cx: &LateContext<'a, 'tcx>, krate: &'tcx Crate) {
71 if let Some(item) = krate.items.values().nth(0) {
72 // Retrieve all inherent implementations from the crate, grouped by type
75 .crate_inherent_impls(item.hir_id.owner_def_id().krate)
79 // Filter out implementations that have generic params (type or lifetime)
80 let mut impl_spans = impls
82 .filter_map(|impl_def| self.impls.get(impl_def))
83 .filter_map(|(span, generics)| if generics.params.len() == 0 { Some(span) } else { None });
84 if let Some(initial_span) = impl_spans.nth(0) {
85 impl_spans.for_each(|additional_span| {
88 MULTIPLE_INHERENT_IMPL,
90 "Multiple implementations of this structure",
92 db.span_note(*initial_span, "First implementation here");