]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/copy_iterator.rs
resolved conflicts
[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
40 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for CopyIterator {
41     fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item) {
42         if let ItemKind::Impl(_, _, _, _, Some(ref trait_ref), _, _) = item.node {
43             let ty = cx.tcx.type_of(cx.tcx.hir.local_def_id(item.id));
44
45             if is_copy(cx, ty) && match_path(&trait_ref.path, &paths::ITERATOR) {
46                 span_note_and_lint(
47                     cx,
48                     COPY_ITERATOR,
49                     item.span,
50                     "you are implementing `Iterator` on a `Copy` type",
51                     item.span,
52                     "consider implementing `IntoIterator` instead",
53                 );
54             }
55         }
56     }
57 }