2020-01-27 02:26:42 +00:00
|
|
|
use crate::utils::{is_copy, match_path, paths, span_lint_and_note};
|
2021-01-15 09:02:28 +00:00
|
|
|
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};
|
2018-07-17 17:22:55 +00:00
|
|
|
|
|
|
|
declare_clippy_lint! {
|
2019-03-05 16:50:33 +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:**
|
2019-08-03 16:42:05 +00:00
|
|
|
/// ```rust,ignore
|
2019-03-05 16:50:33 +00:00
|
|
|
/// #[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
|
|
|
|
2020-06-25 20:41:36 +00:00
|
|
|
impl<'tcx> LateLintPass<'tcx> for CopyIterator {
|
|
|
|
fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) {
|
2020-11-22 22:46:21 +00:00
|
|
|
if let ItemKind::Impl(Impl {
|
2020-01-18 05:14:36 +00:00
|
|
|
of_trait: Some(ref trait_ref),
|
|
|
|
..
|
2020-11-22 22:46:21 +00:00
|
|
|
}) = item.kind
|
2020-01-18 05:14:36 +00:00
|
|
|
{
|
2019-07-06 03:52:51 +00:00
|
|
|
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) {
|
2020-01-27 02:26:42 +00:00
|
|
|
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",
|
2020-04-18 10:29:36 +00:00
|
|
|
None,
|
2018-07-17 17:22:55 +00:00
|
|
|
"consider implementing `IntoIterator` instead",
|
|
|
|
);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|