2 mod explicit_counter_loop
;
3 mod explicit_into_iter_loop
;
4 mod explicit_iter_loop
;
10 mod manual_while_let_some
;
11 mod missing_spin_loop
;
13 mod needless_range_loop
;
16 mod single_element_loop
;
17 mod unused_enumerate_index
;
19 mod while_immutable_condition
;
21 mod while_let_on_iterator
;
23 use clippy_config
::msrvs
::Msrv
;
24 use clippy_utils
::higher
;
25 use rustc_hir
::{Expr, ExprKind, LoopSource, Pat}
;
26 use rustc_lint
::{LateContext, LateLintPass}
;
27 use rustc_session
::{declare_tool_lint, impl_lint_pass}
;
29 use utils
::{make_iterator_snippet, IncrementVisitor, InitializeVisitor}
;
31 declare_clippy_lint
! {
33 /// Checks for for-loops that manually copy items between
34 /// slices that could be optimized by having a memcpy.
36 /// ### Why is this bad?
37 /// It is not as fast as a memcpy.
41 /// # let src = vec![1];
42 /// # let mut dst = vec![0; 65];
43 /// for i in 0..src.len() {
44 /// dst[i + 64] = src[i];
50 /// # let src = vec![1];
51 /// # let mut dst = vec![0; 65];
52 /// dst[64..(src.len() + 64)].clone_from_slice(&src[..]);
54 #[clippy::version = "pre 1.29.0"]
57 "manually copying items between slices"
60 declare_clippy_lint
! {
62 /// Checks for looping over the range of `0..len` of some
63 /// collection just to get the values by index.
65 /// ### Why is this bad?
66 /// Just iterating the collection itself makes the intent
67 /// more clear and is probably faster because it eliminates
68 /// the bounds check that is done when indexing.
72 /// let vec = vec!['a', 'b', 'c'];
73 /// for i in 0..vec.len() {
74 /// println!("{}", vec[i]);
80 /// let vec = vec!['a', 'b', 'c'];
82 /// println!("{}", i);
85 #[clippy::version = "pre 1.29.0"]
86 pub NEEDLESS_RANGE_LOOP
,
88 "for-looping over a range of indices where an iterator over items would do"
91 declare_clippy_lint
! {
93 /// Checks for loops on `x.iter()` where `&x` will do, and
94 /// suggests the latter.
96 /// ### Why is this bad?
99 /// ### Known problems
100 /// False negatives. We currently only warn on some known
105 /// // with `y` a `Vec` or slice:
106 /// # let y = vec![1];
107 /// for x in y.iter() {
114 /// # let y = vec![1];
119 #[clippy::version = "pre 1.29.0"]
120 pub EXPLICIT_ITER_LOOP
,
122 "for-looping over `_.iter()` or `_.iter_mut()` when `&_` or `&mut _` would do"
125 declare_clippy_lint
! {
127 /// Checks for loops on `y.into_iter()` where `y` will do, and
128 /// suggests the latter.
130 /// ### Why is this bad?
135 /// # let y = vec![1];
136 /// // with `y` a `Vec` or slice:
137 /// for x in y.into_iter() {
141 /// can be rewritten to
143 /// # let y = vec![1];
148 #[clippy::version = "pre 1.29.0"]
149 pub EXPLICIT_INTO_ITER_LOOP
,
151 "for-looping over `_.into_iter()` when `_` would do"
154 declare_clippy_lint
! {
156 /// Checks for loops on `x.next()`.
158 /// ### Why is this bad?
159 /// `next()` returns either `Some(value)` if there was a
160 /// value, or `None` otherwise. The insidious thing is that `Option<_>`
161 /// implements `IntoIterator`, so that possibly one value will be iterated,
162 /// leading to some hard to find bugs. No one will want to write such code
163 /// [except to win an Underhanded Rust
164 /// Contest](https://www.reddit.com/r/rust/comments/3hb0wm/underhanded_rust_contest/cu5yuhr).
168 /// for x in y.next() {
172 #[clippy::version = "pre 1.29.0"]
175 "for-looping over `_.next()` which is probably not intended"
178 declare_clippy_lint
! {
180 /// Detects `loop + match` combinations that are easier
181 /// written as a `while let` loop.
183 /// ### Why is this bad?
184 /// The `while let` loop is usually shorter and more
187 /// ### Known problems
188 /// Sometimes the wrong binding is displayed ([#383](https://github.com/rust-lang/rust-clippy/issues/383)).
192 /// # let y = Some(1);
194 /// let x = match y {
198 /// // .. do something with x
200 /// // is easier written as
201 /// while let Some(x) = y {
202 /// // .. do something with x
205 #[clippy::version = "pre 1.29.0"]
208 "`loop { if let { ... } else break }`, which can be written as a `while let` loop"
211 declare_clippy_lint
! {
213 /// Checks `for` loops over slices with an explicit counter
214 /// and suggests the use of `.enumerate()`.
216 /// ### Why is this bad?
217 /// Using `.enumerate()` makes the intent more clear,
218 /// declutters the code and may be faster in some instances.
222 /// # let v = vec![1];
223 /// # fn bar(bar: usize, baz: usize) {}
233 /// # let v = vec![1];
234 /// # fn bar(bar: usize, baz: usize) {}
235 /// for (i, item) in v.iter().enumerate() { bar(i, *item); }
237 #[clippy::version = "pre 1.29.0"]
238 pub EXPLICIT_COUNTER_LOOP
,
240 "for-looping with an explicit counter when `_.enumerate()` would do"
243 declare_clippy_lint
! {
245 /// Checks for empty `loop` expressions.
247 /// ### Why is this bad?
248 /// These busy loops burn CPU cycles without doing
249 /// anything. It is _almost always_ a better idea to `panic!` than to have
252 /// If panicking isn't possible, think of the environment and either:
253 /// - block on something
254 /// - sleep the thread for some microseconds
255 /// - yield or pause the thread
257 /// For `std` targets, this can be done with
258 /// [`std::thread::sleep`](https://doc.rust-lang.org/std/thread/fn.sleep.html)
259 /// or [`std::thread::yield_now`](https://doc.rust-lang.org/std/thread/fn.yield_now.html).
261 /// For `no_std` targets, doing this is more complicated, especially because
262 /// `#[panic_handler]`s can't panic. To stop/pause the thread, you will
263 /// probably need to invoke some target-specific intrinsic. Examples include:
264 /// - [`x86_64::instructions::hlt`](https://docs.rs/x86_64/0.12.2/x86_64/instructions/fn.hlt.html)
265 /// - [`cortex_m::asm::wfi`](https://docs.rs/cortex-m/0.6.3/cortex_m/asm/fn.wfi.html)
271 #[clippy::version = "pre 1.29.0"]
274 "empty `loop {}`, which should block or sleep"
277 declare_clippy_lint
! {
279 /// Checks for `while let` expressions on iterators.
281 /// ### Why is this bad?
282 /// Readability. A simple `for` loop is shorter and conveys
283 /// the intent better.
287 /// while let Some(val) = iter.next() {
294 /// for val in &mut iter {
298 #[clippy::version = "pre 1.29.0"]
299 pub WHILE_LET_ON_ITERATOR
,
301 "using a `while let` loop instead of a for loop on an iterator"
304 declare_clippy_lint
! {
306 /// Checks for iterating a map (`HashMap` or `BTreeMap`) and
307 /// ignoring either the keys or values.
309 /// ### Why is this bad?
310 /// Readability. There are `keys` and `values` methods that
311 /// can be used to express that don't need the values or keys.
315 /// for (k, _) in &map {
320 /// could be replaced by
323 /// for k in map.keys() {
327 #[clippy::version = "pre 1.29.0"]
330 "looping on a map using `iter` when `keys` or `values` would do"
333 declare_clippy_lint
! {
335 /// Checks for loops that will always `break`, `return` or
336 /// `continue` an outer loop.
338 /// ### Why is this bad?
339 /// This loop never loops, all it does is obfuscating the
349 #[clippy::version = "pre 1.29.0"]
352 "any loop that will always `break` or `return`"
355 declare_clippy_lint
! {
357 /// Checks for loops which have a range bound that is a mutable variable
359 /// ### Why is this bad?
360 /// One might think that modifying the mutable variable changes the loop bounds
362 /// ### Known problems
363 /// False positive when mutation is followed by a `break`, but the `break` is not immediately
364 /// after the mutation:
369 /// x += 1; // x is a range bound that is mutated
370 /// ..; // some other expression
371 /// break; // leaves the loop, so mutation is not an issue
375 /// False positive on nested loops ([#6072](https://github.com/rust-lang/rust-clippy/issues/6072))
379 /// let mut foo = 42;
380 /// for i in 0..foo {
382 /// println!("{}", i); // prints numbers from 0 to 42, not 0 to 21
385 #[clippy::version = "pre 1.29.0"]
388 "for loop over a range where one of the bounds is a mutable variable"
391 declare_clippy_lint
! {
393 /// Checks whether variables used within while loop condition
394 /// can be (and are) mutated in the body.
396 /// ### Why is this bad?
397 /// If the condition is unchanged, entering the body of the loop
398 /// will lead to an infinite loop.
400 /// ### Known problems
401 /// If the `while`-loop is in a closure, the check for mutation of the
402 /// condition variables in the body can cause false negatives. For example when only `Upvar` `a` is
403 /// in the condition and only `Upvar` `b` gets mutated in the body, the lint will not trigger.
409 /// println!("let me loop forever!");
412 #[clippy::version = "pre 1.29.0"]
413 pub WHILE_IMMUTABLE_CONDITION
,
415 "variables used within while expression are not mutated in the body"
418 declare_clippy_lint
! {
420 /// Checks whether a for loop is being used to push a constant
421 /// value into a Vec.
423 /// ### Why is this bad?
424 /// This kind of operation can be expressed more succinctly with
425 /// `vec![item; SIZE]` or `vec.resize(NEW_SIZE, item)` and using these alternatives may also
426 /// have better performance.
432 /// let mut vec: Vec<u8> = Vec::new();
445 /// let mut vec: Vec<u8> = vec![item1; 20];
446 /// vec.resize(20 + 30, item2);
448 #[clippy::version = "1.47.0"]
451 "the same item is pushed inside of a for loop"
454 declare_clippy_lint
! {
456 /// Checks whether a for loop has a single element.
458 /// ### Why is this bad?
459 /// There is no reason to have a loop of a
465 /// for item in &[item1] {
466 /// println!("{}", item);
473 /// let item = &item1;
474 /// println!("{}", item);
476 #[clippy::version = "1.49.0"]
477 pub SINGLE_ELEMENT_LOOP
,
479 "there is no reason to have a single element loop"
482 declare_clippy_lint
! {
484 /// Checks for unnecessary `if let` usage in a for loop
485 /// where only the `Some` or `Ok` variant of the iterator element is used.
487 /// ### Why is this bad?
488 /// It is verbose and can be simplified
489 /// by first calling the `flatten` method on the `Iterator`.
494 /// let x = vec![Some(1), Some(2), Some(3)];
496 /// if let Some(n) = n {
497 /// println!("{}", n);
503 /// let x = vec![Some(1), Some(2), Some(3)];
504 /// for n in x.into_iter().flatten() {
505 /// println!("{}", n);
508 #[clippy::version = "1.52.0"]
511 "for loops over `Option`s or `Result`s with a single expression can be simplified"
514 declare_clippy_lint
! {
516 /// Checks for empty spin loops
518 /// ### Why is this bad?
519 /// The loop body should have something like `thread::park()` or at least
520 /// `std::hint::spin_loop()` to avoid needlessly burning cycles and conserve
521 /// energy. Perhaps even better use an actual lock, if possible.
523 /// ### Known problems
524 /// This lint doesn't currently trigger on `while let` or
525 /// `loop { match .. { .. } }` loops, which would be considered idiomatic in
526 /// combination with e.g. `AtomicBool::compare_exchange_weak`.
531 /// use core::sync::atomic::{AtomicBool, Ordering};
532 /// let b = AtomicBool::new(true);
533 /// // give a ref to `b` to another thread,wait for it to become false
534 /// while b.load(Ordering::Acquire) {};
538 ///# use core::sync::atomic::{AtomicBool, Ordering};
539 ///# let b = AtomicBool::new(true);
540 /// while b.load(Ordering::Acquire) {
541 /// std::hint::spin_loop()
544 #[clippy::version = "1.61.0"]
545 pub MISSING_SPIN_LOOP
,
547 "An empty busy waiting loop"
550 declare_clippy_lint
! {
552 /// Checks for manual implementations of Iterator::find
554 /// ### Why is this bad?
555 /// It doesn't affect performance, but using `find` is shorter and easier to read.
560 /// fn example(arr: Vec<i32>) -> Option<i32> {
571 /// fn example(arr: Vec<i32>) -> Option<i32> {
572 /// arr.into_iter().find(|&el| el == 1)
575 #[clippy::version = "1.64.0"]
578 "manual implementation of `Iterator::find`"
581 declare_clippy_lint
! {
583 /// Checks for uses of the `enumerate` method where the index is unused (`_`)
585 /// ### Why is this bad?
586 /// The index from `.enumerate()` is immediately dropped.
590 /// let v = vec![1, 2, 3, 4];
591 /// for (_, x) in v.iter().enumerate() {
597 /// let v = vec![1, 2, 3, 4];
598 /// for x in v.iter() {
602 #[clippy::version = "1.75.0"]
603 pub UNUSED_ENUMERATE_INDEX
,
605 "using `.enumerate()` and immediately dropping the index"
608 declare_clippy_lint
! {
610 /// Looks for loops that check for emptiness of a `Vec` in the condition and pop an element
611 /// in the body as a separate operation.
613 /// ### Why is this bad?
614 /// Such loops can be written in a more idiomatic way by using a while-let loop and directly
615 /// pattern matching on the return value of `Vec::pop()`.
619 /// let mut numbers = vec![1, 2, 3, 4, 5];
620 /// while !numbers.is_empty() {
621 /// let number = numbers.pop().unwrap();
627 /// let mut numbers = vec![1, 2, 3, 4, 5];
628 /// while let Some(number) = numbers.pop() {
632 #[clippy::version = "1.71.0"]
633 pub MANUAL_WHILE_LET_SOME
,
635 "checking for emptiness of a `Vec` in the loop condition and popping an element in the body"
640 enforce_iter_loop_reborrow
: bool
,
643 pub fn new(msrv
: Msrv
, enforce_iter_loop_reborrow
: bool
) -> Self {
646 enforce_iter_loop_reborrow
,
651 impl_lint_pass
!(Loops
=> [
656 EXPLICIT_INTO_ITER_LOOP
,
659 EXPLICIT_COUNTER_LOOP
,
661 WHILE_LET_ON_ITERATOR
,
665 WHILE_IMMUTABLE_CONDITION
,
670 MANUAL_WHILE_LET_SOME
,
671 UNUSED_ENUMERATE_INDEX
,
674 impl<'tcx
> LateLintPass
<'tcx
> for Loops
{
675 fn check_expr(&mut self, cx
: &LateContext
<'tcx
>, expr
: &'tcx Expr
<'_
>) {
676 let for_loop
= higher
::ForLoop
::hir(expr
);
677 if let Some(higher
::ForLoop
{
685 // we don't want to check expanded macros
686 // this check is not at the top of the function
687 // since higher::for_loop expressions are marked as expansions
688 if body
.span
.from_expansion() {
691 self.check_for_loop(cx
, pat
, arg
, body
, expr
, span
);
692 if let ExprKind
::Block(block
, _
) = body
.kind
{
693 never_loop
::check(cx
, block
, loop_id
, span
, for_loop
.as_ref());
697 // we don't want to check expanded macros
698 if expr
.span
.from_expansion() {
702 // check for never_loop
703 if let ExprKind
::Loop(block
, ..) = expr
.kind
{
704 never_loop
::check(cx
, block
, expr
.hir_id
, expr
.span
, None
);
707 // check for `loop { if let {} else break }` that could be `while let`
708 // (also matches an explicit "match" instead of "if let")
709 // (even if the "match" or "if let" is used for declaration)
710 if let ExprKind
::Loop(block
, _
, LoopSource
::Loop
, _
) = expr
.kind
{
711 // also check for empty `loop {}` statements, skipping those in #[panic_handler]
712 empty_loop
::check(cx
, expr
, block
);
713 while_let_loop
::check(cx
, expr
, block
);
716 while_let_on_iterator
::check(cx
, expr
);
718 if let Some(higher
::While { condition, body, span }
) = higher
::While
::hir(expr
) {
719 while_immutable_condition
::check(cx
, condition
, body
);
720 missing_spin_loop
::check(cx
, condition
, body
);
721 manual_while_let_some
::check(cx
, condition
, body
, span
);
725 extract_msrv_attr
!(LateContext
);
729 fn check_for_loop
<'tcx
>(
731 cx
: &LateContext
<'tcx
>,
734 body
: &'tcx Expr
<'_
>,
735 expr
: &'tcx Expr
<'_
>,
738 let is_manual_memcpy_triggered
= manual_memcpy
::check(cx
, pat
, arg
, body
, expr
);
739 if !is_manual_memcpy_triggered
{
740 needless_range_loop
::check(cx
, pat
, arg
, body
, expr
);
741 explicit_counter_loop
::check(cx
, pat
, arg
, body
, expr
);
743 self.check_for_loop_arg(cx
, pat
, arg
);
744 for_kv_map
::check(cx
, pat
, arg
, body
);
745 mut_range_bound
::check(cx
, arg
, body
);
746 single_element_loop
::check(cx
, pat
, arg
, body
, expr
);
747 same_item_push
::check(cx
, pat
, arg
, body
, expr
);
748 manual_flatten
::check(cx
, pat
, arg
, body
, span
);
749 manual_find
::check(cx
, pat
, arg
, body
, span
, expr
);
750 unused_enumerate_index
::check(cx
, pat
, arg
, body
);
753 fn check_for_loop_arg(&self, cx
: &LateContext
<'_
>, _
: &Pat
<'_
>, arg
: &Expr
<'_
>) {
754 if let ExprKind
::MethodCall(method
, self_arg
, [], _
) = arg
.kind
{
755 match method
.ident
.as_str() {
756 "iter" | "iter_mut" => {
757 explicit_iter_loop
::check(cx
, self_arg
, arg
, &self.msrv
, self.enforce_iter_loop_reborrow
);
760 explicit_into_iter_loop
::check(cx
, self_arg
, arg
);
763 iter_next_loop
::check(cx
, arg
);