]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/copy_iterator.rs
Auto merge of #6859 - magurotuna:if_then_some_else_none, r=giraffate
[rust.git] / clippy_lints / src / copy_iterator.rs
1 use crate::utils::{is_copy, span_lint_and_note};
2 use rustc_hir::{Impl, Item, ItemKind};
3 use rustc_lint::{LateContext, LateLintPass};
4 use rustc_session::{declare_lint_pass, declare_tool_lint};
5 use rustc_span::sym;
6
7 use if_chain::if_chain;
8
9 declare_clippy_lint! {
10     /// **What it does:** Checks for types that implement `Copy` as well as
11     /// `Iterator`.
12     ///
13     /// **Why is this bad?** Implicit copies can be confusing when working with
14     /// iterator combinators.
15     ///
16     /// **Known problems:** None.
17     ///
18     /// **Example:**
19     /// ```rust,ignore
20     /// #[derive(Copy, Clone)]
21     /// struct Countdown(u8);
22     ///
23     /// impl Iterator for Countdown {
24     ///     // ...
25     /// }
26     ///
27     /// let a: Vec<_> = my_iterator.take(1).collect();
28     /// let b: Vec<_> = my_iterator.collect();
29     /// ```
30     pub COPY_ITERATOR,
31     pedantic,
32     "implementing `Iterator` on a `Copy` type"
33 }
34
35 declare_lint_pass!(CopyIterator => [COPY_ITERATOR]);
36
37 impl<'tcx> LateLintPass<'tcx> for CopyIterator {
38     fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) {
39         if_chain! {
40             if let ItemKind::Impl(Impl {
41                 of_trait: Some(ref trait_ref),
42                 ..
43             }) = item.kind;
44             let ty = cx.tcx.type_of(item.def_id);
45             if is_copy(cx, ty);
46             if let Some(trait_id) = trait_ref.trait_def_id();
47             if cx.tcx.is_diagnostic_item(sym::Iterator, trait_id);
48             then {
49                 span_lint_and_note(
50                     cx,
51                     COPY_ITERATOR,
52                     item.span,
53                     "you are implementing `Iterator` on a `Copy` type",
54                     None,
55                     "consider implementing `IntoIterator` instead",
56                 );
57             }
58         }
59     }
60 }