2 mod explicit_counter_loop;
3 mod explicit_into_iter_loop;
4 mod explicit_iter_loop;
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 /// Detects `loop + match` combinations that are easier
178 /// written as a `while let` loop.
180 /// ### Why is this bad?
181 /// The `while let` loop is usually shorter and more
184 /// ### Known problems
185 /// Sometimes the wrong binding is displayed ([#383](https://github.com/rust-lang/rust-clippy/issues/383)).
189 /// # let y = Some(1);
191 /// let x = match y {
195 /// // .. do something with x
197 /// // is easier written as
198 /// while let Some(x) = y {
199 /// // .. do something with x
202 #[clippy::version = "pre 1.29.0"]
205 "`loop { if let { ... } else break }`, which can be written as a `while let` loop"
208 declare_clippy_lint! {
210 /// Checks for functions collecting an iterator when collect
213 /// ### Why is this bad?
214 /// `collect` causes the allocation of a new data structure,
215 /// when this allocation may not be needed.
219 /// # let iterator = vec![1].into_iter();
220 /// let len = iterator.clone().collect::<Vec<_>>().len();
222 /// let len = iterator.count();
224 #[clippy::version = "1.30.0"]
225 pub NEEDLESS_COLLECT,
227 "collecting an iterator when collect is not needed"
230 declare_clippy_lint! {
232 /// Checks `for` loops over slices with an explicit counter
233 /// and suggests the use of `.enumerate()`.
235 /// ### Why is this bad?
236 /// Using `.enumerate()` makes the intent more clear,
237 /// declutters the code and may be faster in some instances.
241 /// # let v = vec![1];
242 /// # fn bar(bar: usize, baz: usize) {}
252 /// # let v = vec![1];
253 /// # fn bar(bar: usize, baz: usize) {}
254 /// for (i, item) in v.iter().enumerate() { bar(i, *item); }
256 #[clippy::version = "pre 1.29.0"]
257 pub EXPLICIT_COUNTER_LOOP,
259 "for-looping with an explicit counter when `_.enumerate()` would do"
262 declare_clippy_lint! {
264 /// Checks for empty `loop` expressions.
266 /// ### Why is this bad?
267 /// These busy loops burn CPU cycles without doing
268 /// anything. It is _almost always_ a better idea to `panic!` than to have
271 /// If panicking isn't possible, think of the environment and either:
272 /// - block on something
273 /// - sleep the thread for some microseconds
274 /// - yield or pause the thread
276 /// For `std` targets, this can be done with
277 /// [`std::thread::sleep`](https://doc.rust-lang.org/std/thread/fn.sleep.html)
278 /// or [`std::thread::yield_now`](https://doc.rust-lang.org/std/thread/fn.yield_now.html).
280 /// For `no_std` targets, doing this is more complicated, especially because
281 /// `#[panic_handler]`s can't panic. To stop/pause the thread, you will
282 /// probably need to invoke some target-specific intrinsic. Examples include:
283 /// - [`x86_64::instructions::hlt`](https://docs.rs/x86_64/0.12.2/x86_64/instructions/fn.hlt.html)
284 /// - [`cortex_m::asm::wfi`](https://docs.rs/cortex-m/0.6.3/cortex_m/asm/fn.wfi.html)
290 #[clippy::version = "pre 1.29.0"]
293 "empty `loop {}`, which should block or sleep"
296 declare_clippy_lint! {
298 /// Checks for `while let` expressions on iterators.
300 /// ### Why is this bad?
301 /// Readability. A simple `for` loop is shorter and conveys
302 /// the intent better.
306 /// while let Some(val) = iter.next() {
313 /// for val in &mut iter {
317 #[clippy::version = "pre 1.29.0"]
318 pub WHILE_LET_ON_ITERATOR,
320 "using a `while let` loop instead of a for loop on an iterator"
323 declare_clippy_lint! {
325 /// Checks for iterating a map (`HashMap` or `BTreeMap`) and
326 /// ignoring either the keys or values.
328 /// ### Why is this bad?
329 /// Readability. There are `keys` and `values` methods that
330 /// can be used to express that don't need the values or keys.
334 /// for (k, _) in &map {
339 /// could be replaced by
342 /// for k in map.keys() {
346 #[clippy::version = "pre 1.29.0"]
349 "looping on a map using `iter` when `keys` or `values` would do"
352 declare_clippy_lint! {
354 /// Checks for loops that will always `break`, `return` or
355 /// `continue` an outer loop.
357 /// ### Why is this bad?
358 /// This loop never loops, all it does is obfuscating the
368 #[clippy::version = "pre 1.29.0"]
371 "any loop that will always `break` or `return`"
374 declare_clippy_lint! {
376 /// Checks for loops which have a range bound that is a mutable variable
378 /// ### Why is this bad?
379 /// One might think that modifying the mutable variable changes the loop bounds
381 /// ### Known problems
382 /// False positive when mutation is followed by a `break`, but the `break` is not immediately
383 /// after the mutation:
388 /// x += 1; // x is a range bound that is mutated
389 /// ..; // some other expression
390 /// break; // leaves the loop, so mutation is not an issue
394 /// False positive on nested loops ([#6072](https://github.com/rust-lang/rust-clippy/issues/6072))
398 /// let mut foo = 42;
399 /// for i in 0..foo {
401 /// println!("{}", i); // prints numbers from 0 to 42, not 0 to 21
404 #[clippy::version = "pre 1.29.0"]
407 "for loop over a range where one of the bounds is a mutable variable"
410 declare_clippy_lint! {
412 /// Checks whether variables used within while loop condition
413 /// can be (and are) mutated in the body.
415 /// ### Why is this bad?
416 /// If the condition is unchanged, entering the body of the loop
417 /// will lead to an infinite loop.
419 /// ### Known problems
420 /// If the `while`-loop is in a closure, the check for mutation of the
421 /// condition variables in the body can cause false negatives. For example when only `Upvar` `a` is
422 /// in the condition and only `Upvar` `b` gets mutated in the body, the lint will not trigger.
428 /// println!("let me loop forever!");
431 #[clippy::version = "pre 1.29.0"]
432 pub WHILE_IMMUTABLE_CONDITION,
434 "variables used within while expression are not mutated in the body"
437 declare_clippy_lint! {
439 /// Checks whether a for loop is being used to push a constant
440 /// value into a Vec.
442 /// ### Why is this bad?
443 /// This kind of operation can be expressed more succinctly with
444 /// `vec![item; SIZE]` or `vec.resize(NEW_SIZE, item)` and using these alternatives may also
445 /// have better performance.
451 /// let mut vec: Vec<u8> = Vec::new();
464 /// let mut vec: Vec<u8> = vec![item1; 20];
465 /// vec.resize(20 + 30, item2);
467 #[clippy::version = "1.47.0"]
470 "the same item is pushed inside of a for loop"
473 declare_clippy_lint! {
475 /// Checks whether a for loop has a single element.
477 /// ### Why is this bad?
478 /// There is no reason to have a loop of a
484 /// for item in &[item1] {
485 /// println!("{}", item);
492 /// let item = &item1;
493 /// println!("{}", item);
495 #[clippy::version = "1.49.0"]
496 pub SINGLE_ELEMENT_LOOP,
498 "there is no reason to have a single element loop"
501 declare_clippy_lint! {
503 /// Check for unnecessary `if let` usage in a for loop
504 /// where only the `Some` or `Ok` variant of the iterator element is used.
506 /// ### Why is this bad?
507 /// It is verbose and can be simplified
508 /// by first calling the `flatten` method on the `Iterator`.
513 /// let x = vec![Some(1), Some(2), Some(3)];
515 /// if let Some(n) = n {
516 /// println!("{}", n);
522 /// let x = vec![Some(1), Some(2), Some(3)];
523 /// for n in x.into_iter().flatten() {
524 /// println!("{}", n);
527 #[clippy::version = "1.52.0"]
530 "for loops over `Option`s or `Result`s with a single expression can be simplified"
533 declare_clippy_lint! {
535 /// Check for empty spin loops
537 /// ### Why is this bad?
538 /// The loop body should have something like `thread::park()` or at least
539 /// `std::hint::spin_loop()` to avoid needlessly burning cycles and conserve
540 /// energy. Perhaps even better use an actual lock, if possible.
542 /// ### Known problems
543 /// This lint doesn't currently trigger on `while let` or
544 /// `loop { match .. { .. } }` loops, which would be considered idiomatic in
545 /// combination with e.g. `AtomicBool::compare_exchange_weak`.
550 /// use core::sync::atomic::{AtomicBool, Ordering};
551 /// let b = AtomicBool::new(true);
552 /// // give a ref to `b` to another thread,wait for it to become false
553 /// while b.load(Ordering::Acquire) {};
557 ///# use core::sync::atomic::{AtomicBool, Ordering};
558 ///# let b = AtomicBool::new(true);
559 /// while b.load(Ordering::Acquire) {
560 /// std::hint::spin_loop()
563 #[clippy::version = "1.61.0"]
564 pub MISSING_SPIN_LOOP,
566 "An empty busy waiting loop"
569 declare_clippy_lint! {
571 /// Check for manual implementations of Iterator::find
573 /// ### Why is this bad?
574 /// It doesn't affect performance, but using `find` is shorter and easier to read.
579 /// fn example(arr: Vec<i32>) -> Option<i32> {
590 /// fn example(arr: Vec<i32>) -> Option<i32> {
591 /// arr.into_iter().find(|&el| el == 1)
594 #[clippy::version = "1.64.0"]
597 "manual implementation of `Iterator::find`"
600 declare_lint_pass!(Loops => [
605 EXPLICIT_INTO_ITER_LOOP,
609 EXPLICIT_COUNTER_LOOP,
611 WHILE_LET_ON_ITERATOR,
615 WHILE_IMMUTABLE_CONDITION,
622 impl<'tcx> LateLintPass<'tcx> for Loops {
623 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
624 let for_loop = higher::ForLoop::hir(expr);
625 if let Some(higher::ForLoop {
633 // we don't want to check expanded macros
634 // this check is not at the top of the function
635 // since higher::for_loop expressions are marked as expansions
636 if body.span.from_expansion() {
639 check_for_loop(cx, pat, arg, body, expr, span);
640 if let ExprKind::Block(block, _) = body.kind {
641 never_loop::check(cx, block, loop_id, span, for_loop.as_ref());
645 // we don't want to check expanded macros
646 if expr.span.from_expansion() {
650 // check for never_loop
651 if let ExprKind::Loop(block, ..) = expr.kind {
652 never_loop::check(cx, block, expr.hir_id, expr.span, None);
655 // check for `loop { if let {} else break }` that could be `while let`
656 // (also matches an explicit "match" instead of "if let")
657 // (even if the "match" or "if let" is used for declaration)
658 if let ExprKind::Loop(block, _, LoopSource::Loop, _) = expr.kind {
659 // also check for empty `loop {}` statements, skipping those in #[panic_handler]
660 empty_loop::check(cx, expr, block);
661 while_let_loop::check(cx, expr, block);
664 while_let_on_iterator::check(cx, expr);
666 if let Some(higher::While { condition, body }) = higher::While::hir(expr) {
667 while_immutable_condition::check(cx, condition, body);
668 missing_spin_loop::check(cx, condition, body);
671 needless_collect::check(expr, cx);
675 fn check_for_loop<'tcx>(
676 cx: &LateContext<'tcx>,
679 body: &'tcx Expr<'_>,
680 expr: &'tcx Expr<'_>,
683 let is_manual_memcpy_triggered = manual_memcpy::check(cx, pat, arg, body, expr);
684 if !is_manual_memcpy_triggered {
685 needless_range_loop::check(cx, pat, arg, body, expr);
686 explicit_counter_loop::check(cx, pat, arg, body, expr);
688 check_for_loop_arg(cx, pat, arg);
689 for_kv_map::check(cx, pat, arg, body);
690 mut_range_bound::check(cx, arg, body);
691 single_element_loop::check(cx, pat, arg, body, expr);
692 same_item_push::check(cx, pat, arg, body, expr);
693 manual_flatten::check(cx, pat, arg, body, span);
694 manual_find::check(cx, pat, arg, body, span, expr);
697 fn check_for_loop_arg(cx: &LateContext<'_>, _: &Pat<'_>, arg: &Expr<'_>) {
698 if let ExprKind::MethodCall(method, self_arg, [], _) = arg.kind {
699 let method_name = method.ident.as_str();
700 // check for looping over x.iter() or x.iter_mut(), could use &x or &mut x
702 "iter" | "iter_mut" => {
703 explicit_iter_loop::check(cx, self_arg, arg, method_name);
706 explicit_iter_loop::check(cx, self_arg, arg, method_name);
707 explicit_into_iter_loop::check(cx, self_arg, arg);
710 iter_next_loop::check(cx, arg);