2 mod explicit_counter_loop;
3 mod explicit_into_iter_loop;
4 mod explicit_iter_loop;
6 mod for_loops_over_fallibles;
12 mod needless_range_loop;
15 mod single_element_loop;
17 mod while_immutable_condition;
19 mod while_let_on_iterator;
21 use clippy_utils::higher;
22 use rustc_hir::{Expr, ExprKind, LoopSource, Pat};
23 use rustc_lint::{LateContext, LateLintPass};
24 use rustc_session::{declare_lint_pass, declare_tool_lint};
25 use rustc_span::source_map::Span;
26 use utils::{make_iterator_snippet, IncrementVisitor, InitializeVisitor};
28 declare_clippy_lint! {
30 /// Checks for for-loops that manually copy items between
31 /// slices that could be optimized by having a memcpy.
33 /// ### Why is this bad?
34 /// It is not as fast as a memcpy.
38 /// # let src = vec![1];
39 /// # let mut dst = vec![0; 65];
40 /// for i in 0..src.len() {
41 /// dst[i + 64] = src[i];
44 /// Could be written as:
46 /// # let src = vec![1];
47 /// # let mut dst = vec![0; 65];
48 /// dst[64..(src.len() + 64)].clone_from_slice(&src[..]);
50 #[clippy::version = "pre 1.29.0"]
53 "manually copying items between slices"
56 declare_clippy_lint! {
58 /// Checks for looping over the range of `0..len` of some
59 /// collection just to get the values by index.
61 /// ### Why is this bad?
62 /// Just iterating the collection itself makes the intent
63 /// more clear and is probably faster.
67 /// let vec = vec!['a', 'b', 'c'];
68 /// for i in 0..vec.len() {
69 /// println!("{}", vec[i]);
72 /// Could be written as:
74 /// let vec = vec!['a', 'b', 'c'];
76 /// println!("{}", i);
79 #[clippy::version = "pre 1.29.0"]
80 pub NEEDLESS_RANGE_LOOP,
82 "for-looping over a range of indices where an iterator over items would do"
85 declare_clippy_lint! {
87 /// Checks for loops on `x.iter()` where `&x` will do, and
88 /// suggests the latter.
90 /// ### Why is this bad?
93 /// ### Known problems
94 /// False negatives. We currently only warn on some known
99 /// // with `y` a `Vec` or slice:
100 /// # let y = vec![1];
101 /// for x in y.iter() {
105 /// can be rewritten to
107 /// # let y = vec![1];
112 #[clippy::version = "pre 1.29.0"]
113 pub EXPLICIT_ITER_LOOP,
115 "for-looping over `_.iter()` or `_.iter_mut()` when `&_` or `&mut _` would do"
118 declare_clippy_lint! {
120 /// Checks for loops on `y.into_iter()` where `y` will do, and
121 /// suggests the latter.
123 /// ### Why is this bad?
128 /// # let y = vec![1];
129 /// // with `y` a `Vec` or slice:
130 /// for x in y.into_iter() {
134 /// can be rewritten to
136 /// # let y = vec![1];
141 #[clippy::version = "pre 1.29.0"]
142 pub EXPLICIT_INTO_ITER_LOOP,
144 "for-looping over `_.into_iter()` when `_` would do"
147 declare_clippy_lint! {
149 /// Checks for loops on `x.next()`.
151 /// ### Why is this bad?
152 /// `next()` returns either `Some(value)` if there was a
153 /// value, or `None` otherwise. The insidious thing is that `Option<_>`
154 /// implements `IntoIterator`, so that possibly one value will be iterated,
155 /// leading to some hard to find bugs. No one will want to write such code
156 /// [except to win an Underhanded Rust
157 /// Contest](https://www.reddit.com/r/rust/comments/3hb0wm/underhanded_rust_contest/cu5yuhr).
161 /// for x in y.next() {
165 #[clippy::version = "pre 1.29.0"]
168 "for-looping over `_.next()` which is probably not intended"
171 declare_clippy_lint! {
173 /// Checks for `for` loops over `Option` or `Result` values.
175 /// ### Why is this bad?
176 /// Readability. This is more clearly expressed as an `if
181 /// # let opt = Some(1);
189 /// if let Some(x) = opt {
197 /// # let res: Result<i32, std::io::Error> = Ok(1);
205 /// if let Ok(x) = res {
209 #[clippy::version = "1.45.0"]
210 pub FOR_LOOPS_OVER_FALLIBLES,
212 "for-looping over an `Option` or a `Result`, which is more clearly expressed as an `if let`"
215 declare_clippy_lint! {
217 /// Detects `loop + match` combinations that are easier
218 /// written as a `while let` loop.
220 /// ### Why is this bad?
221 /// The `while let` loop is usually shorter and more
224 /// ### Known problems
225 /// Sometimes the wrong binding is displayed ([#383](https://github.com/rust-lang/rust-clippy/issues/383)).
229 /// # let y = Some(1);
231 /// let x = match y {
235 /// // .. do something with x
237 /// // is easier written as
238 /// while let Some(x) = y {
239 /// // .. do something with x
242 #[clippy::version = "pre 1.29.0"]
245 "`loop { if let { ... } else break }`, which can be written as a `while let` loop"
248 declare_clippy_lint! {
250 /// Checks for functions collecting an iterator when collect
253 /// ### Why is this bad?
254 /// `collect` causes the allocation of a new data structure,
255 /// when this allocation may not be needed.
259 /// # let iterator = vec![1].into_iter();
260 /// let len = iterator.clone().collect::<Vec<_>>().len();
262 /// let len = iterator.count();
264 #[clippy::version = "1.30.0"]
265 pub NEEDLESS_COLLECT,
267 "collecting an iterator when collect is not needed"
270 declare_clippy_lint! {
272 /// Checks `for` loops over slices with an explicit counter
273 /// and suggests the use of `.enumerate()`.
275 /// ### Why is this bad?
276 /// Using `.enumerate()` makes the intent more clear,
277 /// declutters the code and may be faster in some instances.
281 /// # let v = vec![1];
282 /// # fn bar(bar: usize, baz: usize) {}
289 /// Could be written as
291 /// # let v = vec![1];
292 /// # fn bar(bar: usize, baz: usize) {}
293 /// for (i, item) in v.iter().enumerate() { bar(i, *item); }
295 #[clippy::version = "pre 1.29.0"]
296 pub EXPLICIT_COUNTER_LOOP,
298 "for-looping with an explicit counter when `_.enumerate()` would do"
301 declare_clippy_lint! {
303 /// Checks for empty `loop` expressions.
305 /// ### Why is this bad?
306 /// These busy loops burn CPU cycles without doing
307 /// anything. It is _almost always_ a better idea to `panic!` than to have
310 /// If panicking isn't possible, think of the environment and either:
311 /// - block on something
312 /// - sleep the thread for some microseconds
313 /// - yield or pause the thread
315 /// For `std` targets, this can be done with
316 /// [`std::thread::sleep`](https://doc.rust-lang.org/std/thread/fn.sleep.html)
317 /// or [`std::thread::yield_now`](https://doc.rust-lang.org/std/thread/fn.yield_now.html).
319 /// For `no_std` targets, doing this is more complicated, especially because
320 /// `#[panic_handler]`s can't panic. To stop/pause the thread, you will
321 /// probably need to invoke some target-specific intrinsic. Examples include:
322 /// - [`x86_64::instructions::hlt`](https://docs.rs/x86_64/0.12.2/x86_64/instructions/fn.hlt.html)
323 /// - [`cortex_m::asm::wfi`](https://docs.rs/cortex-m/0.6.3/cortex_m/asm/fn.wfi.html)
329 #[clippy::version = "pre 1.29.0"]
332 "empty `loop {}`, which should block or sleep"
335 declare_clippy_lint! {
337 /// Checks for `while let` expressions on iterators.
339 /// ### Why is this bad?
340 /// Readability. A simple `for` loop is shorter and conveys
341 /// the intent better.
345 /// while let Some(val) = iter() {
349 #[clippy::version = "pre 1.29.0"]
350 pub WHILE_LET_ON_ITERATOR,
352 "using a `while let` loop instead of a for loop on an iterator"
355 declare_clippy_lint! {
357 /// Checks for iterating a map (`HashMap` or `BTreeMap`) and
358 /// ignoring either the keys or values.
360 /// ### Why is this bad?
361 /// Readability. There are `keys` and `values` methods that
362 /// can be used to express that don't need the values or keys.
366 /// for (k, _) in &map {
371 /// could be replaced by
374 /// for k in map.keys() {
378 #[clippy::version = "pre 1.29.0"]
381 "looping on a map using `iter` when `keys` or `values` would do"
384 declare_clippy_lint! {
386 /// Checks for loops that will always `break`, `return` or
387 /// `continue` an outer loop.
389 /// ### Why is this bad?
390 /// This loop never loops, all it does is obfuscating the
400 #[clippy::version = "pre 1.29.0"]
403 "any loop that will always `break` or `return`"
406 declare_clippy_lint! {
408 /// Checks for loops which have a range bound that is a mutable variable
410 /// ### Why is this bad?
411 /// One might think that modifying the mutable variable changes the loop bounds
413 /// ### Known problems
414 /// False positive when mutation is followed by a `break`, but the `break` is not immediately
415 /// after the mutation:
420 /// x += 1; // x is a range bound that is mutated
421 /// ..; // some other expression
422 /// break; // leaves the loop, so mutation is not an issue
426 /// False positive on nested loops ([#6072](https://github.com/rust-lang/rust-clippy/issues/6072))
430 /// let mut foo = 42;
431 /// for i in 0..foo {
433 /// println!("{}", i); // prints numbers from 0 to 42, not 0 to 21
436 #[clippy::version = "pre 1.29.0"]
439 "for loop over a range where one of the bounds is a mutable variable"
442 declare_clippy_lint! {
444 /// Checks whether variables used within while loop condition
445 /// can be (and are) mutated in the body.
447 /// ### Why is this bad?
448 /// If the condition is unchanged, entering the body of the loop
449 /// will lead to an infinite loop.
451 /// ### Known problems
452 /// If the `while`-loop is in a closure, the check for mutation of the
453 /// condition variables in the body can cause false negatives. For example when only `Upvar` `a` is
454 /// in the condition and only `Upvar` `b` gets mutated in the body, the lint will not trigger.
460 /// println!("let me loop forever!");
463 #[clippy::version = "pre 1.29.0"]
464 pub WHILE_IMMUTABLE_CONDITION,
466 "variables used within while expression are not mutated in the body"
469 declare_clippy_lint! {
471 /// Checks whether a for loop is being used to push a constant
472 /// value into a Vec.
474 /// ### Why is this bad?
475 /// This kind of operation can be expressed more succinctly with
476 /// `vec![item;SIZE]` or `vec.resize(NEW_SIZE, item)` and using these alternatives may also
477 /// have better performance.
483 /// let mut vec: Vec<u8> = Vec::new();
491 /// could be written as
495 /// let mut vec: Vec<u8> = vec![item1; 20];
496 /// vec.resize(20 + 30, item2);
498 #[clippy::version = "1.47.0"]
501 "the same item is pushed inside of a for loop"
504 declare_clippy_lint! {
506 /// Checks whether a for loop has a single element.
508 /// ### Why is this bad?
509 /// There is no reason to have a loop of a
515 /// for item in &[item1] {
516 /// println!("{}", item);
519 /// could be written as
522 /// let item = &item1;
523 /// println!("{}", item);
525 #[clippy::version = "1.49.0"]
526 pub SINGLE_ELEMENT_LOOP,
528 "there is no reason to have a single element loop"
531 declare_clippy_lint! {
533 /// Check for unnecessary `if let` usage in a for loop
534 /// where only the `Some` or `Ok` variant of the iterator element is used.
536 /// ### Why is this bad?
537 /// It is verbose and can be simplified
538 /// by first calling the `flatten` method on the `Iterator`.
543 /// let x = vec![Some(1), Some(2), Some(3)];
545 /// if let Some(n) = n {
546 /// println!("{}", n);
552 /// let x = vec![Some(1), Some(2), Some(3)];
553 /// for n in x.into_iter().flatten() {
554 /// println!("{}", n);
557 #[clippy::version = "1.52.0"]
560 "for loops over `Option`s or `Result`s with a single expression can be simplified"
563 declare_lint_pass!(Loops => [
568 EXPLICIT_INTO_ITER_LOOP,
570 FOR_LOOPS_OVER_FALLIBLES,
573 EXPLICIT_COUNTER_LOOP,
575 WHILE_LET_ON_ITERATOR,
579 WHILE_IMMUTABLE_CONDITION,
584 impl<'tcx> LateLintPass<'tcx> for Loops {
585 #[allow(clippy::too_many_lines)]
586 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
587 let for_loop = higher::ForLoop::hir(expr);
588 if let Some(higher::ForLoop {
596 // we don't want to check expanded macros
597 // this check is not at the top of the function
598 // since higher::for_loop expressions are marked as expansions
599 if body.span.from_expansion() {
602 check_for_loop(cx, pat, arg, body, expr, span);
603 if let ExprKind::Block(block, _) = body.kind {
604 never_loop::check(cx, block, loop_id, span, for_loop.as_ref());
608 // we don't want to check expanded macros
609 if expr.span.from_expansion() {
613 // check for never_loop
614 if let ExprKind::Loop(block, ..) = expr.kind {
615 never_loop::check(cx, block, expr.hir_id, expr.span, None);
618 // check for `loop { if let {} else break }` that could be `while let`
619 // (also matches an explicit "match" instead of "if let")
620 // (even if the "match" or "if let" is used for declaration)
621 if let ExprKind::Loop(block, _, LoopSource::Loop, _) = expr.kind {
622 // also check for empty `loop {}` statements, skipping those in #[panic_handler]
623 empty_loop::check(cx, expr, block);
624 while_let_loop::check(cx, expr, block);
627 while_let_on_iterator::check(cx, expr);
629 if let Some(higher::While { condition, body }) = higher::While::hir(expr) {
630 while_immutable_condition::check(cx, condition, body);
633 needless_collect::check(expr, cx);
637 fn check_for_loop<'tcx>(
638 cx: &LateContext<'tcx>,
641 body: &'tcx Expr<'_>,
642 expr: &'tcx Expr<'_>,
645 let is_manual_memcpy_triggered = manual_memcpy::check(cx, pat, arg, body, expr);
646 if !is_manual_memcpy_triggered {
647 needless_range_loop::check(cx, pat, arg, body, expr);
648 explicit_counter_loop::check(cx, pat, arg, body, expr);
650 check_for_loop_arg(cx, pat, arg);
651 for_kv_map::check(cx, pat, arg, body);
652 mut_range_bound::check(cx, arg, body);
653 single_element_loop::check(cx, pat, arg, body, expr);
654 same_item_push::check(cx, pat, arg, body, expr);
655 manual_flatten::check(cx, pat, arg, body, span);
658 fn check_for_loop_arg(cx: &LateContext<'_>, pat: &Pat<'_>, arg: &Expr<'_>) {
659 let mut next_loop_linted = false; // whether or not ITER_NEXT_LOOP lint was used
661 if let ExprKind::MethodCall(method, _, [self_arg], _) = arg.kind {
662 let method_name = method.ident.as_str();
663 // check for looping over x.iter() or x.iter_mut(), could use &x or &mut x
665 "iter" | "iter_mut" => explicit_iter_loop::check(cx, self_arg, arg, method_name),
667 explicit_iter_loop::check(cx, self_arg, arg, method_name);
668 explicit_into_iter_loop::check(cx, self_arg, arg);
671 next_loop_linted = iter_next_loop::check(cx, arg);
677 if !next_loop_linted {
678 for_loops_over_fallibles::check(cx, pat, arg);