rust-clippy/clippy_lints/src/copy_iterator.rs

52 lines
1.6 KiB
Rust
Raw Normal View History

2018-11-27 20:14:15 +00:00
use crate::utils::{is_copy, match_path, paths, span_note_and_lint};
2020-01-06 16:39:50 +00:00
use rustc_hir::{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};
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<'a, 'tcx> LateLintPass<'a, 'tcx> for CopyIterator {
2019-12-22 14:42:41 +00:00
fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item<'_>) {
2019-09-27 15:16:06 +00:00
if let ItemKind::Impl(_, _, _, _, Some(ref trait_ref), _, _) = item.kind {
let ty = cx.tcx.type_of(cx.tcx.hir().local_def_id(item.hir_id));
2018-07-17 17:22:55 +00:00
2019-05-17 21:53:54 +00:00
if is_copy(cx, ty) && match_path(&trait_ref.path, &paths::ITERATOR) {
2018-07-17 17:22:55 +00:00
span_note_and_lint(
cx,
COPY_ITERATOR,
item.span,
"you are implementing `Iterator` on a `Copy` type",
item.span,
"consider implementing `IntoIterator` instead",
);
}
}
}
}