Skip to content

Commit 0d0483a

Browse files
committed
Added lints into_iter_on_ref and into_iter_on_array. Fix #1565.
1 parent 6256892 commit 0d0483a

File tree

7 files changed

+346
-3
lines changed

7 files changed

+346
-3
lines changed

CHANGELOG.md

+2
Original file line numberDiff line numberDiff line change
@@ -713,6 +713,8 @@ All notable changes to this project will be documented in this file.
713713
[`inline_fn_without_body`]: https://rust-lang-nursery.github.io/rust-clippy/master/index.html#inline_fn_without_body
714714
[`int_plus_one`]: https://rust-lang-nursery.github.io/rust-clippy/master/index.html#int_plus_one
715715
[`integer_arithmetic`]: https://rust-lang-nursery.github.io/rust-clippy/master/index.html#integer_arithmetic
716+
[`into_iter_on_array`]: https://rust-lang-nursery.github.io/rust-clippy/master/index.html#into_iter_on_array
717+
[`into_iter_on_ref`]: https://rust-lang-nursery.github.io/rust-clippy/master/index.html#into_iter_on_ref
716718
[`invalid_ref`]: https://rust-lang-nursery.github.io/rust-clippy/master/index.html#invalid_ref
717719
[`invalid_regex`]: https://rust-lang-nursery.github.io/rust-clippy/master/index.html#invalid_regex
718720
[`invalid_upcast_comparisons`]: https://rust-lang-nursery.github.io/rust-clippy/master/index.html#invalid_upcast_comparisons

README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ We are currently in the process of discussing Clippy 1.0 via the RFC process in
99

