]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/copy_iterator.rs
rustup https://github.com/rust-lang/rust/pull/57726
[rust.git] / clippy_lints / src / copy_iterator.rs
1 use crate::utils::{is_copy, match_path, paths, span_note_and_lint};
2 use rustc::hir::{Item, ItemKind};
3 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
4 use rustc::{declare_tool_lint, lint_array};
5
6 /// **What it does:** Checks for types that implement `Copy` as well as
7 /// `Iterator`.
8 ///
9 /// **Why is this bad?** Implicit copies can be confusing when working with
10 /// iterator combinators.
11 ///
12 /// **Known problems:** None.
13 ///
14 /// **Example:**
15 /// ```rust
16 /// #[derive(Copy, Clone)]
17 /// struct Countdown(u8);
18 ///
19 /// impl Iterator for Countdown {
20 ///     // ...
21 /// }
22 ///
23 /// let a: Vec<_> = my_iterator.take(1).collect();
24 /// let b: Vec<_> = my_iterator.collect();
25 /// ```
26 declare_clippy_lint! {
27     pub COPY_ITERATOR,
28     pedantic,
29     "implementing `Iterator` on a `Copy` type"
30 }
31
32 pub struct CopyIterator;
33
34 impl LintPass for CopyIterator {
35     fn get_lints(&self) -> LintArray {
36         lint_array![COPY_ITERATOR]
37     }
38
39     fn name(&self) -> &'static str {
40         "CopyIterator"
41     }
42 }
43
44 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for CopyIterator {
45     fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item) {
46         if let ItemKind::Impl(_, _, _, _, Some(ref trait_ref), _, _) = item.node {
47             let ty = cx.tcx.type_of(cx.tcx.hir().local_def_id(item.id));
48
49             if is_copy(cx, ty) && match_path(&trait_ref.path, &paths::ITERATOR) {
50                 span_note_and_lint(
51                     cx,
52                     COPY_ITERATOR,
53                     item.span,
54                     "you are implementing `Iterator` on a `Copy` type",
55                     item.span,
56                     "consider implementing `IntoIterator` instead",
57                 );
58             }
59         }
60     }
61 }