]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/copy_iterator.rs
Auto merge of #3597 - xfix:match-ergonomics, r=phansch
[rust.git] / clippy_lints / src / copy_iterator.rs
1 // Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution.
3 //
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.
9
10 use crate::utils::{is_copy, match_path, paths, span_note_and_lint};
11 use rustc::hir::{Item, ItemKind};
12 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
13 use rustc::{declare_tool_lint, lint_array};
14
15 /// **What it does:** Checks for types that implement `Copy` as well as
16 /// `Iterator`.
17 ///
18 /// **Why is this bad?** Implicit copies can be confusing when working with
19 /// iterator combinators.
20 ///
21 /// **Known problems:** None.
22 ///
23 /// **Example:**
24 /// ```rust
25 /// #[derive(Copy, Clone)]
26 /// struct Countdown(u8);
27 ///
28 /// impl Iterator for Countdown {
29 ///     // ...
30 /// }
31 ///
32 /// let a: Vec<_> = my_iterator.take(1).collect();
33 /// let b: Vec<_> = my_iterator.collect();
34 /// ```
35 declare_clippy_lint! {
36     pub COPY_ITERATOR,
37     pedantic,
38     "implementing `Iterator` on a `Copy` type"
39 }
40
41 pub struct CopyIterator;
42
43 impl LintPass for CopyIterator {
44     fn get_lints(&self) -> LintArray {
45         lint_array![COPY_ITERATOR]
46     }
47 }
48
49 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for CopyIterator {
50     fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item) {
51         if let ItemKind::Impl(_, _, _, _, Some(ref trait_ref), _, _) = item.node {
52             let ty = cx.tcx.type_of(cx.tcx.hir().local_def_id(item.id));
53
54             if is_copy(cx, ty) && match_path(&trait_ref.path, &paths::ITERATOR) {
55                 span_note_and_lint(
56                     cx,
57                     COPY_ITERATOR,
58                     item.span,
59                     "you are implementing `Iterator` on a `Copy` type",
60                     item.span,
61                     "consider implementing `IntoIterator` instead",
62                 );
63             }
64         }
65     }
66 }