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