Skip to content

Commit dc1e409

Browse files
bors[bot]kennytm
andcommitted
Merge #3344
3344: Added lints `into_iter_on_ref` and `into_iter_on_array`. r=phansch a=kennytm Fixes #1565. `into_iter_on_array` is a correctness lint against `into_iter()` on `[T; n]` and `PathBuf` (please provide a concise noun that covers both types 🙃). `into_iter_on_ref` is a style lint against `into_iter()` on `&C` where `C` is `[T]`, `Vec<T>`, `BTreeSet<T>` etc. Both suggests replacing the `into_iter()` with `iter()` or `iter_mut()`. `into_iter_on_array` is a correctness lint since it is very likely the standard library would provide an `into_iter()` method for `[T; n]` (#25725) and existing type inference of `[a, b, c].into_iter()` will be broken. `PathBuf` is also placed under this lint since `PathBuf::into_iter` currently doesn't exist and it makes some sense to implement `IntoIterator` on it yielding `OsString`s. Co-authored-by: kennytm <[email protected]>
2 parents a8d2584 + 5563bd6 commit dc1e409

File tree

8 files changed

+350
-7
lines changed

8 files changed

+350
-7
lines changed

Diff for: 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

Diff for: 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 284 lints included in this crate!](https://rust-lang-nursery.github.io/rust-clippy/master/index.html)
12+
[There are 286 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

Diff for: clippy_lints/src/lib.rs

+4
Original file line numberDiff line numberDiff line change
@@ -628,6 +628,8 @@ pub fn register_plugins(reg: &mut rustc_plugin::Registry<'_>, conf: &Conf) {
628628
methods::EXPECT_FUN_CALL,
629629
methods::FILTER_NEXT,
630630
methods::GET_UNWRAP,
631+
methods::INTO_ITER_ON_ARRAY,
632+
methods::INTO_ITER_ON_REF,
631633
methods::ITER_CLONED_COLLECT,
632634
methods::ITER_NTH,
633635
methods::ITER_SKIP_NEXT,
@@ -784,6 +786,7 @@ pub fn register_plugins(reg: &mut rustc_plugin::Registry<'_>, conf: &Conf) {
784786
mem_replace::MEM_REPLACE_OPTION_WITH_NONE,
785787
methods::CHARS_LAST_CMP,
786788
methods::GET_UNWRAP,
789+
methods::INTO_ITER_ON_REF,
787790
methods::ITER_CLONED_COLLECT,
788791
methods::ITER_SKIP_NEXT,
789792
methods::NEW_RET_NO_SELF,
@@ -935,6 +938,7 @@ pub fn register_plugins(reg: &mut rustc_plugin::Registry<'_>, conf: &Conf) {
935938
loops::WHILE_IMMUTABLE_CONDITION,
936939
mem_discriminant::MEM_DISCRIMINANT_NON_ENUM,
937940
methods::CLONE_DOUBLE_REF,
941+
methods::INTO_ITER_ON_ARRAY,
938942
methods::TEMPORARY_CSTRING_AS_PTR,
939943
minmax::MIN_MAX,
940944
misc::CMP_NAN,

Diff for: clippy_lints/src/literal_representation.rs

+3-3
Original file line numberDiff line numberDiff line change
@@ -210,7 +210,7 @@ impl<'a> DigitInfo<'a> {
210210
.filter(|&c| c != '_')
211211
.collect::<Vec<_>>()
212212
.chunks(group_size)
213-
.map(|chunk| chunk.into_iter().rev().collect())
213+
.map(|chunk| chunk.iter().rev().collect())
214214
.rev()
215215
.collect::<Vec<String>>()
216216
.join("_");
@@ -221,7 +221,7 @@ impl<'a> DigitInfo<'a> {
221221
.filter(|&c| c != '_')
222222
.collect::<Vec<_>>()
223223
.chunks(group_size)
224-
.map(|chunk| chunk.into_iter().collect())
224+
.map(|chunk| chunk.iter().collect())
225225
.collect::<Vec<String>>()
226226
.join("_");
227227
format!(
@@ -238,7 +238,7 @@ impl<'a> DigitInfo<'a> {
238238
.collect::<Vec<_>>();
239239
let mut hint = filtered_digits_vec
240240
.chunks(group_size)
241-
.map(|chunk| chunk.into_iter().rev().collect())
241+
.map(|chunk| chunk.iter().rev().collect())
242242
.rev()
243243
.collect::<Vec<String>>()
244244
.join("_");

Diff for: clippy_lints/src/methods/mod.rs

+117-2
Original file line numberDiff line numberDiff line change
@@ -575,7 +575,7 @@ declare_clippy_lint! {
575575
/// temporary placeholder for dealing with the `Option` type, then this does
576576
/// not mitigate the need for error handling. If there is a chance that `.get()`
577577
/// will be `None` in your program, then it is advisable that the `None` case
578-
/// is handled in a future refactor instead of using `.unwrap()` or the Index
578+
/// is handled in a future refactor instead of using `.unwrap()` or the Index
579579
/// trait.
580580
///
581581
/// **Example:**
@@ -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. Auto-referencing resolves the `into_iter` call to its reference
753+
/// instead, like `<&[T; N] as IntoIterator>::into_iter`, which just iterates over item references
754+
/// like calling `iter` would. Furthermore, when the standard library actually
755+
/// [implements the `into_iter` method][25725] which moves the content out of the array, the
756+
/// original use of `into_iter` got inferred with the wrong type and the code will 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+
// FIXME: instead of this hard-coded list, we should check if `<adt>::iter`
2139+
// exists and has the desired signature. Unfortunately FnCtxt is not exported
2140+
// so we can't use its `lookup_method` method.
2141+
static INTO_ITER_COLLECTIONS: [(&Lint, &[&str]); 13] = [
2142+
(INTO_ITER_ON_REF, &paths::VEC),
2143+
(INTO_ITER_ON_REF, &paths::OPTION),
2144+
(INTO_ITER_ON_REF, &paths::RESULT),
2145+
(INTO_ITER_ON_REF, &paths::BTREESET),
2146+
(INTO_ITER_ON_REF, &paths::BTREEMAP),
2147+
(INTO_ITER_ON_REF, &paths::VEC_DEQUE),
2148+
(INTO_ITER_ON_REF, &paths::LINKED_LIST),
2149+
(INTO_ITER_ON_REF, &paths::BINARY_HEAP),
2150+
(INTO_ITER_ON_REF, &paths::HASHSET),
2151+
(INTO_ITER_ON_REF, &paths::HASHMAP),
2152+
(INTO_ITER_ON_ARRAY, &["std", "path", "PathBuf"]),
2153+
(INTO_ITER_ON_REF, &["std", "path", "Path"]),
2154+
(INTO_ITER_ON_REF, &["std", "sync", "mpsc", "Receiver"]),
2155+
];
2156+
2157+
let (self_ty, mutbl) = match self_ref_ty.sty {
2158+
ty::TyKind::Ref(_, self_ty, mutbl) => (self_ty, mutbl),
2159+
_ => unreachable!(),
2160+
};
2161+
let method_name = match mutbl {
2162+
hir::MutImmutable => "iter",
2163+
hir::MutMutable => "iter_mut",
2164+
};
2165+
2166+
let def_id = match self_ty.sty {
2167+
ty::TyKind::Array(..) => return Some((INTO_ITER_ON_ARRAY, "array", method_name)),
2168+
ty::TyKind::Slice(..) => return Some((INTO_ITER_ON_REF, "slice", method_name)),
2169+
ty::Adt(adt, _) => adt.did,
2170+
_ => return None,
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 {

Diff for: 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

Diff for: 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)