1 // Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution.
4 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
7 // option. This file may not be copied, modified, or distributed
8 // except according to those terms.
11 //! lint on inherent implementations
13 use crate::rustc::hir::*;
14 use crate::rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
15 use crate::rustc::{declare_tool_lint, lint_array};
16 use crate::rustc_data_structures::fx::FxHashMap;
17 use std::default::Default;
18 use crate::syntax_pos::Span;
19 use crate::utils::span_lint_and_then;
21 /// **What it does:** Checks for multiple inherent implementations of a struct
23 /// **Why is this bad?** Splitting the implementation of a type makes the code harder to navigate.
25 /// **Known problems:** None.
47 declare_clippy_lint! {
48 pub MULTIPLE_INHERENT_IMPL,
50 "Multiple inherent impl that could be grouped"
54 impls: FxHashMap<def_id::DefId, (Span, Generics)>,
57 impl Default for Pass {
58 fn default() -> Self {
59 Self { impls: FxHashMap::default() }
63 impl LintPass for Pass {
64 fn get_lints(&self) -> LintArray {
65 lint_array!(MULTIPLE_INHERENT_IMPL)
69 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
70 fn check_item(&mut self, _: &LateContext<'a, 'tcx>, item: &'tcx Item) {
71 if let ItemKind::Impl(_, _, _, ref generics, None, _, _) = item.node {
72 // Remember for each inherent implementation encoutered its span and generics
74 .insert(item.hir_id.owner_def_id(), (item.span, generics.clone()));
78 fn check_crate_post(&mut self, cx: &LateContext<'a, 'tcx>, krate: &'tcx Crate) {
79 if let Some(item) = krate.items.values().nth(0) {
80 // Retrieve all inherent implementations from the crate, grouped by type
83 .crate_inherent_impls(item.hir_id.owner_def_id().krate)
87 // Filter out implementations that have generic params (type or lifetime)
88 let mut impl_spans = impls
90 .filter_map(|impl_def| self.impls.get(impl_def))
91 .filter_map(|(span, generics)| if generics.params.len() == 0 {
96 if let Some(initial_span) = impl_spans.nth(0) {
97 impl_spans.for_each(|additional_span| {
100 MULTIPLE_INHERENT_IMPL,
102 "Multiple implementations of this structure",
106 "First implementation here",