2 mod explicit_counter_loop;
4 mod for_loop_over_map_kv;
6 mod for_mut_range_bound;
7 mod for_single_element_loop;
16 mod while_let_on_iterator;
18 use crate::utils::higher;
19 use rustc_hir::{Expr, ExprKind, LoopSource, Pat};
20 use rustc_lint::{LateContext, LateLintPass};
21 use rustc_session::{declare_lint_pass, declare_tool_lint};
22 use rustc_span::source_map::Span;
23 use utils::{get_span_of_entire_for_loop, make_iterator_snippet, IncrementVisitor, InitializeVisitor};
25 declare_clippy_lint! {
26 /// **What it does:** Checks for for-loops that manually copy items between
27 /// slices that could be optimized by having a memcpy.
29 /// **Why is this bad?** It is not as fast as a memcpy.
31 /// **Known problems:** None.
35 /// # let src = vec![1];
36 /// # let mut dst = vec![0; 65];
37 /// for i in 0..src.len() {
38 /// dst[i + 64] = src[i];
41 /// Could be written as:
43 /// # let src = vec![1];
44 /// # let mut dst = vec![0; 65];
45 /// dst[64..(src.len() + 64)].clone_from_slice(&src[..]);
49 "manually copying items between slices"
52 declare_clippy_lint! {
53 /// **What it does:** Checks for looping over the range of `0..len` of some
54 /// collection just to get the values by index.
56 /// **Why is this bad?** Just iterating the collection itself makes the intent
57 /// more clear and is probably faster.
59 /// **Known problems:** None.
63 /// let vec = vec!['a', 'b', 'c'];
64 /// for i in 0..vec.len() {
65 /// println!("{}", vec[i]);
68 /// Could be written as:
70 /// let vec = vec!['a', 'b', 'c'];
72 /// println!("{}", i);
75 pub NEEDLESS_RANGE_LOOP,
77 "for-looping over a range of indices where an iterator over items would do"
80 declare_clippy_lint! {
81 /// **What it does:** Checks for loops on `x.iter()` where `&x` will do, and
82 /// suggests the latter.
84 /// **Why is this bad?** Readability.
86 /// **Known problems:** False negatives. We currently only warn on some known
91 /// // with `y` a `Vec` or slice:
92 /// # let y = vec![1];
93 /// for x in y.iter() {
97 /// can be rewritten to
99 /// # let y = vec![1];
104 pub EXPLICIT_ITER_LOOP,
106 "for-looping over `_.iter()` or `_.iter_mut()` when `&_` or `&mut _` would do"
109 declare_clippy_lint! {
110 /// **What it does:** Checks for loops on `y.into_iter()` where `y` will do, and
111 /// suggests the latter.
113 /// **Why is this bad?** Readability.
115 /// **Known problems:** None
119 /// # let y = vec![1];
120 /// // with `y` a `Vec` or slice:
121 /// for x in y.into_iter() {
125 /// can be rewritten to
127 /// # let y = vec![1];
132 pub EXPLICIT_INTO_ITER_LOOP,
134 "for-looping over `_.into_iter()` when `_` would do"
137 declare_clippy_lint! {
138 /// **What it does:** Checks for loops on `x.next()`.
140 /// **Why is this bad?** `next()` returns either `Some(value)` if there was a
141 /// value, or `None` otherwise. The insidious thing is that `Option<_>`
142 /// implements `IntoIterator`, so that possibly one value will be iterated,
143 /// leading to some hard to find bugs. No one will want to write such code
144 /// [except to win an Underhanded Rust
145 /// Contest](https://www.reddit.com/r/rust/comments/3hb0wm/underhanded_rust_contest/cu5yuhr).
147 /// **Known problems:** None.
151 /// for x in y.next() {
157 "for-looping over `_.next()` which is probably not intended"
160 declare_clippy_lint! {
161 /// **What it does:** Checks for `for` loops over `Option` or `Result` values.
163 /// **Why is this bad?** Readability. This is more clearly expressed as an `if
166 /// **Known problems:** None.
170 /// # let opt = Some(1);
178 /// if let Some(x) = opt {
186 /// # let res: Result<i32, std::io::Error> = Ok(1);
194 /// if let Ok(x) = res {
198 pub FOR_LOOPS_OVER_FALLIBLES,
200 "for-looping over an `Option` or a `Result`, which is more clearly expressed as an `if let`"
203 declare_clippy_lint! {
204 /// **What it does:** Detects `loop + match` combinations that are easier
205 /// written as a `while let` loop.
207 /// **Why is this bad?** The `while let` loop is usually shorter and more
210 /// **Known problems:** Sometimes the wrong binding is displayed ([#383](https://github.com/rust-lang/rust-clippy/issues/383)).
214 /// # let y = Some(1);
216 /// let x = match y {
220 /// // .. do something with x
222 /// // is easier written as
223 /// while let Some(x) = y {
224 /// // .. do something with x
229 "`loop { if let { ... } else break }`, which can be written as a `while let` loop"
232 declare_clippy_lint! {
233 /// **What it does:** Checks for functions collecting an iterator when collect
236 /// **Why is this bad?** `collect` causes the allocation of a new data structure,
237 /// when this allocation may not be needed.
239 /// **Known problems:**
244 /// # let iterator = vec![1].into_iter();
245 /// let len = iterator.clone().collect::<Vec<_>>().len();
247 /// let len = iterator.count();
249 pub NEEDLESS_COLLECT,
251 "collecting an iterator when collect is not needed"
254 declare_clippy_lint! {
255 /// **What it does:** Checks `for` loops over slices with an explicit counter
256 /// and suggests the use of `.enumerate()`.
258 /// **Why is it bad?** Using `.enumerate()` makes the intent more clear,
259 /// declutters the code and may be faster in some instances.
261 /// **Known problems:** None.
265 /// # let v = vec![1];
266 /// # fn bar(bar: usize, baz: usize) {}
273 /// Could be written as
275 /// # let v = vec![1];
276 /// # fn bar(bar: usize, baz: usize) {}
277 /// for (i, item) in v.iter().enumerate() { bar(i, *item); }
279 pub EXPLICIT_COUNTER_LOOP,
281 "for-looping with an explicit counter when `_.enumerate()` would do"
284 declare_clippy_lint! {
285 /// **What it does:** Checks for empty `loop` expressions.
287 /// **Why is this bad?** These busy loops burn CPU cycles without doing
288 /// anything. It is _almost always_ a better idea to `panic!` than to have
291 /// If panicking isn't possible, think of the environment and either:
292 /// - block on something
293 /// - sleep the thread for some microseconds
294 /// - yield or pause the thread
296 /// For `std` targets, this can be done with
297 /// [`std::thread::sleep`](https://doc.rust-lang.org/std/thread/fn.sleep.html)
298 /// or [`std::thread::yield_now`](https://doc.rust-lang.org/std/thread/fn.yield_now.html).
300 /// For `no_std` targets, doing this is more complicated, especially because
301 /// `#[panic_handler]`s can't panic. To stop/pause the thread, you will
302 /// probably need to invoke some target-specific intrinsic. Examples include:
303 /// - [`x86_64::instructions::hlt`](https://docs.rs/x86_64/0.12.2/x86_64/instructions/fn.hlt.html)
304 /// - [`cortex_m::asm::wfi`](https://docs.rs/cortex-m/0.6.3/cortex_m/asm/fn.wfi.html)
306 /// **Known problems:** None.
314 "empty `loop {}`, which should block or sleep"
317 declare_clippy_lint! {
318 /// **What it does:** Checks for `while let` expressions on iterators.
320 /// **Why is this bad?** Readability. A simple `for` loop is shorter and conveys
321 /// the intent better.
323 /// **Known problems:** None.
327 /// while let Some(val) = iter() {
331 pub WHILE_LET_ON_ITERATOR,
333 "using a `while let` loop instead of a for loop on an iterator"
336 declare_clippy_lint! {
337 /// **What it does:** Checks for iterating a map (`HashMap` or `BTreeMap`) and
338 /// ignoring either the keys or values.
340 /// **Why is this bad?** Readability. There are `keys` and `values` methods that
341 /// can be used to express that don't need the values or keys.
343 /// **Known problems:** None.
347 /// for (k, _) in &map {
352 /// could be replaced by
355 /// for k in map.keys() {
361 "looping on a map using `iter` when `keys` or `values` would do"
364 declare_clippy_lint! {
365 /// **What it does:** Checks for loops that will always `break`, `return` or
366 /// `continue` an outer loop.
368 /// **Why is this bad?** This loop never loops, all it does is obfuscating the
371 /// **Known problems:** None
382 "any loop that will always `break` or `return`"
385 declare_clippy_lint! {
386 /// **What it does:** Checks for loops which have a range bound that is a mutable variable
388 /// **Why is this bad?** One might think that modifying the mutable variable changes the loop bounds
390 /// **Known problems:** None
394 /// let mut foo = 42;
395 /// for i in 0..foo {
397 /// println!("{}", i); // prints numbers from 0 to 42, not 0 to 21
402 "for loop over a range where one of the bounds is a mutable variable"
405 declare_clippy_lint! {
406 /// **What it does:** Checks whether variables used within while loop condition
407 /// can be (and are) mutated in the body.
409 /// **Why is this bad?** If the condition is unchanged, entering the body of the loop
410 /// will lead to an infinite loop.
412 /// **Known problems:** If the `while`-loop is in a closure, the check for mutation of the
413 /// condition variables in the body can cause false negatives. For example when only `Upvar` `a` is
414 /// in the condition and only `Upvar` `b` gets mutated in the body, the lint will not trigger.
420 /// println!("let me loop forever!");
423 pub WHILE_IMMUTABLE_CONDITION,
425 "variables used within while expression are not mutated in the body"
428 declare_clippy_lint! {
429 /// **What it does:** Checks whether a for loop is being used to push a constant
430 /// value into a Vec.
432 /// **Why is this bad?** This kind of operation can be expressed more succinctly with
433 /// `vec![item;SIZE]` or `vec.resize(NEW_SIZE, item)` and using these alternatives may also
434 /// have better performance.
435 /// **Known problems:** None
441 /// let mut vec: Vec<u8> = Vec::new();
449 /// could be written as
453 /// let mut vec: Vec<u8> = vec![item1; 20];
454 /// vec.resize(20 + 30, item2);
458 "the same item is pushed inside of a for loop"
461 declare_clippy_lint! {
462 /// **What it does:** Checks whether a for loop has a single element.
464 /// **Why is this bad?** There is no reason to have a loop of a
466 /// **Known problems:** None
471 /// for item in &[item1] {
472 /// println!("{}", item);
475 /// could be written as
478 /// let item = &item1;
479 /// println!("{}", item);
481 pub SINGLE_ELEMENT_LOOP,
483 "there is no reason to have a single element loop"
486 declare_clippy_lint! {
487 /// **What it does:** Check for unnecessary `if let` usage in a for loop
488 /// where only the `Some` or `Ok` variant of the iterator element is used.
490 /// **Why is this bad?** It is verbose and can be simplified
491 /// by first calling the `flatten` method on the `Iterator`.
493 /// **Known problems:** None.
498 /// let x = vec![Some(1), Some(2), Some(3)];
500 /// if let Some(n) = n {
501 /// println!("{}", n);
507 /// let x = vec![Some(1), Some(2), Some(3)];
508 /// for n in x.into_iter().flatten() {
509 /// println!("{}", n);
514 "for loops over `Option`s or `Result`s with a single expression can be simplified"
517 declare_lint_pass!(Loops => [
522 EXPLICIT_INTO_ITER_LOOP,
524 FOR_LOOPS_OVER_FALLIBLES,
527 EXPLICIT_COUNTER_LOOP,
529 WHILE_LET_ON_ITERATOR,
533 WHILE_IMMUTABLE_CONDITION,
538 impl<'tcx> LateLintPass<'tcx> for Loops {
539 #[allow(clippy::too_many_lines)]
540 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
541 if let Some((pat, arg, body, span)) = higher::for_loop(expr) {
542 // we don't want to check expanded macros
543 // this check is not at the top of the function
544 // since higher::for_loop expressions are marked as expansions
545 if body.span.from_expansion() {
548 check_for_loop(cx, pat, arg, body, expr, span);
551 // we don't want to check expanded macros
552 if expr.span.from_expansion() {
556 // check for never_loop
557 never_loop::check_never_loop(cx, expr);
559 // check for `loop { if let {} else break }` that could be `while let`
560 // (also matches an explicit "match" instead of "if let")
561 // (even if the "match" or "if let" is used for declaration)
562 if let ExprKind::Loop(ref block, _, LoopSource::Loop, _) = expr.kind {
563 // also check for empty `loop {}` statements, skipping those in #[panic_handler]
564 empty_loop::check_empty_loop(cx, expr, block);
565 while_let_loop::check_while_let_loop(cx, expr, block);
568 while_let_on_iterator::check_while_let_on_iterator(cx, expr);
570 if let Some((cond, body)) = higher::while_loop(&expr) {
571 infinite_loop::check_infinite_loop(cx, cond, body);
574 needless_collect::check_needless_collect(expr, cx);
578 fn check_for_loop<'tcx>(
579 cx: &LateContext<'tcx>,
582 body: &'tcx Expr<'_>,
583 expr: &'tcx Expr<'_>,
586 let is_manual_memcpy_triggered = manual_memcpy::detect_manual_memcpy(cx, pat, arg, body, expr);
587 if !is_manual_memcpy_triggered {
588 for_loop_range::check_for_loop_range(cx, pat, arg, body, expr);
589 explicit_counter_loop::check_for_loop_explicit_counter(cx, pat, arg, body, expr);
591 for_loop_arg::check_for_loop_arg(cx, pat, arg, expr);
592 for_loop_over_map_kv::check_for_loop_over_map_kv(cx, pat, arg, body, expr);
593 for_mut_range_bound::check_for_mut_range_bound(cx, arg, body);
594 for_single_element_loop::check_for_single_element_loop(cx, pat, arg, body, expr);
595 same_item_push::detect_same_item_push(cx, pat, arg, body, expr);
596 manual_flatten::check_manual_flatten(cx, pat, arg, body, span);