1010
A collection of lints to catch common mistakes and improve your [Rust](https://github.com/rust-lang/rust) code.
1111

12-
[There are 283 lints included in this crate!](https://rust-lang-nursery.github.io/rust-clippy/master/index.html)
12+
[There are 285 lints included in this crate!](https://rust-lang-nursery.github.io/rust-clippy/master/index.html)
1313

1414
We have a bunch of lint categories to allow you to choose how much Clippy is supposed to ~~annoy~~ help you:
1515

clippy_lints/src/lib.rs

+4
Original file line numberDiff line numberDiff line change
@@ -627,6 +627,8 @@ pub fn register_plugins(reg: &mut rustc_plugin::Registry<'_>, conf: &Conf) {
627627
methods::EXPECT_FUN_CALL,
628628
methods::FILTER_NEXT,
629629
methods::GET_UNWRAP,
630+
methods::INTO_ITER_ON_ARRAY,
631+
methods::INTO_ITER_ON_REF,
630632
methods::ITER_CLONED_COLLECT,
631633
methods::ITER_NTH,
632634
methods::ITER_SKIP_NEXT,
@@ -782,6 +784,7 @@ pub fn register_plugins(reg: &mut rustc_plugin::Registry<'_>, conf: &Conf) {
782784
mem_replace::MEM_REPLACE_OPTION_WITH_NONE,
783785
methods::CHARS_LAST_CMP,
784786
methods::GET_UNWRAP,
787+
methods::INTO_ITER_ON_REF,
785788
methods::ITER_CLONED_COLLECT,
786789
methods::ITER_SKIP_NEXT,
787790
methods::NEW_RET_NO_SELF,
@@ -933,6 +936,7 @@ pub fn register_plugins(reg: &mut rustc_plugin::Registry<'_>, conf: &Conf) {
933936
loops::WHILE_IMMUTABLE_CONDITION,
934937
mem_discriminant::MEM_DISCRIMINANT_NON_ENUM,
935938
methods::CLONE_DOUBLE_REF,
939+
methods::INTO_ITER_ON_ARRAY,
936940
methods::TEMPORARY_CSTRING_AS_PTR,
937941
minmax::MIN_MAX,
938942
misc::CMP_NAN,

clippy_lints/src/methods/mod.rs

+116-1
Original file line numberDiff line numberDiff line change
@@ -745,6 +745,51 @@ declare_clippy_lint! {
745745
"using `filter_map` when a more succinct alternative exists"
746746
}
747747

748+
/// **What it does:** Checks for `into_iter` calls on types which should be replaced by `iter` or
749+
/// `iter_mut`.
750+
///
751+
/// **Why is this bad?** Arrays and `PathBuf` do not yet have an `into_iter` method which move out
752+
/// their content into an iterator. Calling `into_iter` instead just forwards to `iter` or
753+
/// `iter_mut` due to auto-referencing, of which only yield references. Furthermore, when the
754+
/// standard library actually [implements the `into_iter` method][25725] which moves the content out
755+
/// of the array, the original use of `into_iter` got inferred with the wrong type and the code will
756+
/// be broken.
757+
///
758+
/// **Known problems:** None
759+
///
760+
/// **Example:**
761+
///
762+
/// ```rust
763+
/// let _ = [1, 2, 3].into_iter().map(|x| *x).collect::<Vec<u32>>();
764+
/// ```
765+
///
766+
/// [25725]: https://github.com/rust-lang/rust/issues/25725
767+
declare_clippy_lint! {
768+
pub INTO_ITER_ON_ARRAY,
769+
correctness,
770+
"using `.into_iter()` on an array"
771+
}
772+
773+
/// **What it does:** Checks for `into_iter` calls on references which should be replaced by `iter`
774+
/// or `iter_mut`.
775+
///
776+
/// **Why is this bad?** Readability. Calling `into_iter` on a reference will not move out its
777+
/// content into the resulting iterator, which is confusing. It is better just call `iter` or
778+
/// `iter_mut` directly.
779+
///
780+
/// **Known problems:** None
781+
///
782+
/// **Example:**
783+
///
784+
/// ```rust
785+
/// let _ = (&vec![3, 4, 5]).into_iter();
786+
/// ```
787+
declare_clippy_lint! {
788+
pub INTO_ITER_ON_REF,
789+
style,
790+
"using `.into_iter()` on a reference"
791+
}
792+
748793
impl LintPass for Pass {
749794
fn get_lints(&self) -> LintArray {
750795
lint_array!(
@@ -779,7 +824,9 @@ impl LintPass for Pass {
779824
ITER_CLONED_COLLECT,
780825
USELESS_ASREF,
781826
UNNECESSARY_FOLD,
782-
UNNECESSARY_FILTER_MAP
827+
UNNECESSARY_FILTER_MAP,
828+
INTO_ITER_ON_ARRAY,
829+
INTO_ITER_ON_REF,
783830
)
784831
}
785832
}
@@ -843,6 +890,9 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
843890
lint_single_char_pattern(cx, expr, &args[pos]);
844891
}
845892
},
893+
ty::Ref(..) if method_call.ident.name == "into_iter" => {
894+
lint_into_iter(cx, expr, self_ty, *method_span);
895+
},
846896
_ => (),
847897
}
848898
},
@@ -2084,6 +2134,71 @@ fn lint_asref(cx: &LateContext<'_, '_>, expr: &hir::Expr, call_name: &str, as_re
20842134
}
20852135
}
20862136

2137+
fn ty_has_iter_method(cx: &LateContext<'_, '_>, self_ref_ty: ty::Ty<'_>) -> Option<(&'static Lint, &'static str, &'static str)> {
2138+
let (self_ty, mutbl) = match self_ref_ty.sty {
2139+
ty::TyKind::Ref(_, self_ty, mutbl) => (self_ty, mutbl),
2140+
_ => unreachable!(),
2141+
};
2142+
let method_name = match mutbl {
2143+
hir::MutImmutable => "iter",
2144+
hir::MutMutable => "iter_mut",
2145+
};
2146+
2147+
let def_id = match self_ty.sty {
2148+
ty::TyKind::Array(..) => return Some((INTO_ITER_ON_ARRAY, "array", method_name)),
2149+
ty::TyKind::Slice(..) => return Some((INTO_ITER_ON_REF, "slice", method_name)),
2150+
ty::Adt(adt, _) => adt.did,
2151+
_ => return None,
2152+
};
2153+
2154+
// FIXME: instead of this hard-coded list, we should check if `<adt>::iter`
2155+
// exists and has the desired signature. Unfortunately FnCtxt is not exported
2156+
// so we can't use its `lookup_method` method.
2157+
static INTO_ITER_COLLECTIONS: [(&Lint, &[&str]); 13] = [
2158+
(INTO_ITER_ON_REF, &paths::VEC),
2159+
(INTO_ITER_ON_REF, &paths::OPTION),
2160+
(INTO_ITER_ON_REF, &paths::RESULT),
2161+
(INTO_ITER_ON_REF, &paths::BTREESET),
2162+
(INTO_ITER_ON_REF, &paths::BTREEMAP),
2163+
(INTO_ITER_ON_REF, &paths::VEC_DEQUE),
2164+
(INTO_ITER_ON_REF, &paths::LINKED_LIST),
2165+
(INTO_ITER_ON_REF, &paths::BINARY_HEAP),
2166+
(INTO_ITER_ON_REF, &paths::HASHSET),
2167+
(INTO_ITER_ON_REF, &paths::HASHMAP),
2168+
(INTO_ITER_ON_ARRAY, &["std", "path", "PathBuf"]),
2169+
(INTO_ITER_ON_REF, &["std", "path", "Path"]),
2170+
(INTO_ITER_ON_REF, &["std", "sync", "mpsc", "Receiver"]),
2171+
];
2172+
2173+
for (lint, path) in &INTO_ITER_COLLECTIONS {
2174+
if match_def_path(cx.tcx, def_id, path) {
2175+
return Some((lint, path.last().unwrap(), method_name))
2176+
}
2177+
}
2178+
None
2179+
}
2180+
2181+
fn lint_into_iter(cx: &LateContext<'_, '_>, expr: &hir::Expr, self_ref_ty: ty::Ty<'_>, method_span: Span) {
2182+
if !match_trait_method(cx, expr, &paths::INTO_ITERATOR) {
2183+
return;
2184+
}
2185+
if let Some((lint, kind, method_name)) = ty_has_iter_method(cx, self_ref_ty) {
2186+
span_lint_and_sugg(
2187+
cx,
2188+
lint,
2189+
method_span,
2190+
&format!(
2191+
"this .into_iter() call is equivalent to .{}() and will not move the {}",
2192+
method_name,
2193+
kind,
2194+
),
2195+
"call directly",
2196+
method_name.to_owned(),
2197+
);
2198+
}
2199+
}
2200+
2201+
20872202
/// Given a `Result<T, E>` type, return its error type (`E`).
20882203
fn get_error_type<'a>(cx: &LateContext<'_, '_>, ty: Ty<'a>) -> Option<Ty<'a>> {
20892204
if let ty::Adt(_, substs) = ty.sty {

tests/ui/for_loop.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ impl Unrelated {
2929
clippy::for_kv_map)]
3030
#[warn(clippy::unused_collect)]
3131
#[allow(clippy::linkedlist, clippy::shadow_unrelated, clippy::unnecessary_mut_passed, clippy::cyclomatic_complexity, clippy::similar_names)]
32-
#[allow(clippy::many_single_char_names, unused_variables)]
32+
#[allow(clippy::many_single_char_names, unused_variables, clippy::into_iter_on_array)]
3333
fn main() {
3434
const MAX_LEN: usize = 42;
3535

tests/ui/into_iter_on_ref.rs

+44
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
#![warn(clippy::into_iter_on_ref)]
2+
#![deny(clippy::into_iter_on_array)]
3+
4+
struct X;
5+
use std::collections::*;
6+
7+
fn main() {
8+
for _ in &[1,2,3] {}
9+
for _ in vec![X, X] {}
10+
for _ in &vec![X, X] {}
11+
for _ in [1,2,3].into_iter() {} //~ ERROR equivalent to .iter()
12+
13+
let _ = [1,2,3].into_iter(); //~ ERROR equivalent to .iter()
14+
let _ = vec![1,2,3].into_iter();
15+
let _ = (&vec![1,2,3]).into_iter(); //~ WARN equivalent to .iter()
16+
let _ = vec![1,2,3].into_boxed_slice().into_iter(); //~ WARN equivalent to .iter()
17+
let _ = std::rc::Rc::from(&[X][..]).into_iter(); //~ WARN equivalent to .iter()
18+
let _ = std::sync::Arc::from(&[X][..]).into_iter(); //~ WARN equivalent to .iter()
19+
20+
let _ = (&&&&&&&[1,2,3]).into_iter(); //~ ERROR equivalent to .iter()
21+
let _ = (&&&&mut &&&[1,2,3]).into_iter(); //~ ERROR equivalent to .iter()
22+
let _ = (&mut &mut &mut [1,2,3]).into_iter(); //~ ERROR equivalent to .iter_mut()
23+
24+
let _ = (&Some(4)).into_iter(); //~ WARN equivalent to .iter()
25+
let _ = (&mut Some(5)).into_iter(); //~ WARN equivalent to .iter_mut()
26+
let _ = (&Ok::<_, i32>(6)).into_iter(); //~ WARN equivalent to .iter()
27+
let _ = (&mut Err::<i32, _>(7)).into_iter(); //~ WARN equivalent to .iter_mut()
28+
let _ = (&Vec::<i32>::new()).into_iter(); //~ WARN equivalent to .iter()
29+
let _ = (&mut Vec::<i32>::new()).into_iter(); //~ WARN equivalent to .iter_mut()
30+
let _ = (&BTreeMap::<i32, u64>::new()).into_iter(); //~ WARN equivalent to .iter()
31+
let _ = (&mut BTreeMap::<i32, u64>::new()).into_iter(); //~ WARN equivalent to .iter_mut()
32+
let _ = (&VecDeque::<i32>::new()).into_iter(); //~ WARN equivalent to .iter()
33+
let _ = (&mut VecDeque::<i32>::new()).into_iter(); //~ WARN equivalent to .iter_mut()
34+
let _ = (&LinkedList::<i32>::new()).into_iter(); //~ WARN equivalent to .iter()
35+
let _ = (&mut LinkedList::<i32>::new()).into_iter(); //~ WARN equivalent to .iter_mut()
36+
let _ = (&HashMap::<i32, u64>::new()).into_iter(); //~ WARN equivalent to .iter()
37+
let _ = (&mut HashMap::<i32, u64>::new()).into_iter(); //~ WARN equivalent to .iter_mut()
38+
39+
let _ = (&BTreeSet::<i32>::new()).into_iter(); //~ WARN equivalent to .iter()
40+
let _ = (&BinaryHeap::<i32>::new()).into_iter(); //~ WARN equivalent to .iter()
41+
let _ = (&HashSet::<i32>::new()).into_iter(); //~ WARN equivalent to .iter()
42+
let _ = std::path::Path::new("12/34").into_iter(); //~ WARN equivalent to .iter()
43+
let _ = std::path::PathBuf::from("12/34").into_iter(); //~ ERROR equivalent to .iter()
44+
}

0 commit comments

Comments
 (0)