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.
10 //! lint on inherent implementations
12 use crate::utils::span_lint_and_then;
14 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
15 use rustc::{declare_tool_lint, lint_array};
16 use rustc_data_structures::fx::FxHashMap;
17 use std::default::Default;
20 /// **What it does:** Checks for multiple inherent implementations of a struct
22 /// **Why is this bad?** Splitting the implementation of a type makes the code harder to navigate.
24 /// **Known problems:** None.
46 declare_clippy_lint! {
47 pub MULTIPLE_INHERENT_IMPL,
49 "Multiple inherent impl that could be grouped"
53 impls: FxHashMap<def_id::DefId, (Span, Generics)>,
56 impl Default for Pass {
57 fn default() -> Self {
59 impls: FxHashMap::default(),
64 impl LintPass for Pass {
65 fn get_lints(&self) -> LintArray {
66 lint_array!(MULTIPLE_INHERENT_IMPL)
70 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
71 fn check_item(&mut self, _: &LateContext<'a, 'tcx>, item: &'tcx Item) {
72 if let ItemKind::Impl(_, _, _, ref generics, None, _, _) = item.node {
73 // Remember for each inherent implementation encoutered its span and generics
75 .insert(item.hir_id.owner_def_id(), (item.span, generics.clone()));
79 fn check_crate_post(&mut self, cx: &LateContext<'a, 'tcx>, krate: &'tcx Crate) {
80 if let Some(item) = krate.items.values().nth(0) {
81 // Retrieve all inherent implementations from the crate, grouped by type
84 .crate_inherent_impls(item.hir_id.owner_def_id().krate)
88 // Filter out implementations that have generic params (type or lifetime)
89 let mut impl_spans = impls
91 .filter_map(|impl_def| self.impls.get(impl_def))
92 .filter_map(|(span, generics)| if generics.params.len() == 0 { Some(span) } else { None });
93 if let Some(initial_span) = impl_spans.nth(0) {
94 impl_spans.for_each(|additional_span| {
97 MULTIPLE_INHERENT_IMPL,
99 "Multiple implementations of this structure",
101 db.span_note(*initial_span, "First implementation here");