Auto merge of #12823 - schvv31n:fix-iter-on-empty-collections, r=y21

Suppress `iter_on_empty_collections` if the iterator's concrete type is relied upon

changelog: fixed #12807
This commit is contained in:
bors 2024-05-27 16:18:41 +00:00
commit 76eee82e79
4 changed files with 97 additions and 2 deletions

View file

@ -20,6 +20,28 @@ fn array() {
};
let _ = if false { ["test"].iter() } else { [].iter() };
let smth = Some(vec![1, 2, 3]);
// Don't trigger when the empty collection iter is relied upon for its concrete type
// But do trigger if it is just an iterator, despite being an argument to a method
for i in smth.as_ref().map_or([].iter(), |s| s.iter()).chain(std::iter::empty()) {
println!("{i}");
}
// Same as above, but for empty collection iters with extra layers
for i in smth.as_ref().map_or({ [].iter() }, |s| s.iter()) {
println!("{y}", y = i + 1);
}
// Same as above, but for regular function calls
for i in Option::map_or(smth.as_ref(), [].iter(), |s| s.iter()) {
println!("{i}");
}
// Same as above, but when there are no predicates that mention the collection iter type.
let mut iter = [34, 228, 35].iter();
let _ = std::mem::replace(&mut iter, [].iter());
}
macro_rules! in_macros {

View file

@ -20,6 +20,28 @@ fn array() {
};
let _ = if false { ["test"].iter() } else { [].iter() };
let smth = Some(vec![1, 2, 3]);
// Don't trigger when the empty collection iter is relied upon for its concrete type
// But do trigger if it is just an iterator, despite being an argument to a method
for i in smth.as_ref().map_or([].iter(), |s| s.iter()).chain([].iter()) {
println!("{i}");
}
// Same as above, but for empty collection iters with extra layers
for i in smth.as_ref().map_or({ [].iter() }, |s| s.iter()) {
println!("{y}", y = i + 1);
}
// Same as above, but for regular function calls
for i in Option::map_or(smth.as_ref(), [].iter(), |s| s.iter()) {
println!("{i}");
}
// Same as above, but when there are no predicates that mention the collection iter type.
let mut iter = [34, 228, 35].iter();
let _ = std::mem::replace(&mut iter, [].iter());
}
macro_rules! in_macros {

View file

@ -37,5 +37,11 @@ error: `iter` call on an empty collection
LL | assert_eq!(None.iter().next(), Option::<&i32>::None);
| ^^^^^^^^^^^ help: try: `std::iter::empty()`
error: aborting due to 6 previous errors
error: `iter` call on an empty collection
--> tests/ui/iter_on_empty_collections.rs:28:66
|
LL | for i in smth.as_ref().map_or([].iter(), |s| s.iter()).chain([].iter()) {
| ^^^^^^^^^ help: try: `std::iter::empty()`
error: aborting due to 7 previous errors