Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix replacing for loops over ranges with for_each. #10139

Merged
merged 2 commits into from
Sep 3, 2021
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 42 additions & 5 deletions crates/ide_assists/src/handlers/replace_for_loop_with_for_each.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,14 +50,15 @@ pub(crate) fn replace_for_loop_with_for_each(acc: &mut Assists, ctx: &AssistCont
// We have either "for x in &col" and col implements a method called iter
// or "for x in &mut col" and col implements a method called iter_mut
format_to!(buf, "{}.{}()", expr_behind_ref, method);
} else if matches!(iterable, ast::Expr::RangeExpr(..)) {
yotamofek marked this conversation as resolved.
Show resolved Hide resolved
// range expressions need to be parenthesized for the syntax to be correct
format_to!(buf, "({})", iterable);
} else if impls_core_iter(&ctx.sema, &iterable) {
format_to!(buf, "{}", iterable);
} else if let ast::Expr::RefExpr(_) = iterable {
format_to!(buf, "({}).into_iter()", iterable);
} else {
if let ast::Expr::RefExpr(_) = iterable {
format_to!(buf, "({}).into_iter()", iterable);
} else {
format_to!(buf, "{}.into_iter()", iterable);
}
format_to!(buf, "{}.into_iter()", iterable);
}

format_to!(buf, ".for_each(|{}| {});", pat, body);
Expand Down Expand Up @@ -167,6 +168,42 @@ fn main() {
)
}

#[test]
fn test_for_in_range() {
check_assist(
replace_for_loop_with_for_each,
r#"
//- minicore: range, iterators
impl<T> core::iter::Iterator for core::ops::Range<T> {
type Item = T;

fn next(&mut self) -> Option<Self::Item> {
None
}
}

fn main() {
for $0x in 0..92 {
print!("{}", x);
}
}"#,
r#"
impl<T> core::iter::Iterator for core::ops::Range<T> {
type Item = T;

fn next(&mut self) -> Option<Self::Item> {
None
}
}

fn main() {
(0..92).for_each(|x| {
print!("{}", x);
});
}"#,
)
}

#[test]
fn not_available_in_body() {
cov_mark::check!(not_available_in_body);
Expand Down