rust-clippy/clippy_lints/src/copy_iterator.rs

62 lines
1.8 KiB
Rust
Raw Normal View History

use clippy_utils::diagnostics::span_lint_and_note;
2021-03-13 23:01:03 +00:00
use clippy_utils::ty::is_copy;
use rustc_hir::{Impl, Item, ItemKind};
2020-01-12 06:08:41 +00:00
use rustc_lint::{LateContext, LateLintPass};
2020-01-11 11:37:08 +00:00
use rustc_session::{declare_lint_pass, declare_tool_lint};
use rustc_span::sym;
use if_chain::if_chain;
2018-07-17 17:22:55 +00:00
declare_clippy_lint! {
/// **What it does:** Checks for types that implement `Copy` as well as
/// `Iterator`.
///
/// **Why is this bad?** Implicit copies can be confusing when working with
/// iterator combinators.
///
/// **Known problems:** None.
///
/// **Example:**
/// ```rust,ignore
/// #[derive(Copy, Clone)]
/// struct Countdown(u8);
///
/// impl Iterator for Countdown {
/// // ...
/// }
///
/// let a: Vec<_> = my_iterator.take(1).collect();
/// let b: Vec<_> = my_iterator.collect();
/// ```
2018-07-17 17:22:55 +00:00
pub COPY_ITERATOR,
pedantic,
"implementing `Iterator` on a `Copy` type"
}
2019-04-08 20:43:55 +00:00
declare_lint_pass!(CopyIterator => [COPY_ITERATOR]);
2018-07-17 17:22:55 +00:00
impl<'tcx> LateLintPass<'tcx> for CopyIterator {
fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) {
if_chain! {
if let ItemKind::Impl(Impl {
of_trait: Some(ref trait_ref),
..
}) = item.kind;
let ty = cx.tcx.type_of(item.def_id);
if is_copy(cx, ty);
if let Some(trait_id) = trait_ref.trait_def_id();
if cx.tcx.is_diagnostic_item(sym::Iterator, trait_id);
then {
span_lint_and_note(
2018-07-17 17:22:55 +00:00
cx,
COPY_ITERATOR,
item.span,
"you are implementing `Iterator` on a `Copy` type",
None,
2018-07-17 17:22:55 +00:00
"consider implementing `IntoIterator` instead",
);
}
}
}
}