]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/copy_iterator.rs
Rollup merge of #4332 - phansch:rustfix_unnecessary_cast, r=flip1995
[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_lint_pass, declare_tool_lint};
5
6 declare_clippy_lint! {
7     /// **What it does:** Checks for types that implement `Copy` as well as
8     /// `Iterator`.
9     ///
10     /// **Why is this bad?** Implicit copies can be confusing when working with
11     /// iterator combinators.
12     ///
13     /// **Known problems:** None.
14     ///
15     /// **Example:**
16     /// ```rust,ignore
17     /// #[derive(Copy, Clone)]
18     /// struct Countdown(u8);
19     ///
20     /// impl Iterator for Countdown {
21     ///     // ...
22     /// }
23     ///
24     /// let a: Vec<_> = my_iterator.take(1).collect();
25     /// let b: Vec<_> = my_iterator.collect();
26     /// ```
27     pub COPY_ITERATOR,
28     pedantic,
29     "implementing `Iterator` on a `Copy` type"
30 }
31
32 declare_lint_pass!(CopyIterator => [COPY_ITERATOR]);
33
34 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for CopyIterator {
35     fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item) {
36         if let ItemKind::Impl(_, _, _, _, Some(ref trait_ref), _, _) = item.node {
37             let ty = cx.tcx.type_of(cx.tcx.hir().local_def_id(item.hir_id));
38
39             if is_copy(cx, ty) && match_path(&trait_ref.path, &paths::ITERATOR) {
40                 span_note_and_lint(
41                     cx,
42                     COPY_ITERATOR,
43                     item.span,
44                     "you are implementing `Iterator` on a `Copy` type",
45                     item.span,
46                     "consider implementing `IntoIterator` instead",
47                 );
48             }
49         }
50     }
51 }