2 mod explicit_counter_loop
;
3 mod explicit_into_iter_loop
;
4 mod explicit_iter_loop
;
6 mod for_loops_over_fallibles
;
10 mod missing_spin_loop
;
13 mod needless_range_loop
;
16 mod single_element_loop
;
18 mod while_immutable_condition
;
20 mod while_let_on_iterator
;
22 use clippy_utils
::higher
;
23 use rustc_hir
::{Expr, ExprKind, LoopSource, Pat}
;
24 use rustc_lint
::{LateContext, LateLintPass}
;
25 use rustc_session
::{declare_lint_pass, declare_tool_lint}
;
26 use rustc_span
::source_map
::Span
;
27 use utils
::{make_iterator_snippet, IncrementVisitor, InitializeVisitor}
;
29 declare_clippy_lint
! {
31 /// Checks for for-loops that manually copy items between
32 /// slices that could be optimized by having a memcpy.
34 /// ### Why is this bad?
35 /// It is not as fast as a memcpy.
39 /// # let src = vec![1];
40 /// # let mut dst = vec![0; 65];
41 /// for i in 0..src.len() {
42 /// dst[i + 64] = src[i];
48 /// # let src = vec![1];
49 /// # let mut dst = vec![0; 65];
50 /// dst[64..(src.len() + 64)].clone_from_slice(&src[..]);
52 #[clippy::version = "pre 1.29.0"]
55 "manually copying items between slices"
58 declare_clippy_lint
! {
60 /// Checks for looping over the range of `0..len` of some
61 /// collection just to get the values by index.
63 /// ### Why is this bad?
64 /// Just iterating the collection itself makes the intent
65 /// more clear and is probably faster.
69 /// let vec = vec!['a', 'b', 'c'];
70 /// for i in 0..vec.len() {
71 /// println!("{}", vec[i]);
77 /// let vec = vec!['a', 'b', 'c'];
79 /// println!("{}", i);
82 #[clippy::version = "pre 1.29.0"]
83 pub NEEDLESS_RANGE_LOOP
,
85 "for-looping over a range of indices where an iterator over items would do"
88 declare_clippy_lint
! {
90 /// Checks for loops on `x.iter()` where `&x` will do, and
91 /// suggests the latter.
93 /// ### Why is this bad?
96 /// ### Known problems
97 /// False negatives. We currently only warn on some known
102 /// // with `y` a `Vec` or slice:
103 /// # let y = vec![1];
104 /// for x in y.iter() {
111 /// # let y = vec![1];
116 #[clippy::version = "pre 1.29.0"]
117 pub EXPLICIT_ITER_LOOP
,
119 "for-looping over `_.iter()` or `_.iter_mut()` when `&_` or `&mut _` would do"
122 declare_clippy_lint
! {
124 /// Checks for loops on `y.into_iter()` where `y` will do, and
125 /// suggests the latter.
127 /// ### Why is this bad?
132 /// # let y = vec![1];
133 /// // with `y` a `Vec` or slice:
134 /// for x in y.into_iter() {
138 /// can be rewritten to
140 /// # let y = vec![1];
145 #[clippy::version = "pre 1.29.0"]
146 pub EXPLICIT_INTO_ITER_LOOP
,
148 "for-looping over `_.into_iter()` when `_` would do"
151 declare_clippy_lint
! {
153 /// Checks for loops on `x.next()`.
155 /// ### Why is this bad?
156 /// `next()` returns either `Some(value)` if there was a
157 /// value, or `None` otherwise. The insidious thing is that `Option<_>`
158 /// implements `IntoIterator`, so that possibly one value will be iterated,
159 /// leading to some hard to find bugs. No one will want to write such code
160 /// [except to win an Underhanded Rust
161 /// Contest](https://www.reddit.com/r/rust/comments/3hb0wm/underhanded_rust_contest/cu5yuhr).
165 /// for x in y.next() {
169 #[clippy::version = "pre 1.29.0"]
172 "for-looping over `_.next()` which is probably not intended"
175 declare_clippy_lint
! {
177 /// Checks for `for` loops over `Option` or `Result` values.
179 /// ### Why is this bad?
180 /// Readability. This is more clearly expressed as an `if
185 /// # let opt = Some(1);
186 /// # let res: Result<i32, std::io::Error> = Ok(1);
195 /// for x in res.iter() {
202 /// # let opt = Some(1);
203 /// # let res: Result<i32, std::io::Error> = Ok(1);
204 /// if let Some(x) = opt {
208 /// if let Ok(x) = res {
212 #[clippy::version = "1.45.0"]
213 pub FOR_LOOPS_OVER_FALLIBLES
,
215 "for-looping over an `Option` or a `Result`, which is more clearly expressed as an `if let`"
218 declare_clippy_lint
! {
220 /// Detects `loop + match` combinations that are easier
221 /// written as a `while let` loop.
223 /// ### Why is this bad?
224 /// The `while let` loop is usually shorter and more
227 /// ### Known problems
228 /// Sometimes the wrong binding is displayed ([#383](https://github.com/rust-lang/rust-clippy/issues/383)).
232 /// # let y = Some(1);
234 /// let x = match y {
238 /// // .. do something with x
240 /// // is easier written as
241 /// while let Some(x) = y {
242 /// // .. do something with x
245 #[clippy::version = "pre 1.29.0"]
248 "`loop { if let { ... } else break }`, which can be written as a `while let` loop"
251 declare_clippy_lint
! {
253 /// Checks for functions collecting an iterator when collect
256 /// ### Why is this bad?
257 /// `collect` causes the allocation of a new data structure,
258 /// when this allocation may not be needed.
262 /// # let iterator = vec![1].into_iter();
263 /// let len = iterator.clone().collect::<Vec<_>>().len();
265 /// let len = iterator.count();
267 #[clippy::version = "1.30.0"]
268 pub NEEDLESS_COLLECT
,
270 "collecting an iterator when collect is not needed"
273 declare_clippy_lint
! {
275 /// Checks `for` loops over slices with an explicit counter
276 /// and suggests the use of `.enumerate()`.
278 /// ### Why is this bad?
279 /// Using `.enumerate()` makes the intent more clear,
280 /// declutters the code and may be faster in some instances.
284 /// # let v = vec![1];
285 /// # fn bar(bar: usize, baz: usize) {}
295 /// # let v = vec![1];
296 /// # fn bar(bar: usize, baz: usize) {}
297 /// for (i, item) in v.iter().enumerate() { bar(i, *item); }
299 #[clippy::version = "pre 1.29.0"]
300 pub EXPLICIT_COUNTER_LOOP
,
302 "for-looping with an explicit counter when `_.enumerate()` would do"
305 declare_clippy_lint
! {
307 /// Checks for empty `loop` expressions.
309 /// ### Why is this bad?
310 /// These busy loops burn CPU cycles without doing
311 /// anything. It is _almost always_ a better idea to `panic!` than to have
314 /// If panicking isn't possible, think of the environment and either:
315 /// - block on something
316 /// - sleep the thread for some microseconds
317 /// - yield or pause the thread
319 /// For `std` targets, this can be done with
320 /// [`std::thread::sleep`](https://doc.rust-lang.org/std/thread/fn.sleep.html)
321 /// or [`std::thread::yield_now`](https://doc.rust-lang.org/std/thread/fn.yield_now.html).
323 /// For `no_std` targets, doing this is more complicated, especially because
324 /// `#[panic_handler]`s can't panic. To stop/pause the thread, you will
325 /// probably need to invoke some target-specific intrinsic. Examples include:
326 /// - [`x86_64::instructions::hlt`](https://docs.rs/x86_64/0.12.2/x86_64/instructions/fn.hlt.html)
327 /// - [`cortex_m::asm::wfi`](https://docs.rs/cortex-m/0.6.3/cortex_m/asm/fn.wfi.html)
333 #[clippy::version = "pre 1.29.0"]
336 "empty `loop {}`, which should block or sleep"
339 declare_clippy_lint
! {
341 /// Checks for `while let` expressions on iterators.
343 /// ### Why is this bad?
344 /// Readability. A simple `for` loop is shorter and conveys
345 /// the intent better.
349 /// while let Some(val) = iter() {
353 #[clippy::version = "pre 1.29.0"]
354 pub WHILE_LET_ON_ITERATOR
,
356 "using a `while let` loop instead of a for loop on an iterator"
359 declare_clippy_lint
! {
361 /// Checks for iterating a map (`HashMap` or `BTreeMap`) and
362 /// ignoring either the keys or values.
364 /// ### Why is this bad?
365 /// Readability. There are `keys` and `values` methods that
366 /// can be used to express that don't need the values or keys.
370 /// for (k, _) in &map {
375 /// could be replaced by
378 /// for k in map.keys() {
382 #[clippy::version = "pre 1.29.0"]
385 "looping on a map using `iter` when `keys` or `values` would do"
388 declare_clippy_lint
! {
390 /// Checks for loops that will always `break`, `return` or
391 /// `continue` an outer loop.
393 /// ### Why is this bad?
394 /// This loop never loops, all it does is obfuscating the
404 #[clippy::version = "pre 1.29.0"]
407 "any loop that will always `break` or `return`"
410 declare_clippy_lint
! {
412 /// Checks for loops which have a range bound that is a mutable variable
414 /// ### Why is this bad?
415 /// One might think that modifying the mutable variable changes the loop bounds
417 /// ### Known problems
418 /// False positive when mutation is followed by a `break`, but the `break` is not immediately
419 /// after the mutation:
424 /// x += 1; // x is a range bound that is mutated
425 /// ..; // some other expression
426 /// break; // leaves the loop, so mutation is not an issue
430 /// False positive on nested loops ([#6072](https://github.com/rust-lang/rust-clippy/issues/6072))
434 /// let mut foo = 42;
435 /// for i in 0..foo {
437 /// println!("{}", i); // prints numbers from 0 to 42, not 0 to 21
440 #[clippy::version = "pre 1.29.0"]
443 "for loop over a range where one of the bounds is a mutable variable"
446 declare_clippy_lint
! {
448 /// Checks whether variables used within while loop condition
449 /// can be (and are) mutated in the body.
451 /// ### Why is this bad?
452 /// If the condition is unchanged, entering the body of the loop
453 /// will lead to an infinite loop.
455 /// ### Known problems
456 /// If the `while`-loop is in a closure, the check for mutation of the
457 /// condition variables in the body can cause false negatives. For example when only `Upvar` `a` is
458 /// in the condition and only `Upvar` `b` gets mutated in the body, the lint will not trigger.
464 /// println!("let me loop forever!");
467 #[clippy::version = "pre 1.29.0"]
468 pub WHILE_IMMUTABLE_CONDITION
,
470 "variables used within while expression are not mutated in the body"
473 declare_clippy_lint
! {
475 /// Checks whether a for loop is being used to push a constant
476 /// value into a Vec.
478 /// ### Why is this bad?
479 /// This kind of operation can be expressed more succinctly with
480 /// `vec![item; SIZE]` or `vec.resize(NEW_SIZE, item)` and using these alternatives may also
481 /// have better performance.
487 /// let mut vec: Vec<u8> = Vec::new();
500 /// let mut vec: Vec<u8> = vec![item1; 20];
501 /// vec.resize(20 + 30, item2);
503 #[clippy::version = "1.47.0"]
506 "the same item is pushed inside of a for loop"
509 declare_clippy_lint
! {
511 /// Checks whether a for loop has a single element.
513 /// ### Why is this bad?
514 /// There is no reason to have a loop of a
520 /// for item in &[item1] {
521 /// println!("{}", item);
528 /// let item = &item1;
529 /// println!("{}", item);
531 #[clippy::version = "1.49.0"]
532 pub SINGLE_ELEMENT_LOOP
,
534 "there is no reason to have a single element loop"
537 declare_clippy_lint
! {
539 /// Check for unnecessary `if let` usage in a for loop
540 /// where only the `Some` or `Ok` variant of the iterator element is used.
542 /// ### Why is this bad?
543 /// It is verbose and can be simplified
544 /// by first calling the `flatten` method on the `Iterator`.
549 /// let x = vec![Some(1), Some(2), Some(3)];
551 /// if let Some(n) = n {
552 /// println!("{}", n);
558 /// let x = vec![Some(1), Some(2), Some(3)];
559 /// for n in x.into_iter().flatten() {
560 /// println!("{}", n);
563 #[clippy::version = "1.52.0"]
566 "for loops over `Option`s or `Result`s with a single expression can be simplified"
569 declare_clippy_lint
! {
571 /// Check for empty spin loops
573 /// ### Why is this bad?
574 /// The loop body should have something like `thread::park()` or at least
575 /// `std::hint::spin_loop()` to avoid needlessly burning cycles and conserve
576 /// energy. Perhaps even better use an actual lock, if possible.
578 /// ### Known problems
579 /// This lint doesn't currently trigger on `while let` or
580 /// `loop { match .. { .. } }` loops, which would be considered idiomatic in
581 /// combination with e.g. `AtomicBool::compare_exchange_weak`.
586 /// use core::sync::atomic::{AtomicBool, Ordering};
587 /// let b = AtomicBool::new(true);
588 /// // give a ref to `b` to another thread,wait for it to become false
589 /// while b.load(Ordering::Acquire) {};
593 ///# use core::sync::atomic::{AtomicBool, Ordering};
594 ///# let b = AtomicBool::new(true);
595 /// while b.load(Ordering::Acquire) {
596 /// std::hint::spin_loop()
599 #[clippy::version = "1.61.0"]
600 pub MISSING_SPIN_LOOP
,
602 "An empty busy waiting loop"
605 declare_lint_pass
!(Loops
=> [
610 EXPLICIT_INTO_ITER_LOOP
,
612 FOR_LOOPS_OVER_FALLIBLES
,
615 EXPLICIT_COUNTER_LOOP
,
617 WHILE_LET_ON_ITERATOR
,
621 WHILE_IMMUTABLE_CONDITION
,
627 impl<'tcx
> LateLintPass
<'tcx
> for Loops
{
628 fn check_expr(&mut self, cx
: &LateContext
<'tcx
>, expr
: &'tcx Expr
<'_
>) {
629 let for_loop
= higher
::ForLoop
::hir(expr
);
630 if let Some(higher
::ForLoop
{
638 // we don't want to check expanded macros
639 // this check is not at the top of the function
640 // since higher::for_loop expressions are marked as expansions
641 if body
.span
.from_expansion() {
644 check_for_loop(cx
, pat
, arg
, body
, expr
, span
);
645 if let ExprKind
::Block(block
, _
) = body
.kind
{
646 never_loop
::check(cx
, block
, loop_id
, span
, for_loop
.as_ref());
650 // we don't want to check expanded macros
651 if expr
.span
.from_expansion() {
655 // check for never_loop
656 if let ExprKind
::Loop(block
, ..) = expr
.kind
{
657 never_loop
::check(cx
, block
, expr
.hir_id
, expr
.span
, None
);
660 // check for `loop { if let {} else break }` that could be `while let`
661 // (also matches an explicit "match" instead of "if let")
662 // (even if the "match" or "if let" is used for declaration)
663 if let ExprKind
::Loop(block
, _
, LoopSource
::Loop
, _
) = expr
.kind
{
664 // also check for empty `loop {}` statements, skipping those in #[panic_handler]
665 empty_loop
::check(cx
, expr
, block
);
666 while_let_loop
::check(cx
, expr
, block
);
669 while_let_on_iterator
::check(cx
, expr
);
671 if let Some(higher
::While { condition, body }
) = higher
::While
::hir(expr
) {
672 while_immutable_condition
::check(cx
, condition
, body
);
673 missing_spin_loop
::check(cx
, condition
, body
);
676 needless_collect
::check(expr
, cx
);
680 fn check_for_loop
<'tcx
>(
681 cx
: &LateContext
<'tcx
>,
684 body
: &'tcx Expr
<'_
>,
685 expr
: &'tcx Expr
<'_
>,
688 let is_manual_memcpy_triggered
= manual_memcpy
::check(cx
, pat
, arg
, body
, expr
);
689 if !is_manual_memcpy_triggered
{
690 needless_range_loop
::check(cx
, pat
, arg
, body
, expr
);
691 explicit_counter_loop
::check(cx
, pat
, arg
, body
, expr
);
693 check_for_loop_arg(cx
, pat
, arg
);
694 for_kv_map
::check(cx
, pat
, arg
, body
);
695 mut_range_bound
::check(cx
, arg
, body
);
696 single_element_loop
::check(cx
, pat
, arg
, body
, expr
);
697 same_item_push
::check(cx
, pat
, arg
, body
, expr
);
698 manual_flatten
::check(cx
, pat
, arg
, body
, span
);
701 fn check_for_loop_arg(cx
: &LateContext
<'_
>, pat
: &Pat
<'_
>, arg
: &Expr
<'_
>) {
702 let mut next_loop_linted
= false; // whether or not ITER_NEXT_LOOP lint was used
704 if let ExprKind
::MethodCall(method
, [self_arg
], _
) = arg
.kind
{
705 let method_name
= method
.ident
.as_str();
706 // check for looping over x.iter() or x.iter_mut(), could use &x or &mut x
708 "iter" | "iter_mut" => {
709 explicit_iter_loop
::check(cx
, self_arg
, arg
, method_name
);
710 for_loops_over_fallibles
::check(cx
, pat
, self_arg
, Some(method_name
));
713 explicit_iter_loop
::check(cx
, self_arg
, arg
, method_name
);
714 explicit_into_iter_loop
::check(cx
, self_arg
, arg
);
715 for_loops_over_fallibles
::check(cx
, pat
, self_arg
, Some(method_name
));
718 next_loop_linted
= iter_next_loop
::check(cx
, arg
);
724 if !next_loop_linted
{
725 for_loops_over_fallibles
::check(cx
, pat
, arg
, None
);