Skip to content

Commit 9698e41

Browse files
committed
Change explicit_counter_loop's message to add parentheses if necessary
1 parent bd6c2df commit 9698e41

File tree

3 files changed

+23
-4
lines changed

3 files changed

+23
-4
lines changed

clippy_lints/src/loops.rs

+5-1
Original file line numberDiff line numberDiff line change
@@ -1499,7 +1499,11 @@ fn check_for_loop_explicit_counter<'a, 'tcx>(
14991499
{1}) in {2}.enumerate()` or similar iterators",
15001500
name,
15011501
snippet(cx, pat.span, "_"),
1502-
snippet(cx, arg.span, "_")
1502+
if higher::range(cx, arg).is_some() {
1503+
format!("({})", snippet(cx, arg.span, "_"))
1504+
} else {
1505+
format!("{}", sugg::Sugg::hir(cx, arg, "_").maybe_par())
1506+
}
15031507
),
15041508
);
15051509
}

tests/ui/explicit_counter_loop.rs

+9
Original file line numberDiff line numberDiff line change
@@ -113,3 +113,12 @@ mod issue_3308 {
113113
}
114114
}
115115
}
116+
117+
mod issue_1670 {
118+
pub fn test() {
119+
let mut count = 0;
120+
for _i in 3..10 {
121+
count += 1;
122+
}
123+
}
124+
}

tests/ui/explicit_counter_loop.stderr

+9-3
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,12 @@
1-
error: the variable `_index` is used as a loop counter. Consider using `for (_index, _v) in &vec.enumerate()` or similar iterators
1+
error: the variable `_index` is used as a loop counter. Consider using `for (_index, _v) in (&vec).enumerate()` or similar iterators
22
--> $DIR/explicit_counter_loop.rs:6:15
33
|
44
LL | for _v in &vec {
55
| ^^^^
66
|
77
= note: `-D clippy::explicit-counter-loop` implied by `-D warnings`
88

9-
error: the variable `_index` is used as a loop counter. Consider using `for (_index, _v) in &vec.enumerate()` or similar iterators
9+
error: the variable `_index` is used as a loop counter. Consider using `for (_index, _v) in (&vec).enumerate()` or similar iterators
1010
--> $DIR/explicit_counter_loop.rs:12:15
1111
|
1212
LL | for _v in &vec {
@@ -24,5 +24,11 @@ error: the variable `count` is used as a loop counter. Consider using `for (coun
2424
LL | for ch in text.chars() {
2525
| ^^^^^^^^^^^^
2626

27-
error: aborting due to 4 previous errors
27+
error: the variable `count` is used as a loop counter. Consider using `for (count, _i) in (3..10).enumerate()` or similar iterators
28+
--> $DIR/explicit_counter_loop.rs:120:19
29+
|
30+
LL | for _i in 3..10 {
31+
| ^^^^^
32+
33+
error: aborting due to 5 previous errors
2834

0 commit comments

Comments
 (0)