2018-11-27 20:14:15 +00:00
|
|
|
use crate::utils::{is_copy, match_path, paths, span_note_and_lint};
|
2018-12-29 15:04:45 +00:00
|
|
|
use rustc::hir::{Item, ItemKind};
|
|
|
|
use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
|
|
|
|
use rustc::{declare_tool_lint, lint_array};
|
2018-07-17 17:22:55 +00:00
|
|
|
|
|
|
|
/// **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
|
|
|
|
/// #[derive(Copy, Clone)]
|
|
|
|
/// struct Countdown(u8);
|
|
|
|
///
|
|
|
|
/// impl Iterator for Countdown {
|
|
|
|
/// // ...
|
|
|
|
/// }
|
|
|
|
///
|
|
|
|
/// let a: Vec<_> = my_iterator.take(1).collect();
|
|
|
|
/// let b: Vec<_> = my_iterator.collect();
|
|
|
|
/// ```
|
|
|
|
declare_clippy_lint! {
|
|
|
|
pub COPY_ITERATOR,
|
|
|
|
pedantic,
|
|
|
|
"implementing `Iterator` on a `Copy` type"
|
|
|
|
}
|
|
|
|
|
|
|
|
pub struct CopyIterator;
|
|
|
|
|
|
|
|
impl LintPass for CopyIterator {
|
|
|
|
fn get_lints(&self) -> LintArray {
|
|
|
|
lint_array![COPY_ITERATOR]
|
|
|
|
}
|
2019-01-26 19:40:55 +00:00
|
|
|
|
|
|
|
fn name(&self) -> &'static str {
|
|
|
|
"CopyIterator"
|
|
|
|
}
|
2018-07-17 17:22:55 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
impl<'a, 'tcx> LateLintPass<'a, 'tcx> for CopyIterator {
|
|
|
|
fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item) {
|
|
|
|
if let ItemKind::Impl(_, _, _, _, Some(ref trait_ref), _, _) = item.node {
|
2018-12-08 00:56:03 +00:00
|
|
|
let ty = cx.tcx.type_of(cx.tcx.hir().local_def_id(item.id));
|
2018-07-17 17:22:55 +00:00
|
|
|
|
|
|
|
if is_copy(cx, ty) && match_path(&trait_ref.path, &paths::ITERATOR) {
|
|
|
|
span_note_and_lint(
|
|
|
|
cx,
|
|
|
|
COPY_ITERATOR,
|
|
|
|
item.span,
|
|
|
|
"you are implementing `Iterator` on a `Copy` type",
|
|
|
|
item.span,
|
|
|
|
"consider implementing `IntoIterator` instead",
|
|
|
|
);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|