]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/loops.rs
Remove hir::Expr::attrs.
[rust.git] / clippy_lints / src / loops.rs
1 use crate::consts::constant;
2 use crate::utils::sugg::Sugg;
3 use crate::utils::usage::mutated_variables;
4 use crate::utils::visitors::LocalUsedVisitor;
5 use crate::utils::{
6     contains_name, get_enclosing_block, get_parent_expr, get_trait_def_id, has_iter_method, higher, implements_trait,
7     indent_of, is_in_panic_handler, is_integer_const, is_no_std_crate, is_ok_ctor, is_refutable, is_some_ctor,
8     is_type_diagnostic_item, last_path_segment, match_trait_method, match_type, multispan_sugg, path_to_local,
9     path_to_local_id, paths, single_segment_path, snippet, snippet_with_applicability, snippet_with_macro_callsite,
10     span_lint, span_lint_and_help, span_lint_and_sugg, span_lint_and_then, sugg, SpanlessEq,
11 };
12 use if_chain::if_chain;
13 use rustc_ast::ast;
14 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
15 use rustc_errors::Applicability;
16 use rustc_hir::def::{DefKind, Res};
17 use rustc_hir::intravisit::{walk_block, walk_expr, walk_pat, walk_stmt, NestedVisitorMap, Visitor};
18 use rustc_hir::{
19     def_id, BinOpKind, BindingAnnotation, Block, BorrowKind, Expr, ExprKind, GenericArg, HirId, InlineAsmOperand,
20     Local, LoopSource, MatchSource, Mutability, Node, Pat, PatKind, QPath, Stmt, StmtKind,
21 };
22 use rustc_infer::infer::TyCtxtInferExt;
23 use rustc_lint::{LateContext, LateLintPass, LintContext};
24 use rustc_middle::hir::map::Map;
25 use rustc_middle::lint::in_external_macro;
26 use rustc_middle::middle::region;
27 use rustc_middle::ty::{self, Ty, TyS};
28 use rustc_session::{declare_lint_pass, declare_tool_lint};
29 use rustc_span::source_map::Span;
30 use rustc_span::symbol::{sym, Ident, Symbol};
31 use rustc_typeck::expr_use_visitor::{ConsumeMode, Delegate, ExprUseVisitor, PlaceBase, PlaceWithHirId};
32 use std::iter::{once, Iterator};
33 use std::mem;
34
35 declare_clippy_lint! {
36     /// **What it does:** Checks for for-loops that manually copy items between
37     /// slices that could be optimized by having a memcpy.
38     ///
39     /// **Why is this bad?** It is not as fast as a memcpy.
40     ///
41     /// **Known problems:** None.
42     ///
43     /// **Example:**
44     /// ```rust
45     /// # let src = vec![1];
46     /// # let mut dst = vec![0; 65];
47     /// for i in 0..src.len() {
48     ///     dst[i + 64] = src[i];
49     /// }
50     /// ```
51     /// Could be written as:
52     /// ```rust
53     /// # let src = vec![1];
54     /// # let mut dst = vec![0; 65];
55     /// dst[64..(src.len() + 64)].clone_from_slice(&src[..]);
56     /// ```
57     pub MANUAL_MEMCPY,
58     perf,
59     "manually copying items between slices"
60 }
61
62 declare_clippy_lint! {
63     /// **What it does:** Checks for looping over the range of `0..len` of some
64     /// collection just to get the values by index.
65     ///
66     /// **Why is this bad?** Just iterating the collection itself makes the intent
67     /// more clear and is probably faster.
68     ///
69     /// **Known problems:** None.
70     ///
71     /// **Example:**
72     /// ```rust
73     /// let vec = vec!['a', 'b', 'c'];
74     /// for i in 0..vec.len() {
75     ///     println!("{}", vec[i]);
76     /// }
77     /// ```
78     /// Could be written as:
79     /// ```rust
80     /// let vec = vec!['a', 'b', 'c'];
81     /// for i in vec {
82     ///     println!("{}", i);
83     /// }
84     /// ```
85     pub NEEDLESS_RANGE_LOOP,
86     style,
87     "for-looping over a range of indices where an iterator over items would do"
88 }
89
90 declare_clippy_lint! {
91     /// **What it does:** Checks for loops on `x.iter()` where `&x` will do, and
92     /// suggests the latter.
93     ///
94     /// **Why is this bad?** Readability.
95     ///
96     /// **Known problems:** False negatives. We currently only warn on some known
97     /// types.
98     ///
99     /// **Example:**
100     /// ```rust
101     /// // with `y` a `Vec` or slice:
102     /// # let y = vec![1];
103     /// for x in y.iter() {
104     ///     // ..
105     /// }
106     /// ```
107     /// can be rewritten to
108     /// ```rust
109     /// # let y = vec![1];
110     /// for x in &y {
111     ///     // ..
112     /// }
113     /// ```
114     pub EXPLICIT_ITER_LOOP,
115     pedantic,
116     "for-looping over `_.iter()` or `_.iter_mut()` when `&_` or `&mut _` would do"
117 }
118
119 declare_clippy_lint! {
120     /// **What it does:** Checks for loops on `y.into_iter()` where `y` will do, and
121     /// suggests the latter.
122     ///
123     /// **Why is this bad?** Readability.
124     ///
125     /// **Known problems:** None
126     ///
127     /// **Example:**
128     /// ```rust
129     /// # let y = vec![1];
130     /// // with `y` a `Vec` or slice:
131     /// for x in y.into_iter() {
132     ///     // ..
133     /// }
134     /// ```
135     /// can be rewritten to
136     /// ```rust
137     /// # let y = vec![1];
138     /// for x in y {
139     ///     // ..
140     /// }
141     /// ```
142     pub EXPLICIT_INTO_ITER_LOOP,
143     pedantic,
144     "for-looping over `_.into_iter()` when `_` would do"
145 }
146
147 declare_clippy_lint! {
148     /// **What it does:** Checks for loops on `x.next()`.
149     ///
150     /// **Why is this bad?** `next()` returns either `Some(value)` if there was a
151     /// value, or `None` otherwise. The insidious thing is that `Option<_>`
152     /// implements `IntoIterator`, so that possibly one value will be iterated,
153     /// leading to some hard to find bugs. No one will want to write such code
154     /// [except to win an Underhanded Rust
155     /// Contest](https://www.reddit.com/r/rust/comments/3hb0wm/underhanded_rust_contest/cu5yuhr).
156     ///
157     /// **Known problems:** None.
158     ///
159     /// **Example:**
160     /// ```ignore
161     /// for x in y.next() {
162     ///     ..
163     /// }
164     /// ```
165     pub ITER_NEXT_LOOP,
166     correctness,
167     "for-looping over `_.next()` which is probably not intended"
168 }
169
170 declare_clippy_lint! {
171     /// **What it does:** Checks for `for` loops over `Option` or `Result` values.
172     ///
173     /// **Why is this bad?** Readability. This is more clearly expressed as an `if
174     /// let`.
175     ///
176     /// **Known problems:** None.
177     ///
178     /// **Example:**
179     /// ```rust
180     /// # let opt = Some(1);
181     ///
182     /// // Bad
183     /// for x in opt {
184     ///     // ..
185     /// }
186     ///
187     /// // Good
188     /// if let Some(x) = opt {
189     ///     // ..
190     /// }
191     /// ```
192     ///
193     /// // or
194     ///
195     /// ```rust
196     /// # let res: Result<i32, std::io::Error> = Ok(1);
197     ///
198     /// // Bad
199     /// for x in &res {
200     ///     // ..
201     /// }
202     ///
203     /// // Good
204     /// if let Ok(x) = res {
205     ///     // ..
206     /// }
207     /// ```
208     pub FOR_LOOPS_OVER_FALLIBLES,
209     correctness,
210     "for-looping over an `Option` or a `Result`, which is more clearly expressed as an `if let`"
211 }
212
213 declare_clippy_lint! {
214     /// **What it does:** Detects `loop + match` combinations that are easier
215     /// written as a `while let` loop.
216     ///
217     /// **Why is this bad?** The `while let` loop is usually shorter and more
218     /// readable.
219     ///
220     /// **Known problems:** Sometimes the wrong binding is displayed ([#383](https://github.com/rust-lang/rust-clippy/issues/383)).
221     ///
222     /// **Example:**
223     /// ```rust,no_run
224     /// # let y = Some(1);
225     /// loop {
226     ///     let x = match y {
227     ///         Some(x) => x,
228     ///         None => break,
229     ///     };
230     ///     // .. do something with x
231     /// }
232     /// // is easier written as
233     /// while let Some(x) = y {
234     ///     // .. do something with x
235     /// };
236     /// ```
237     pub WHILE_LET_LOOP,
238     complexity,
239     "`loop { if let { ... } else break }`, which can be written as a `while let` loop"
240 }
241
242 declare_clippy_lint! {
243     /// **What it does:** Checks for functions collecting an iterator when collect
244     /// is not needed.
245     ///
246     /// **Why is this bad?** `collect` causes the allocation of a new data structure,
247     /// when this allocation may not be needed.
248     ///
249     /// **Known problems:**
250     /// None
251     ///
252     /// **Example:**
253     /// ```rust
254     /// # let iterator = vec![1].into_iter();
255     /// let len = iterator.clone().collect::<Vec<_>>().len();
256     /// // should be
257     /// let len = iterator.count();
258     /// ```
259     pub NEEDLESS_COLLECT,
260     perf,
261     "collecting an iterator when collect is not needed"
262 }
263
264 declare_clippy_lint! {
265     /// **What it does:** Checks `for` loops over slices with an explicit counter
266     /// and suggests the use of `.enumerate()`.
267     ///
268     /// **Why is it bad?** Using `.enumerate()` makes the intent more clear,
269     /// declutters the code and may be faster in some instances.
270     ///
271     /// **Known problems:** None.
272     ///
273     /// **Example:**
274     /// ```rust
275     /// # let v = vec![1];
276     /// # fn bar(bar: usize, baz: usize) {}
277     /// let mut i = 0;
278     /// for item in &v {
279     ///     bar(i, *item);
280     ///     i += 1;
281     /// }
282     /// ```
283     /// Could be written as
284     /// ```rust
285     /// # let v = vec![1];
286     /// # fn bar(bar: usize, baz: usize) {}
287     /// for (i, item) in v.iter().enumerate() { bar(i, *item); }
288     /// ```
289     pub EXPLICIT_COUNTER_LOOP,
290     complexity,
291     "for-looping with an explicit counter when `_.enumerate()` would do"
292 }
293
294 declare_clippy_lint! {
295     /// **What it does:** Checks for empty `loop` expressions.
296     ///
297     /// **Why is this bad?** These busy loops burn CPU cycles without doing
298     /// anything. It is _almost always_ a better idea to `panic!` than to have
299     /// a busy loop.
300     ///
301     /// If panicking isn't possible, think of the environment and either:
302     ///   - block on something
303     ///   - sleep the thread for some microseconds
304     ///   - yield or pause the thread
305     ///
306     /// For `std` targets, this can be done with
307     /// [`std::thread::sleep`](https://doc.rust-lang.org/std/thread/fn.sleep.html)
308     /// or [`std::thread::yield_now`](https://doc.rust-lang.org/std/thread/fn.yield_now.html).
309     ///
310     /// For `no_std` targets, doing this is more complicated, especially because
311     /// `#[panic_handler]`s can't panic. To stop/pause the thread, you will
312     /// probably need to invoke some target-specific intrinsic. Examples include:
313     ///   - [`x86_64::instructions::hlt`](https://docs.rs/x86_64/0.12.2/x86_64/instructions/fn.hlt.html)
314     ///   - [`cortex_m::asm::wfi`](https://docs.rs/cortex-m/0.6.3/cortex_m/asm/fn.wfi.html)
315     ///
316     /// **Known problems:** None.
317     ///
318     /// **Example:**
319     /// ```no_run
320     /// loop {}
321     /// ```
322     pub EMPTY_LOOP,
323     style,
324     "empty `loop {}`, which should block or sleep"
325 }
326
327 declare_clippy_lint! {
328     /// **What it does:** Checks for `while let` expressions on iterators.
329     ///
330     /// **Why is this bad?** Readability. A simple `for` loop is shorter and conveys
331     /// the intent better.
332     ///
333     /// **Known problems:** None.
334     ///
335     /// **Example:**
336     /// ```ignore
337     /// while let Some(val) = iter() {
338     ///     ..
339     /// }
340     /// ```
341     pub WHILE_LET_ON_ITERATOR,
342     style,
343     "using a `while let` loop instead of a for loop on an iterator"
344 }
345
346 declare_clippy_lint! {
347     /// **What it does:** Checks for iterating a map (`HashMap` or `BTreeMap`) and
348     /// ignoring either the keys or values.
349     ///
350     /// **Why is this bad?** Readability. There are `keys` and `values` methods that
351     /// can be used to express that don't need the values or keys.
352     ///
353     /// **Known problems:** None.
354     ///
355     /// **Example:**
356     /// ```ignore
357     /// for (k, _) in &map {
358     ///     ..
359     /// }
360     /// ```
361     ///
362     /// could be replaced by
363     ///
364     /// ```ignore
365     /// for k in map.keys() {
366     ///     ..
367     /// }
368     /// ```
369     pub FOR_KV_MAP,
370     style,
371     "looping on a map using `iter` when `keys` or `values` would do"
372 }
373
374 declare_clippy_lint! {
375     /// **What it does:** Checks for loops that will always `break`, `return` or
376     /// `continue` an outer loop.
377     ///
378     /// **Why is this bad?** This loop never loops, all it does is obfuscating the
379     /// code.
380     ///
381     /// **Known problems:** None
382     ///
383     /// **Example:**
384     /// ```rust
385     /// loop {
386     ///     ..;
387     ///     break;
388     /// }
389     /// ```
390     pub NEVER_LOOP,
391     correctness,
392     "any loop that will always `break` or `return`"
393 }
394
395 declare_clippy_lint! {
396     /// **What it does:** Checks for loops which have a range bound that is a mutable variable
397     ///
398     /// **Why is this bad?** One might think that modifying the mutable variable changes the loop bounds
399     ///
400     /// **Known problems:** None
401     ///
402     /// **Example:**
403     /// ```rust
404     /// let mut foo = 42;
405     /// for i in 0..foo {
406     ///     foo -= 1;
407     ///     println!("{}", i); // prints numbers from 0 to 42, not 0 to 21
408     /// }
409     /// ```
410     pub MUT_RANGE_BOUND,
411     complexity,
412     "for loop over a range where one of the bounds is a mutable variable"
413 }
414
415 declare_clippy_lint! {
416     /// **What it does:** Checks whether variables used within while loop condition
417     /// can be (and are) mutated in the body.
418     ///
419     /// **Why is this bad?** If the condition is unchanged, entering the body of the loop
420     /// will lead to an infinite loop.
421     ///
422     /// **Known problems:** If the `while`-loop is in a closure, the check for mutation of the
423     /// condition variables in the body can cause false negatives. For example when only `Upvar` `a` is
424     /// in the condition and only `Upvar` `b` gets mutated in the body, the lint will not trigger.
425     ///
426     /// **Example:**
427     /// ```rust
428     /// let i = 0;
429     /// while i > 10 {
430     ///     println!("let me loop forever!");
431     /// }
432     /// ```
433     pub WHILE_IMMUTABLE_CONDITION,
434     correctness,
435     "variables used within while expression are not mutated in the body"
436 }
437
438 declare_clippy_lint! {
439     /// **What it does:** Checks whether a for loop is being used to push a constant
440     /// value into a Vec.
441     ///
442     /// **Why is this bad?** This kind of operation can be expressed more succinctly with
443     /// `vec![item;SIZE]` or `vec.resize(NEW_SIZE, item)` and using these alternatives may also
444     /// have better performance.
445     /// **Known problems:** None
446     ///
447     /// **Example:**
448     /// ```rust
449     /// let item1 = 2;
450     /// let item2 = 3;
451     /// let mut vec: Vec<u8> = Vec::new();
452     /// for _ in 0..20 {
453     ///    vec.push(item1);
454     /// }
455     /// for _ in 0..30 {
456     ///     vec.push(item2);
457     /// }
458     /// ```
459     /// could be written as
460     /// ```rust
461     /// let item1 = 2;
462     /// let item2 = 3;
463     /// let mut vec: Vec<u8> = vec![item1; 20];
464     /// vec.resize(20 + 30, item2);
465     /// ```
466     pub SAME_ITEM_PUSH,
467     style,
468     "the same item is pushed inside of a for loop"
469 }
470
471 declare_clippy_lint! {
472     /// **What it does:** Checks whether a for loop has a single element.
473     ///
474     /// **Why is this bad?** There is no reason to have a loop of a
475     /// single element.
476     /// **Known problems:** None
477     ///
478     /// **Example:**
479     /// ```rust
480     /// let item1 = 2;
481     /// for item in &[item1] {
482     ///     println!("{}", item);
483     /// }
484     /// ```
485     /// could be written as
486     /// ```rust
487     /// let item1 = 2;
488     /// let item = &item1;
489     /// println!("{}", item);
490     /// ```
491     pub SINGLE_ELEMENT_LOOP,
492     complexity,
493     "there is no reason to have a single element loop"
494 }
495
496 declare_clippy_lint! {
497     /// **What it does:** Check for unnecessary `if let` usage in a for loop
498     /// where only the `Some` or `Ok` variant of the iterator element is used.
499     ///
500     /// **Why is this bad?** It is verbose and can be simplified
501     /// by first calling the `flatten` method on the `Iterator`.
502     ///
503     /// **Known problems:** None.
504     ///
505     /// **Example:**
506     ///
507     /// ```rust
508     /// let x = vec![Some(1), Some(2), Some(3)];
509     /// for n in x {
510     ///     if let Some(n) = n {
511     ///         println!("{}", n);
512     ///     }
513     /// }
514     /// ```
515     /// Use instead:
516     /// ```rust
517     /// let x = vec![Some(1), Some(2), Some(3)];
518     /// for n in x.into_iter().flatten() {
519     ///     println!("{}", n);
520     /// }
521     /// ```
522     pub MANUAL_FLATTEN,
523     complexity,
524     "for loops over `Option`s or `Result`s with a single expression can be simplified"
525 }
526
527 declare_lint_pass!(Loops => [
528     MANUAL_MEMCPY,
529     MANUAL_FLATTEN,
530     NEEDLESS_RANGE_LOOP,
531     EXPLICIT_ITER_LOOP,
532     EXPLICIT_INTO_ITER_LOOP,
533     ITER_NEXT_LOOP,
534     FOR_LOOPS_OVER_FALLIBLES,
535     WHILE_LET_LOOP,
536     NEEDLESS_COLLECT,
537     EXPLICIT_COUNTER_LOOP,
538     EMPTY_LOOP,
539     WHILE_LET_ON_ITERATOR,
540     FOR_KV_MAP,
541     NEVER_LOOP,
542     MUT_RANGE_BOUND,
543     WHILE_IMMUTABLE_CONDITION,
544     SAME_ITEM_PUSH,
545     SINGLE_ELEMENT_LOOP,
546 ]);
547
548 impl<'tcx> LateLintPass<'tcx> for Loops {
549     #[allow(clippy::too_many_lines)]
550     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
551         if let Some((pat, arg, body, span)) = higher::for_loop(expr) {
552             // we don't want to check expanded macros
553             // this check is not at the top of the function
554             // since higher::for_loop expressions are marked as expansions
555             if body.span.from_expansion() {
556                 return;
557             }
558             check_for_loop(cx, pat, arg, body, expr, span);
559         }
560
561         // we don't want to check expanded macros
562         if expr.span.from_expansion() {
563             return;
564         }
565
566         // check for never_loop
567         if let ExprKind::Loop(ref block, _, _, _) = expr.kind {
568             match never_loop_block(block, expr.hir_id) {
569                 NeverLoopResult::AlwaysBreak => span_lint(cx, NEVER_LOOP, expr.span, "this loop never actually loops"),
570                 NeverLoopResult::MayContinueMainLoop | NeverLoopResult::Otherwise => (),
571             }
572         }
573
574         // check for `loop { if let {} else break }` that could be `while let`
575         // (also matches an explicit "match" instead of "if let")
576         // (even if the "match" or "if let" is used for declaration)
577         if let ExprKind::Loop(ref block, _, LoopSource::Loop, _) = expr.kind {
578             // also check for empty `loop {}` statements, skipping those in #[panic_handler]
579             if block.stmts.is_empty() && block.expr.is_none() && !is_in_panic_handler(cx, expr) {
580                 let msg = "empty `loop {}` wastes CPU cycles";
581                 let help = if is_no_std_crate(cx) {
582                     "you should either use `panic!()` or add a call pausing or sleeping the thread to the loop body"
583                 } else {
584                     "you should either use `panic!()` or add `std::thread::sleep(..);` to the loop body"
585                 };
586                 span_lint_and_help(cx, EMPTY_LOOP, expr.span, msg, None, help);
587             }
588
589             // extract the expression from the first statement (if any) in a block
590             let inner_stmt_expr = extract_expr_from_first_stmt(block);
591             // or extract the first expression (if any) from the block
592             if let Some(inner) = inner_stmt_expr.or_else(|| extract_first_expr(block)) {
593                 if let ExprKind::Match(ref matchexpr, ref arms, ref source) = inner.kind {
594                     // ensure "if let" compatible match structure
595                     match *source {
596                         MatchSource::Normal | MatchSource::IfLetDesugar { .. } => {
597                             if arms.len() == 2
598                                 && arms[0].guard.is_none()
599                                 && arms[1].guard.is_none()
600                                 && is_simple_break_expr(&arms[1].body)
601                             {
602                                 if in_external_macro(cx.sess(), expr.span) {
603                                     return;
604                                 }
605
606                                 // NOTE: we used to build a body here instead of using
607                                 // ellipsis, this was removed because:
608                                 // 1) it was ugly with big bodies;
609                                 // 2) it was not indented properly;
610                                 // 3) it wasn’t very smart (see #675).
611                                 let mut applicability = Applicability::HasPlaceholders;
612                                 span_lint_and_sugg(
613                                     cx,
614                                     WHILE_LET_LOOP,
615                                     expr.span,
616                                     "this loop could be written as a `while let` loop",
617                                     "try",
618                                     format!(
619                                         "while let {} = {} {{ .. }}",
620                                         snippet_with_applicability(cx, arms[0].pat.span, "..", &mut applicability),
621                                         snippet_with_applicability(cx, matchexpr.span, "..", &mut applicability),
622                                     ),
623                                     applicability,
624                                 );
625                             }
626                         },
627                         _ => (),
628                     }
629                 }
630             }
631         }
632         if let ExprKind::Match(ref match_expr, ref arms, MatchSource::WhileLetDesugar) = expr.kind {
633             let pat = &arms[0].pat.kind;
634             if let (
635                 &PatKind::TupleStruct(ref qpath, ref pat_args, _),
636                 &ExprKind::MethodCall(ref method_path, _, ref method_args, _),
637             ) = (pat, &match_expr.kind)
638             {
639                 let iter_expr = &method_args[0];
640
641                 // Don't lint when the iterator is recreated on every iteration
642                 if_chain! {
643                     if let ExprKind::MethodCall(..) | ExprKind::Call(..) = iter_expr.kind;
644                     if let Some(iter_def_id) = get_trait_def_id(cx, &paths::ITERATOR);
645                     if implements_trait(cx, cx.typeck_results().expr_ty(iter_expr), iter_def_id, &[]);
646                     then {
647                         return;
648                     }
649                 }
650
651                 let lhs_constructor = last_path_segment(qpath);
652                 if method_path.ident.name == sym::next
653                     && match_trait_method(cx, match_expr, &paths::ITERATOR)
654                     && lhs_constructor.ident.name == sym::Some
655                     && (pat_args.is_empty()
656                         || !is_refutable(cx, &pat_args[0])
657                             && !is_used_inside(cx, iter_expr, &arms[0].body)
658                             && !is_iterator_used_after_while_let(cx, iter_expr)
659                             && !is_nested(cx, expr, &method_args[0]))
660                 {
661                     let mut applicability = Applicability::MachineApplicable;
662                     let iterator = snippet_with_applicability(cx, method_args[0].span, "_", &mut applicability);
663                     let loop_var = if pat_args.is_empty() {
664                         "_".to_string()
665                     } else {
666                         snippet_with_applicability(cx, pat_args[0].span, "_", &mut applicability).into_owned()
667                     };
668                     span_lint_and_sugg(
669                         cx,
670                         WHILE_LET_ON_ITERATOR,
671                         expr.span.with_hi(match_expr.span.hi()),
672                         "this loop could be written as a `for` loop",
673                         "try",
674                         format!("for {} in {}", loop_var, iterator),
675                         applicability,
676                     );
677                 }
678             }
679         }
680
681         if let Some((cond, body)) = higher::while_loop(&expr) {
682             check_infinite_loop(cx, cond, body);
683         }
684
685         check_needless_collect(expr, cx);
686     }
687 }
688
689 enum NeverLoopResult {
690     // A break/return always get triggered but not necessarily for the main loop.
691     AlwaysBreak,
692     // A continue may occur for the main loop.
693     MayContinueMainLoop,
694     Otherwise,
695 }
696
697 #[must_use]
698 fn absorb_break(arg: &NeverLoopResult) -> NeverLoopResult {
699     match *arg {
700         NeverLoopResult::AlwaysBreak | NeverLoopResult::Otherwise => NeverLoopResult::Otherwise,
701         NeverLoopResult::MayContinueMainLoop => NeverLoopResult::MayContinueMainLoop,
702     }
703 }
704
705 // Combine two results for parts that are called in order.
706 #[must_use]
707 fn combine_seq(first: NeverLoopResult, second: NeverLoopResult) -> NeverLoopResult {
708     match first {
709         NeverLoopResult::AlwaysBreak | NeverLoopResult::MayContinueMainLoop => first,
710         NeverLoopResult::Otherwise => second,
711     }
712 }
713
714 // Combine two results where both parts are called but not necessarily in order.
715 #[must_use]
716 fn combine_both(left: NeverLoopResult, right: NeverLoopResult) -> NeverLoopResult {
717     match (left, right) {
718         (NeverLoopResult::MayContinueMainLoop, _) | (_, NeverLoopResult::MayContinueMainLoop) => {
719             NeverLoopResult::MayContinueMainLoop
720         },
721         (NeverLoopResult::AlwaysBreak, _) | (_, NeverLoopResult::AlwaysBreak) => NeverLoopResult::AlwaysBreak,
722         (NeverLoopResult::Otherwise, NeverLoopResult::Otherwise) => NeverLoopResult::Otherwise,
723     }
724 }
725
726 // Combine two results where only one of the part may have been executed.
727 #[must_use]
728 fn combine_branches(b1: NeverLoopResult, b2: NeverLoopResult) -> NeverLoopResult {
729     match (b1, b2) {
730         (NeverLoopResult::AlwaysBreak, NeverLoopResult::AlwaysBreak) => NeverLoopResult::AlwaysBreak,
731         (NeverLoopResult::MayContinueMainLoop, _) | (_, NeverLoopResult::MayContinueMainLoop) => {
732             NeverLoopResult::MayContinueMainLoop
733         },
734         (NeverLoopResult::Otherwise, _) | (_, NeverLoopResult::Otherwise) => NeverLoopResult::Otherwise,
735     }
736 }
737
738 fn never_loop_block(block: &Block<'_>, main_loop_id: HirId) -> NeverLoopResult {
739     let stmts = block.stmts.iter().map(stmt_to_expr);
740     let expr = once(block.expr.as_deref());
741     let mut iter = stmts.chain(expr).flatten();
742     never_loop_expr_seq(&mut iter, main_loop_id)
743 }
744
745 fn stmt_to_expr<'tcx>(stmt: &Stmt<'tcx>) -> Option<&'tcx Expr<'tcx>> {
746     match stmt.kind {
747         StmtKind::Semi(ref e, ..) | StmtKind::Expr(ref e, ..) => Some(e),
748         StmtKind::Local(ref local) => local.init.as_deref(),
749         _ => None,
750     }
751 }
752
753 fn never_loop_expr(expr: &Expr<'_>, main_loop_id: HirId) -> NeverLoopResult {
754     match expr.kind {
755         ExprKind::Box(ref e)
756         | ExprKind::Unary(_, ref e)
757         | ExprKind::Cast(ref e, _)
758         | ExprKind::Type(ref e, _)
759         | ExprKind::Field(ref e, _)
760         | ExprKind::AddrOf(_, _, ref e)
761         | ExprKind::Struct(_, _, Some(ref e))
762         | ExprKind::Repeat(ref e, _)
763         | ExprKind::DropTemps(ref e) => never_loop_expr(e, main_loop_id),
764         ExprKind::Array(ref es) | ExprKind::MethodCall(_, _, ref es, _) | ExprKind::Tup(ref es) => {
765             never_loop_expr_all(&mut es.iter(), main_loop_id)
766         },
767         ExprKind::Call(ref e, ref es) => never_loop_expr_all(&mut once(&**e).chain(es.iter()), main_loop_id),
768         ExprKind::Binary(_, ref e1, ref e2)
769         | ExprKind::Assign(ref e1, ref e2, _)
770         | ExprKind::AssignOp(_, ref e1, ref e2)
771         | ExprKind::Index(ref e1, ref e2) => never_loop_expr_all(&mut [&**e1, &**e2].iter().cloned(), main_loop_id),
772         ExprKind::Loop(ref b, _, _, _) => {
773             // Break can come from the inner loop so remove them.
774             absorb_break(&never_loop_block(b, main_loop_id))
775         },
776         ExprKind::If(ref e, ref e2, ref e3) => {
777             let e1 = never_loop_expr(e, main_loop_id);
778             let e2 = never_loop_expr(e2, main_loop_id);
779             let e3 = e3
780                 .as_ref()
781                 .map_or(NeverLoopResult::Otherwise, |e| never_loop_expr(e, main_loop_id));
782             combine_seq(e1, combine_branches(e2, e3))
783         },
784         ExprKind::Match(ref e, ref arms, _) => {
785             let e = never_loop_expr(e, main_loop_id);
786             if arms.is_empty() {
787                 e
788             } else {
789                 let arms = never_loop_expr_branch(&mut arms.iter().map(|a| &*a.body), main_loop_id);
790                 combine_seq(e, arms)
791             }
792         },
793         ExprKind::Block(ref b, _) => never_loop_block(b, main_loop_id),
794         ExprKind::Continue(d) => {
795             let id = d
796                 .target_id
797                 .expect("target ID can only be missing in the presence of compilation errors");
798             if id == main_loop_id {
799                 NeverLoopResult::MayContinueMainLoop
800             } else {
801                 NeverLoopResult::AlwaysBreak
802             }
803         },
804         ExprKind::Break(_, ref e) | ExprKind::Ret(ref e) => e.as_ref().map_or(NeverLoopResult::AlwaysBreak, |e| {
805             combine_seq(never_loop_expr(e, main_loop_id), NeverLoopResult::AlwaysBreak)
806         }),
807         ExprKind::InlineAsm(ref asm) => asm
808             .operands
809             .iter()
810             .map(|(o, _)| match o {
811                 InlineAsmOperand::In { expr, .. }
812                 | InlineAsmOperand::InOut { expr, .. }
813                 | InlineAsmOperand::Const { expr }
814                 | InlineAsmOperand::Sym { expr } => never_loop_expr(expr, main_loop_id),
815                 InlineAsmOperand::Out { expr, .. } => never_loop_expr_all(&mut expr.iter(), main_loop_id),
816                 InlineAsmOperand::SplitInOut { in_expr, out_expr, .. } => {
817                     never_loop_expr_all(&mut once(in_expr).chain(out_expr.iter()), main_loop_id)
818                 },
819             })
820             .fold(NeverLoopResult::Otherwise, combine_both),
821         ExprKind::Struct(_, _, None)
822         | ExprKind::Yield(_, _)
823         | ExprKind::Closure(_, _, _, _, _)
824         | ExprKind::LlvmInlineAsm(_)
825         | ExprKind::Path(_)
826         | ExprKind::ConstBlock(_)
827         | ExprKind::Lit(_)
828         | ExprKind::Err => NeverLoopResult::Otherwise,
829     }
830 }
831
832 fn never_loop_expr_seq<'a, T: Iterator<Item = &'a Expr<'a>>>(es: &mut T, main_loop_id: HirId) -> NeverLoopResult {
833     es.map(|e| never_loop_expr(e, main_loop_id))
834         .fold(NeverLoopResult::Otherwise, combine_seq)
835 }
836
837 fn never_loop_expr_all<'a, T: Iterator<Item = &'a Expr<'a>>>(es: &mut T, main_loop_id: HirId) -> NeverLoopResult {
838     es.map(|e| never_loop_expr(e, main_loop_id))
839         .fold(NeverLoopResult::Otherwise, combine_both)
840 }
841
842 fn never_loop_expr_branch<'a, T: Iterator<Item = &'a Expr<'a>>>(e: &mut T, main_loop_id: HirId) -> NeverLoopResult {
843     e.map(|e| never_loop_expr(e, main_loop_id))
844         .fold(NeverLoopResult::AlwaysBreak, combine_branches)
845 }
846
847 fn check_for_loop<'tcx>(
848     cx: &LateContext<'tcx>,
849     pat: &'tcx Pat<'_>,
850     arg: &'tcx Expr<'_>,
851     body: &'tcx Expr<'_>,
852     expr: &'tcx Expr<'_>,
853     span: Span,
854 ) {
855     let is_manual_memcpy_triggered = detect_manual_memcpy(cx, pat, arg, body, expr);
856     if !is_manual_memcpy_triggered {
857         check_for_loop_range(cx, pat, arg, body, expr);
858         check_for_loop_explicit_counter(cx, pat, arg, body, expr);
859     }
860     check_for_loop_arg(cx, pat, arg, expr);
861     check_for_loop_over_map_kv(cx, pat, arg, body, expr);
862     check_for_mut_range_bound(cx, arg, body);
863     check_for_single_element_loop(cx, pat, arg, body, expr);
864     detect_same_item_push(cx, pat, arg, body, expr);
865     check_manual_flatten(cx, pat, arg, body, span);
866 }
867
868 // this function assumes the given expression is a `for` loop.
869 fn get_span_of_entire_for_loop(expr: &Expr<'_>) -> Span {
870     // for some reason this is the only way to get the `Span`
871     // of the entire `for` loop
872     if let ExprKind::Match(_, arms, _) = &expr.kind {
873         arms[0].body.span
874     } else {
875         unreachable!()
876     }
877 }
878
879 /// a wrapper of `Sugg`. Besides what `Sugg` do, this removes unnecessary `0`;
880 /// and also, it avoids subtracting a variable from the same one by replacing it with `0`.
881 /// it exists for the convenience of the overloaded operators while normal functions can do the
882 /// same.
883 #[derive(Clone)]
884 struct MinifyingSugg<'a>(Sugg<'a>);
885
886 impl<'a> MinifyingSugg<'a> {
887     fn as_str(&self) -> &str {
888         let s = match &self.0 {
889             Sugg::NonParen(s) | Sugg::MaybeParen(s) | Sugg::BinOp(_, s) => s,
890         };
891         s.as_ref()
892     }
893
894     fn into_sugg(self) -> Sugg<'a> {
895         self.0
896     }
897 }
898
899 impl<'a> From<Sugg<'a>> for MinifyingSugg<'a> {
900     fn from(sugg: Sugg<'a>) -> Self {
901         Self(sugg)
902     }
903 }
904
905 impl std::ops::Add for &MinifyingSugg<'static> {
906     type Output = MinifyingSugg<'static>;
907     fn add(self, rhs: &MinifyingSugg<'static>) -> MinifyingSugg<'static> {
908         match (self.as_str(), rhs.as_str()) {
909             ("0", _) => rhs.clone(),
910             (_, "0") => self.clone(),
911             (_, _) => (&self.0 + &rhs.0).into(),
912         }
913     }
914 }
915
916 impl std::ops::Sub for &MinifyingSugg<'static> {
917     type Output = MinifyingSugg<'static>;
918     fn sub(self, rhs: &MinifyingSugg<'static>) -> MinifyingSugg<'static> {
919         match (self.as_str(), rhs.as_str()) {
920             (_, "0") => self.clone(),
921             ("0", _) => (-rhs.0.clone()).into(),
922             (x, y) if x == y => sugg::ZERO.into(),
923             (_, _) => (&self.0 - &rhs.0).into(),
924         }
925     }
926 }
927
928 impl std::ops::Add<&MinifyingSugg<'static>> for MinifyingSugg<'static> {
929     type Output = MinifyingSugg<'static>;
930     fn add(self, rhs: &MinifyingSugg<'static>) -> MinifyingSugg<'static> {
931         match (self.as_str(), rhs.as_str()) {
932             ("0", _) => rhs.clone(),
933             (_, "0") => self,
934             (_, _) => (self.0 + &rhs.0).into(),
935         }
936     }
937 }
938
939 impl std::ops::Sub<&MinifyingSugg<'static>> for MinifyingSugg<'static> {
940     type Output = MinifyingSugg<'static>;
941     fn sub(self, rhs: &MinifyingSugg<'static>) -> MinifyingSugg<'static> {
942         match (self.as_str(), rhs.as_str()) {
943             (_, "0") => self,
944             ("0", _) => (-rhs.0.clone()).into(),
945             (x, y) if x == y => sugg::ZERO.into(),
946             (_, _) => (self.0 - &rhs.0).into(),
947         }
948     }
949 }
950
951 /// a wrapper around `MinifyingSugg`, which carries a operator like currying
952 /// so that the suggested code become more efficient (e.g. `foo + -bar` `foo - bar`).
953 struct Offset {
954     value: MinifyingSugg<'static>,
955     sign: OffsetSign,
956 }
957
958 #[derive(Clone, Copy)]
959 enum OffsetSign {
960     Positive,
961     Negative,
962 }
963
964 impl Offset {
965     fn negative(value: Sugg<'static>) -> Self {
966         Self {
967             value: value.into(),
968             sign: OffsetSign::Negative,
969         }
970     }
971
972     fn positive(value: Sugg<'static>) -> Self {
973         Self {
974             value: value.into(),
975             sign: OffsetSign::Positive,
976         }
977     }
978
979     fn empty() -> Self {
980         Self::positive(sugg::ZERO)
981     }
982 }
983
984 fn apply_offset(lhs: &MinifyingSugg<'static>, rhs: &Offset) -> MinifyingSugg<'static> {
985     match rhs.sign {
986         OffsetSign::Positive => lhs + &rhs.value,
987         OffsetSign::Negative => lhs - &rhs.value,
988     }
989 }
990
991 #[derive(Debug, Clone, Copy)]
992 enum StartKind<'hir> {
993     Range,
994     Counter { initializer: &'hir Expr<'hir> },
995 }
996
997 struct IndexExpr<'hir> {
998     base: &'hir Expr<'hir>,
999     idx: StartKind<'hir>,
1000     idx_offset: Offset,
1001 }
1002
1003 struct Start<'hir> {
1004     id: HirId,
1005     kind: StartKind<'hir>,
1006 }
1007
1008 fn is_slice_like<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'_>) -> bool {
1009     let is_slice = match ty.kind() {
1010         ty::Ref(_, subty, _) => is_slice_like(cx, subty),
1011         ty::Slice(..) | ty::Array(..) => true,
1012         _ => false,
1013     };
1014
1015     is_slice || is_type_diagnostic_item(cx, ty, sym::vec_type) || is_type_diagnostic_item(cx, ty, sym::vecdeque_type)
1016 }
1017
1018 fn fetch_cloned_expr<'tcx>(expr: &'tcx Expr<'tcx>) -> &'tcx Expr<'tcx> {
1019     if_chain! {
1020         if let ExprKind::MethodCall(method, _, args, _) = expr.kind;
1021         if method.ident.name == sym::clone;
1022         if args.len() == 1;
1023         if let Some(arg) = args.get(0);
1024         then { arg } else { expr }
1025     }
1026 }
1027
1028 fn get_details_from_idx<'tcx>(
1029     cx: &LateContext<'tcx>,
1030     idx: &Expr<'_>,
1031     starts: &[Start<'tcx>],
1032 ) -> Option<(StartKind<'tcx>, Offset)> {
1033     fn get_start<'tcx>(e: &Expr<'_>, starts: &[Start<'tcx>]) -> Option<StartKind<'tcx>> {
1034         let id = path_to_local(e)?;
1035         starts.iter().find(|start| start.id == id).map(|start| start.kind)
1036     }
1037
1038     fn get_offset<'tcx>(cx: &LateContext<'tcx>, e: &Expr<'_>, starts: &[Start<'tcx>]) -> Option<Sugg<'static>> {
1039         match &e.kind {
1040             ExprKind::Lit(l) => match l.node {
1041                 ast::LitKind::Int(x, _ty) => Some(Sugg::NonParen(x.to_string().into())),
1042                 _ => None,
1043             },
1044             ExprKind::Path(..) if get_start(e, starts).is_none() => Some(Sugg::hir(cx, e, "???")),
1045             _ => None,
1046         }
1047     }
1048
1049     match idx.kind {
1050         ExprKind::Binary(op, lhs, rhs) => match op.node {
1051             BinOpKind::Add => {
1052                 let offset_opt = get_start(lhs, starts)
1053                     .and_then(|s| get_offset(cx, rhs, starts).map(|o| (s, o)))
1054                     .or_else(|| get_start(rhs, starts).and_then(|s| get_offset(cx, lhs, starts).map(|o| (s, o))));
1055
1056                 offset_opt.map(|(s, o)| (s, Offset::positive(o)))
1057             },
1058             BinOpKind::Sub => {
1059                 get_start(lhs, starts).and_then(|s| get_offset(cx, rhs, starts).map(|o| (s, Offset::negative(o))))
1060             },
1061             _ => None,
1062         },
1063         ExprKind::Path(..) => get_start(idx, starts).map(|s| (s, Offset::empty())),
1064         _ => None,
1065     }
1066 }
1067
1068 fn get_assignment<'tcx>(e: &'tcx Expr<'tcx>) -> Option<(&'tcx Expr<'tcx>, &'tcx Expr<'tcx>)> {
1069     if let ExprKind::Assign(lhs, rhs, _) = e.kind {
1070         Some((lhs, rhs))
1071     } else {
1072         None
1073     }
1074 }
1075
1076 /// Get assignments from the given block.
1077 /// The returned iterator yields `None` if no assignment expressions are there,
1078 /// filtering out the increments of the given whitelisted loop counters;
1079 /// because its job is to make sure there's nothing other than assignments and the increments.
1080 fn get_assignments<'a, 'tcx>(
1081     Block { stmts, expr, .. }: &'tcx Block<'tcx>,
1082     loop_counters: &'a [Start<'tcx>],
1083 ) -> impl Iterator<Item = Option<(&'tcx Expr<'tcx>, &'tcx Expr<'tcx>)>> + 'a {
1084     // As the `filter` and `map` below do different things, I think putting together
1085     // just increases complexity. (cc #3188 and #4193)
1086     stmts
1087         .iter()
1088         .filter_map(move |stmt| match stmt.kind {
1089             StmtKind::Local(..) | StmtKind::Item(..) => None,
1090             StmtKind::Expr(e) | StmtKind::Semi(e) => Some(e),
1091         })
1092         .chain((*expr).into_iter())
1093         .filter(move |e| {
1094             if let ExprKind::AssignOp(_, place, _) = e.kind {
1095                 path_to_local(place).map_or(false, |id| {
1096                     !loop_counters
1097                         .iter()
1098                         // skip the first item which should be `StartKind::Range`
1099                         // this makes it possible to use the slice with `StartKind::Range` in the same iterator loop.
1100                         .skip(1)
1101                         .any(|counter| counter.id == id)
1102                 })
1103             } else {
1104                 true
1105             }
1106         })
1107         .map(get_assignment)
1108 }
1109
1110 fn get_loop_counters<'a, 'tcx>(
1111     cx: &'a LateContext<'tcx>,
1112     body: &'tcx Block<'tcx>,
1113     expr: &'tcx Expr<'_>,
1114 ) -> Option<impl Iterator<Item = Start<'tcx>> + 'a> {
1115     // Look for variables that are incremented once per loop iteration.
1116     let mut increment_visitor = IncrementVisitor::new(cx);
1117     walk_block(&mut increment_visitor, body);
1118
1119     // For each candidate, check the parent block to see if
1120     // it's initialized to zero at the start of the loop.
1121     get_enclosing_block(&cx, expr.hir_id).and_then(|block| {
1122         increment_visitor
1123             .into_results()
1124             .filter_map(move |var_id| {
1125                 let mut initialize_visitor = InitializeVisitor::new(cx, expr, var_id);
1126                 walk_block(&mut initialize_visitor, block);
1127
1128                 initialize_visitor.get_result().map(|(_, initializer)| Start {
1129                     id: var_id,
1130                     kind: StartKind::Counter { initializer },
1131                 })
1132             })
1133             .into()
1134     })
1135 }
1136
1137 fn build_manual_memcpy_suggestion<'tcx>(
1138     cx: &LateContext<'tcx>,
1139     start: &Expr<'_>,
1140     end: &Expr<'_>,
1141     limits: ast::RangeLimits,
1142     dst: &IndexExpr<'_>,
1143     src: &IndexExpr<'_>,
1144 ) -> String {
1145     fn print_offset(offset: MinifyingSugg<'static>) -> MinifyingSugg<'static> {
1146         if offset.as_str() == "0" {
1147             sugg::EMPTY.into()
1148         } else {
1149             offset
1150         }
1151     }
1152
1153     let print_limit = |end: &Expr<'_>, end_str: &str, base: &Expr<'_>, sugg: MinifyingSugg<'static>| {
1154         if_chain! {
1155             if let ExprKind::MethodCall(method, _, len_args, _) = end.kind;
1156             if method.ident.name == sym!(len);
1157             if len_args.len() == 1;
1158             if let Some(arg) = len_args.get(0);
1159             if path_to_local(arg) == path_to_local(base);
1160             then {
1161                 if sugg.as_str() == end_str {
1162                     sugg::EMPTY.into()
1163                 } else {
1164                     sugg
1165                 }
1166             } else {
1167                 match limits {
1168                     ast::RangeLimits::Closed => {
1169                         sugg + &sugg::ONE.into()
1170                     },
1171                     ast::RangeLimits::HalfOpen => sugg,
1172                 }
1173             }
1174         }
1175     };
1176
1177     let start_str = Sugg::hir(cx, start, "").into();
1178     let end_str: MinifyingSugg<'_> = Sugg::hir(cx, end, "").into();
1179
1180     let print_offset_and_limit = |idx_expr: &IndexExpr<'_>| match idx_expr.idx {
1181         StartKind::Range => (
1182             print_offset(apply_offset(&start_str, &idx_expr.idx_offset)).into_sugg(),
1183             print_limit(
1184                 end,
1185                 end_str.as_str(),
1186                 idx_expr.base,
1187                 apply_offset(&end_str, &idx_expr.idx_offset),
1188             )
1189             .into_sugg(),
1190         ),
1191         StartKind::Counter { initializer } => {
1192             let counter_start = Sugg::hir(cx, initializer, "").into();
1193             (
1194                 print_offset(apply_offset(&counter_start, &idx_expr.idx_offset)).into_sugg(),
1195                 print_limit(
1196                     end,
1197                     end_str.as_str(),
1198                     idx_expr.base,
1199                     apply_offset(&end_str, &idx_expr.idx_offset) + &counter_start - &start_str,
1200                 )
1201                 .into_sugg(),
1202             )
1203         },
1204     };
1205
1206     let (dst_offset, dst_limit) = print_offset_and_limit(&dst);
1207     let (src_offset, src_limit) = print_offset_and_limit(&src);
1208
1209     let dst_base_str = snippet(cx, dst.base.span, "???");
1210     let src_base_str = snippet(cx, src.base.span, "???");
1211
1212     let dst = if dst_offset == sugg::EMPTY && dst_limit == sugg::EMPTY {
1213         dst_base_str
1214     } else {
1215         format!(
1216             "{}[{}..{}]",
1217             dst_base_str,
1218             dst_offset.maybe_par(),
1219             dst_limit.maybe_par()
1220         )
1221         .into()
1222     };
1223
1224     format!(
1225         "{}.clone_from_slice(&{}[{}..{}]);",
1226         dst,
1227         src_base_str,
1228         src_offset.maybe_par(),
1229         src_limit.maybe_par()
1230     )
1231 }
1232
1233 /// Checks for for loops that sequentially copy items from one slice-like
1234 /// object to another.
1235 fn detect_manual_memcpy<'tcx>(
1236     cx: &LateContext<'tcx>,
1237     pat: &'tcx Pat<'_>,
1238     arg: &'tcx Expr<'_>,
1239     body: &'tcx Expr<'_>,
1240     expr: &'tcx Expr<'_>,
1241 ) -> bool {
1242     if let Some(higher::Range {
1243         start: Some(start),
1244         end: Some(end),
1245         limits,
1246     }) = higher::range(arg)
1247     {
1248         // the var must be a single name
1249         if let PatKind::Binding(_, canonical_id, _, _) = pat.kind {
1250             let mut starts = vec![Start {
1251                 id: canonical_id,
1252                 kind: StartKind::Range,
1253             }];
1254
1255             // This is one of few ways to return different iterators
1256             // derived from: https://stackoverflow.com/questions/29760668/conditionally-iterate-over-one-of-several-possible-iterators/52064434#52064434
1257             let mut iter_a = None;
1258             let mut iter_b = None;
1259
1260             if let ExprKind::Block(block, _) = body.kind {
1261                 if let Some(loop_counters) = get_loop_counters(cx, block, expr) {
1262                     starts.extend(loop_counters);
1263                 }
1264                 iter_a = Some(get_assignments(block, &starts));
1265             } else {
1266                 iter_b = Some(get_assignment(body));
1267             }
1268
1269             let assignments = iter_a.into_iter().flatten().chain(iter_b.into_iter());
1270
1271             let big_sugg = assignments
1272                 // The only statements in the for loops can be indexed assignments from
1273                 // indexed retrievals (except increments of loop counters).
1274                 .map(|o| {
1275                     o.and_then(|(lhs, rhs)| {
1276                         let rhs = fetch_cloned_expr(rhs);
1277                         if_chain! {
1278                             if let ExprKind::Index(base_left, idx_left) = lhs.kind;
1279                             if let ExprKind::Index(base_right, idx_right) = rhs.kind;
1280                             if is_slice_like(cx, cx.typeck_results().expr_ty(base_left))
1281                                 && is_slice_like(cx, cx.typeck_results().expr_ty(base_right));
1282                             if let Some((start_left, offset_left)) = get_details_from_idx(cx, &idx_left, &starts);
1283                             if let Some((start_right, offset_right)) = get_details_from_idx(cx, &idx_right, &starts);
1284
1285                             // Source and destination must be different
1286                             if path_to_local(base_left) != path_to_local(base_right);
1287                             then {
1288                                 Some((IndexExpr { base: base_left, idx: start_left, idx_offset: offset_left },
1289                                     IndexExpr { base: base_right, idx: start_right, idx_offset: offset_right }))
1290                             } else {
1291                                 None
1292                             }
1293                         }
1294                     })
1295                 })
1296                 .map(|o| o.map(|(dst, src)| build_manual_memcpy_suggestion(cx, start, end, limits, &dst, &src)))
1297                 .collect::<Option<Vec<_>>>()
1298                 .filter(|v| !v.is_empty())
1299                 .map(|v| v.join("\n    "));
1300
1301             if let Some(big_sugg) = big_sugg {
1302                 span_lint_and_sugg(
1303                     cx,
1304                     MANUAL_MEMCPY,
1305                     get_span_of_entire_for_loop(expr),
1306                     "it looks like you're manually copying between slices",
1307                     "try replacing the loop by",
1308                     big_sugg,
1309                     Applicability::Unspecified,
1310                 );
1311                 return true;
1312             }
1313         }
1314     }
1315     false
1316 }
1317
1318 // Scans the body of the for loop and determines whether lint should be given
1319 struct SameItemPushVisitor<'a, 'tcx> {
1320     should_lint: bool,
1321     // this field holds the last vec push operation visited, which should be the only push seen
1322     vec_push: Option<(&'tcx Expr<'tcx>, &'tcx Expr<'tcx>)>,
1323     cx: &'a LateContext<'tcx>,
1324 }
1325
1326 impl<'a, 'tcx> Visitor<'tcx> for SameItemPushVisitor<'a, 'tcx> {
1327     type Map = Map<'tcx>;
1328
1329     fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
1330         match &expr.kind {
1331             // Non-determinism may occur ... don't give a lint
1332             ExprKind::Loop(..) | ExprKind::Match(..) => self.should_lint = false,
1333             ExprKind::Block(block, _) => self.visit_block(block),
1334             _ => {},
1335         }
1336     }
1337
1338     fn visit_block(&mut self, b: &'tcx Block<'_>) {
1339         for stmt in b.stmts.iter() {
1340             self.visit_stmt(stmt);
1341         }
1342     }
1343
1344     fn visit_stmt(&mut self, s: &'tcx Stmt<'_>) {
1345         let vec_push_option = get_vec_push(self.cx, s);
1346         if vec_push_option.is_none() {
1347             // Current statement is not a push so visit inside
1348             match &s.kind {
1349                 StmtKind::Expr(expr) | StmtKind::Semi(expr) => self.visit_expr(&expr),
1350                 _ => {},
1351             }
1352         } else {
1353             // Current statement is a push ...check whether another
1354             // push had been previously done
1355             if self.vec_push.is_none() {
1356                 self.vec_push = vec_push_option;
1357             } else {
1358                 // There are multiple pushes ... don't lint
1359                 self.should_lint = false;
1360             }
1361         }
1362     }
1363
1364     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
1365         NestedVisitorMap::None
1366     }
1367 }
1368
1369 // Given some statement, determine if that statement is a push on a Vec. If it is, return
1370 // the Vec being pushed into and the item being pushed
1371 fn get_vec_push<'tcx>(cx: &LateContext<'tcx>, stmt: &'tcx Stmt<'_>) -> Option<(&'tcx Expr<'tcx>, &'tcx Expr<'tcx>)> {
1372     if_chain! {
1373             // Extract method being called
1374             if let StmtKind::Semi(semi_stmt) = &stmt.kind;
1375             if let ExprKind::MethodCall(path, _, args, _) = &semi_stmt.kind;
1376             // Figure out the parameters for the method call
1377             if let Some(self_expr) = args.get(0);
1378             if let Some(pushed_item) = args.get(1);
1379             // Check that the method being called is push() on a Vec
1380             if is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(self_expr), sym::vec_type);
1381             if path.ident.name.as_str() == "push";
1382             then {
1383                 return Some((self_expr, pushed_item))
1384             }
1385     }
1386     None
1387 }
1388
1389 /// Detects for loop pushing the same item into a Vec
1390 fn detect_same_item_push<'tcx>(
1391     cx: &LateContext<'tcx>,
1392     pat: &'tcx Pat<'_>,
1393     _: &'tcx Expr<'_>,
1394     body: &'tcx Expr<'_>,
1395     _: &'tcx Expr<'_>,
1396 ) {
1397     fn emit_lint(cx: &LateContext<'_>, vec: &Expr<'_>, pushed_item: &Expr<'_>) {
1398         let vec_str = snippet_with_macro_callsite(cx, vec.span, "");
1399         let item_str = snippet_with_macro_callsite(cx, pushed_item.span, "");
1400
1401         span_lint_and_help(
1402             cx,
1403             SAME_ITEM_PUSH,
1404             vec.span,
1405             "it looks like the same item is being pushed into this Vec",
1406             None,
1407             &format!(
1408                 "try using vec![{};SIZE] or {}.resize(NEW_SIZE, {})",
1409                 item_str, vec_str, item_str
1410             ),
1411         )
1412     }
1413
1414     if !matches!(pat.kind, PatKind::Wild) {
1415         return;
1416     }
1417
1418     // Determine whether it is safe to lint the body
1419     let mut same_item_push_visitor = SameItemPushVisitor {
1420         should_lint: true,
1421         vec_push: None,
1422         cx,
1423     };
1424     walk_expr(&mut same_item_push_visitor, body);
1425     if same_item_push_visitor.should_lint {
1426         if let Some((vec, pushed_item)) = same_item_push_visitor.vec_push {
1427             let vec_ty = cx.typeck_results().expr_ty(vec);
1428             let ty = vec_ty.walk().nth(1).unwrap().expect_ty();
1429             if cx
1430                 .tcx
1431                 .lang_items()
1432                 .clone_trait()
1433                 .map_or(false, |id| implements_trait(cx, ty, id, &[]))
1434             {
1435                 // Make sure that the push does not involve possibly mutating values
1436                 match pushed_item.kind {
1437                     ExprKind::Path(ref qpath) => {
1438                         match cx.qpath_res(qpath, pushed_item.hir_id) {
1439                             // immutable bindings that are initialized with literal or constant
1440                             Res::Local(hir_id) => {
1441                                 if_chain! {
1442                                     let node = cx.tcx.hir().get(hir_id);
1443                                     if let Node::Binding(pat) = node;
1444                                     if let PatKind::Binding(bind_ann, ..) = pat.kind;
1445                                     if !matches!(bind_ann, BindingAnnotation::RefMut | BindingAnnotation::Mutable);
1446                                     let parent_node = cx.tcx.hir().get_parent_node(hir_id);
1447                                     if let Some(Node::Local(parent_let_expr)) = cx.tcx.hir().find(parent_node);
1448                                     if let Some(init) = parent_let_expr.init;
1449                                     then {
1450                                         match init.kind {
1451                                             // immutable bindings that are initialized with literal
1452                                             ExprKind::Lit(..) => emit_lint(cx, vec, pushed_item),
1453                                             // immutable bindings that are initialized with constant
1454                                             ExprKind::Path(ref path) => {
1455                                                 if let Res::Def(DefKind::Const, ..) = cx.qpath_res(path, init.hir_id) {
1456                                                     emit_lint(cx, vec, pushed_item);
1457                                                 }
1458                                             }
1459                                             _ => {},
1460                                         }
1461                                     }
1462                                 }
1463                             },
1464                             // constant
1465                             Res::Def(DefKind::Const, ..) => emit_lint(cx, vec, pushed_item),
1466                             _ => {},
1467                         }
1468                     },
1469                     ExprKind::Lit(..) => emit_lint(cx, vec, pushed_item),
1470                     _ => {},
1471                 }
1472             }
1473         }
1474     }
1475 }
1476
1477 /// Checks for looping over a range and then indexing a sequence with it.
1478 /// The iteratee must be a range literal.
1479 #[allow(clippy::too_many_lines)]
1480 fn check_for_loop_range<'tcx>(
1481     cx: &LateContext<'tcx>,
1482     pat: &'tcx Pat<'_>,
1483     arg: &'tcx Expr<'_>,
1484     body: &'tcx Expr<'_>,
1485     expr: &'tcx Expr<'_>,
1486 ) {
1487     if let Some(higher::Range {
1488         start: Some(start),
1489         ref end,
1490         limits,
1491     }) = higher::range(arg)
1492     {
1493         // the var must be a single name
1494         if let PatKind::Binding(_, canonical_id, ident, _) = pat.kind {
1495             let mut visitor = VarVisitor {
1496                 cx,
1497                 var: canonical_id,
1498                 indexed_mut: FxHashSet::default(),
1499                 indexed_indirectly: FxHashMap::default(),
1500                 indexed_directly: FxHashMap::default(),
1501                 referenced: FxHashSet::default(),
1502                 nonindex: false,
1503                 prefer_mutable: false,
1504             };
1505             walk_expr(&mut visitor, body);
1506
1507             // linting condition: we only indexed one variable, and indexed it directly
1508             if visitor.indexed_indirectly.is_empty() && visitor.indexed_directly.len() == 1 {
1509                 let (indexed, (indexed_extent, indexed_ty)) = visitor
1510                     .indexed_directly
1511                     .into_iter()
1512                     .next()
1513                     .expect("already checked that we have exactly 1 element");
1514
1515                 // ensure that the indexed variable was declared before the loop, see #601
1516                 if let Some(indexed_extent) = indexed_extent {
1517                     let parent_id = cx.tcx.hir().get_parent_item(expr.hir_id);
1518                     let parent_def_id = cx.tcx.hir().local_def_id(parent_id);
1519                     let region_scope_tree = cx.tcx.region_scope_tree(parent_def_id);
1520                     let pat_extent = region_scope_tree.var_scope(pat.hir_id.local_id);
1521                     if region_scope_tree.is_subscope_of(indexed_extent, pat_extent) {
1522                         return;
1523                     }
1524                 }
1525
1526                 // don't lint if the container that is indexed does not have .iter() method
1527                 let has_iter = has_iter_method(cx, indexed_ty);
1528                 if has_iter.is_none() {
1529                     return;
1530                 }
1531
1532                 // don't lint if the container that is indexed into is also used without
1533                 // indexing
1534                 if visitor.referenced.contains(&indexed) {
1535                     return;
1536                 }
1537
1538                 let starts_at_zero = is_integer_const(cx, start, 0);
1539
1540                 let skip = if starts_at_zero {
1541                     String::new()
1542                 } else if visitor.indexed_mut.contains(&indexed) && contains_name(indexed, start) {
1543                     return;
1544                 } else {
1545                     format!(".skip({})", snippet(cx, start.span, ".."))
1546                 };
1547
1548                 let mut end_is_start_plus_val = false;
1549
1550                 let take = if let Some(end) = *end {
1551                     let mut take_expr = end;
1552
1553                     if let ExprKind::Binary(ref op, ref left, ref right) = end.kind {
1554                         if let BinOpKind::Add = op.node {
1555                             let start_equal_left = SpanlessEq::new(cx).eq_expr(start, left);
1556                             let start_equal_right = SpanlessEq::new(cx).eq_expr(start, right);
1557
1558                             if start_equal_left {
1559                                 take_expr = right;
1560                             } else if start_equal_right {
1561                                 take_expr = left;
1562                             }
1563
1564                             end_is_start_plus_val = start_equal_left | start_equal_right;
1565                         }
1566                     }
1567
1568                     if is_len_call(end, indexed) || is_end_eq_array_len(cx, end, limits, indexed_ty) {
1569                         String::new()
1570                     } else if visitor.indexed_mut.contains(&indexed) && contains_name(indexed, take_expr) {
1571                         return;
1572                     } else {
1573                         match limits {
1574                             ast::RangeLimits::Closed => {
1575                                 let take_expr = sugg::Sugg::hir(cx, take_expr, "<count>");
1576                                 format!(".take({})", take_expr + sugg::ONE)
1577                             },
1578                             ast::RangeLimits::HalfOpen => format!(".take({})", snippet(cx, take_expr.span, "..")),
1579                         }
1580                     }
1581                 } else {
1582                     String::new()
1583                 };
1584
1585                 let (ref_mut, method) = if visitor.indexed_mut.contains(&indexed) {
1586                     ("mut ", "iter_mut")
1587                 } else {
1588                     ("", "iter")
1589                 };
1590
1591                 let take_is_empty = take.is_empty();
1592                 let mut method_1 = take;
1593                 let mut method_2 = skip;
1594
1595                 if end_is_start_plus_val {
1596                     mem::swap(&mut method_1, &mut method_2);
1597                 }
1598
1599                 if visitor.nonindex {
1600                     span_lint_and_then(
1601                         cx,
1602                         NEEDLESS_RANGE_LOOP,
1603                         expr.span,
1604                         &format!("the loop variable `{}` is used to index `{}`", ident.name, indexed),
1605                         |diag| {
1606                             multispan_sugg(
1607                                 diag,
1608                                 "consider using an iterator",
1609                                 vec![
1610                                     (pat.span, format!("({}, <item>)", ident.name)),
1611                                     (
1612                                         arg.span,
1613                                         format!("{}.{}().enumerate(){}{}", indexed, method, method_1, method_2),
1614                                     ),
1615                                 ],
1616                             );
1617                         },
1618                     );
1619                 } else {
1620                     let repl = if starts_at_zero && take_is_empty {
1621                         format!("&{}{}", ref_mut, indexed)
1622                     } else {
1623                         format!("{}.{}(){}{}", indexed, method, method_1, method_2)
1624                     };
1625
1626                     span_lint_and_then(
1627                         cx,
1628                         NEEDLESS_RANGE_LOOP,
1629                         expr.span,
1630                         &format!(
1631                             "the loop variable `{}` is only used to index `{}`.",
1632                             ident.name, indexed
1633                         ),
1634                         |diag| {
1635                             multispan_sugg(
1636                                 diag,
1637                                 "consider using an iterator",
1638                                 vec![(pat.span, "<item>".to_string()), (arg.span, repl)],
1639                             );
1640                         },
1641                     );
1642                 }
1643             }
1644         }
1645     }
1646 }
1647
1648 fn is_len_call(expr: &Expr<'_>, var: Symbol) -> bool {
1649     if_chain! {
1650         if let ExprKind::MethodCall(ref method, _, ref len_args, _) = expr.kind;
1651         if len_args.len() == 1;
1652         if method.ident.name == sym!(len);
1653         if let ExprKind::Path(QPath::Resolved(_, ref path)) = len_args[0].kind;
1654         if path.segments.len() == 1;
1655         if path.segments[0].ident.name == var;
1656         then {
1657             return true;
1658         }
1659     }
1660
1661     false
1662 }
1663
1664 fn is_end_eq_array_len<'tcx>(
1665     cx: &LateContext<'tcx>,
1666     end: &Expr<'_>,
1667     limits: ast::RangeLimits,
1668     indexed_ty: Ty<'tcx>,
1669 ) -> bool {
1670     if_chain! {
1671         if let ExprKind::Lit(ref lit) = end.kind;
1672         if let ast::LitKind::Int(end_int, _) = lit.node;
1673         if let ty::Array(_, arr_len_const) = indexed_ty.kind();
1674         if let Some(arr_len) = arr_len_const.try_eval_usize(cx.tcx, cx.param_env);
1675         then {
1676             return match limits {
1677                 ast::RangeLimits::Closed => end_int + 1 >= arr_len.into(),
1678                 ast::RangeLimits::HalfOpen => end_int >= arr_len.into(),
1679             };
1680         }
1681     }
1682
1683     false
1684 }
1685
1686 fn lint_iter_method(cx: &LateContext<'_>, args: &[Expr<'_>], arg: &Expr<'_>, method_name: &str) {
1687     let mut applicability = Applicability::MachineApplicable;
1688     let object = snippet_with_applicability(cx, args[0].span, "_", &mut applicability);
1689     let muta = if method_name == "iter_mut" { "mut " } else { "" };
1690     span_lint_and_sugg(
1691         cx,
1692         EXPLICIT_ITER_LOOP,
1693         arg.span,
1694         "it is more concise to loop over references to containers instead of using explicit \
1695          iteration methods",
1696         "to write this more concisely, try",
1697         format!("&{}{}", muta, object),
1698         applicability,
1699     )
1700 }
1701
1702 fn check_for_loop_arg(cx: &LateContext<'_>, pat: &Pat<'_>, arg: &Expr<'_>, expr: &Expr<'_>) {
1703     let mut next_loop_linted = false; // whether or not ITER_NEXT_LOOP lint was used
1704     if let ExprKind::MethodCall(ref method, _, ref args, _) = arg.kind {
1705         // just the receiver, no arguments
1706         if args.len() == 1 {
1707             let method_name = &*method.ident.as_str();
1708             // check for looping over x.iter() or x.iter_mut(), could use &x or &mut x
1709             if method_name == "iter" || method_name == "iter_mut" {
1710                 if is_ref_iterable_type(cx, &args[0]) {
1711                     lint_iter_method(cx, args, arg, method_name);
1712                 }
1713             } else if method_name == "into_iter" && match_trait_method(cx, arg, &paths::INTO_ITERATOR) {
1714                 let receiver_ty = cx.typeck_results().expr_ty(&args[0]);
1715                 let receiver_ty_adjusted = cx.typeck_results().expr_ty_adjusted(&args[0]);
1716                 if TyS::same_type(receiver_ty, receiver_ty_adjusted) {
1717                     let mut applicability = Applicability::MachineApplicable;
1718                     let object = snippet_with_applicability(cx, args[0].span, "_", &mut applicability);
1719                     span_lint_and_sugg(
1720                         cx,
1721                         EXPLICIT_INTO_ITER_LOOP,
1722                         arg.span,
1723                         "it is more concise to loop over containers instead of using explicit \
1724                          iteration methods",
1725                         "to write this more concisely, try",
1726                         object.to_string(),
1727                         applicability,
1728                     );
1729                 } else {
1730                     let ref_receiver_ty = cx.tcx.mk_ref(
1731                         cx.tcx.lifetimes.re_erased,
1732                         ty::TypeAndMut {
1733                             ty: receiver_ty,
1734                             mutbl: Mutability::Not,
1735                         },
1736                     );
1737                     if TyS::same_type(receiver_ty_adjusted, ref_receiver_ty) {
1738                         lint_iter_method(cx, args, arg, method_name)
1739                     }
1740                 }
1741             } else if method_name == "next" && match_trait_method(cx, arg, &paths::ITERATOR) {
1742                 span_lint(
1743                     cx,
1744                     ITER_NEXT_LOOP,
1745                     expr.span,
1746                     "you are iterating over `Iterator::next()` which is an Option; this will compile but is \
1747                     probably not what you want",
1748                 );
1749                 next_loop_linted = true;
1750             }
1751         }
1752     }
1753     if !next_loop_linted {
1754         check_arg_type(cx, pat, arg);
1755     }
1756 }
1757
1758 /// Checks for `for` loops over `Option`s and `Result`s.
1759 fn check_arg_type(cx: &LateContext<'_>, pat: &Pat<'_>, arg: &Expr<'_>) {
1760     let ty = cx.typeck_results().expr_ty(arg);
1761     if is_type_diagnostic_item(cx, ty, sym::option_type) {
1762         span_lint_and_help(
1763             cx,
1764             FOR_LOOPS_OVER_FALLIBLES,
1765             arg.span,
1766             &format!(
1767                 "for loop over `{0}`, which is an `Option`. This is more readably written as an \
1768                 `if let` statement.",
1769                 snippet(cx, arg.span, "_")
1770             ),
1771             None,
1772             &format!(
1773                 "consider replacing `for {0} in {1}` with `if let Some({0}) = {1}`",
1774                 snippet(cx, pat.span, "_"),
1775                 snippet(cx, arg.span, "_")
1776             ),
1777         );
1778     } else if is_type_diagnostic_item(cx, ty, sym::result_type) {
1779         span_lint_and_help(
1780             cx,
1781             FOR_LOOPS_OVER_FALLIBLES,
1782             arg.span,
1783             &format!(
1784                 "for loop over `{0}`, which is a `Result`. This is more readably written as an \
1785                 `if let` statement.",
1786                 snippet(cx, arg.span, "_")
1787             ),
1788             None,
1789             &format!(
1790                 "consider replacing `for {0} in {1}` with `if let Ok({0}) = {1}`",
1791                 snippet(cx, pat.span, "_"),
1792                 snippet(cx, arg.span, "_")
1793             ),
1794         );
1795     }
1796 }
1797
1798 // To trigger the EXPLICIT_COUNTER_LOOP lint, a variable must be
1799 // incremented exactly once in the loop body, and initialized to zero
1800 // at the start of the loop.
1801 fn check_for_loop_explicit_counter<'tcx>(
1802     cx: &LateContext<'tcx>,
1803     pat: &'tcx Pat<'_>,
1804     arg: &'tcx Expr<'_>,
1805     body: &'tcx Expr<'_>,
1806     expr: &'tcx Expr<'_>,
1807 ) {
1808     // Look for variables that are incremented once per loop iteration.
1809     let mut increment_visitor = IncrementVisitor::new(cx);
1810     walk_expr(&mut increment_visitor, body);
1811
1812     // For each candidate, check the parent block to see if
1813     // it's initialized to zero at the start of the loop.
1814     if let Some(block) = get_enclosing_block(&cx, expr.hir_id) {
1815         for id in increment_visitor.into_results() {
1816             let mut initialize_visitor = InitializeVisitor::new(cx, expr, id);
1817             walk_block(&mut initialize_visitor, block);
1818
1819             if_chain! {
1820                 if let Some((name, initializer)) = initialize_visitor.get_result();
1821                 if is_integer_const(cx, initializer, 0);
1822                 then {
1823                     let mut applicability = Applicability::MachineApplicable;
1824
1825                     let for_span = get_span_of_entire_for_loop(expr);
1826
1827                     span_lint_and_sugg(
1828                         cx,
1829                         EXPLICIT_COUNTER_LOOP,
1830                         for_span.with_hi(arg.span.hi()),
1831                         &format!("the variable `{}` is used as a loop counter.", name),
1832                         "consider using",
1833                         format!(
1834                             "for ({}, {}) in {}.enumerate()",
1835                             name,
1836                             snippet_with_applicability(cx, pat.span, "item", &mut applicability),
1837                             make_iterator_snippet(cx, arg, &mut applicability),
1838                         ),
1839                         applicability,
1840                     );
1841                 }
1842             }
1843         }
1844     }
1845 }
1846
1847 /// If `arg` was the argument to a `for` loop, return the "cleanest" way of writing the
1848 /// actual `Iterator` that the loop uses.
1849 fn make_iterator_snippet(cx: &LateContext<'_>, arg: &Expr<'_>, applic_ref: &mut Applicability) -> String {
1850     let impls_iterator = get_trait_def_id(cx, &paths::ITERATOR).map_or(false, |id| {
1851         implements_trait(cx, cx.typeck_results().expr_ty(arg), id, &[])
1852     });
1853     if impls_iterator {
1854         format!(
1855             "{}",
1856             sugg::Sugg::hir_with_applicability(cx, arg, "_", applic_ref).maybe_par()
1857         )
1858     } else {
1859         // (&x).into_iter() ==> x.iter()
1860         // (&mut x).into_iter() ==> x.iter_mut()
1861         match &arg.kind {
1862             ExprKind::AddrOf(BorrowKind::Ref, mutability, arg_inner)
1863                 if has_iter_method(cx, cx.typeck_results().expr_ty(&arg_inner)).is_some() =>
1864             {
1865                 let meth_name = match mutability {
1866                     Mutability::Mut => "iter_mut",
1867                     Mutability::Not => "iter",
1868                 };
1869                 format!(
1870                     "{}.{}()",
1871                     sugg::Sugg::hir_with_applicability(cx, &arg_inner, "_", applic_ref).maybe_par(),
1872                     meth_name,
1873                 )
1874             }
1875             _ => format!(
1876                 "{}.into_iter()",
1877                 sugg::Sugg::hir_with_applicability(cx, arg, "_", applic_ref).maybe_par()
1878             ),
1879         }
1880     }
1881 }
1882
1883 /// Checks for the `FOR_KV_MAP` lint.
1884 fn check_for_loop_over_map_kv<'tcx>(
1885     cx: &LateContext<'tcx>,
1886     pat: &'tcx Pat<'_>,
1887     arg: &'tcx Expr<'_>,
1888     body: &'tcx Expr<'_>,
1889     expr: &'tcx Expr<'_>,
1890 ) {
1891     let pat_span = pat.span;
1892
1893     if let PatKind::Tuple(ref pat, _) = pat.kind {
1894         if pat.len() == 2 {
1895             let arg_span = arg.span;
1896             let (new_pat_span, kind, ty, mutbl) = match *cx.typeck_results().expr_ty(arg).kind() {
1897                 ty::Ref(_, ty, mutbl) => match (&pat[0].kind, &pat[1].kind) {
1898                     (key, _) if pat_is_wild(cx, key, body) => (pat[1].span, "value", ty, mutbl),
1899                     (_, value) if pat_is_wild(cx, value, body) => (pat[0].span, "key", ty, Mutability::Not),
1900                     _ => return,
1901                 },
1902                 _ => return,
1903             };
1904             let mutbl = match mutbl {
1905                 Mutability::Not => "",
1906                 Mutability::Mut => "_mut",
1907             };
1908             let arg = match arg.kind {
1909                 ExprKind::AddrOf(BorrowKind::Ref, _, ref expr) => &**expr,
1910                 _ => arg,
1911             };
1912
1913             if is_type_diagnostic_item(cx, ty, sym::hashmap_type) || match_type(cx, ty, &paths::BTREEMAP) {
1914                 span_lint_and_then(
1915                     cx,
1916                     FOR_KV_MAP,
1917                     expr.span,
1918                     &format!("you seem to want to iterate on a map's {}s", kind),
1919                     |diag| {
1920                         let map = sugg::Sugg::hir(cx, arg, "map");
1921                         multispan_sugg(
1922                             diag,
1923                             "use the corresponding method",
1924                             vec![
1925                                 (pat_span, snippet(cx, new_pat_span, kind).into_owned()),
1926                                 (arg_span, format!("{}.{}s{}()", map.maybe_par(), kind, mutbl)),
1927                             ],
1928                         );
1929                     },
1930                 );
1931             }
1932         }
1933     }
1934 }
1935
1936 fn check_for_single_element_loop<'tcx>(
1937     cx: &LateContext<'tcx>,
1938     pat: &'tcx Pat<'_>,
1939     arg: &'tcx Expr<'_>,
1940     body: &'tcx Expr<'_>,
1941     expr: &'tcx Expr<'_>,
1942 ) {
1943     if_chain! {
1944         if let ExprKind::AddrOf(BorrowKind::Ref, _, ref arg_expr) = arg.kind;
1945         if let PatKind::Binding(.., target, _) = pat.kind;
1946         if let ExprKind::Array([arg_expression]) = arg_expr.kind;
1947         if let ExprKind::Path(ref list_item) = arg_expression.kind;
1948         if let Some(list_item_name) = single_segment_path(list_item).map(|ps| ps.ident.name);
1949         if let ExprKind::Block(ref block, _) = body.kind;
1950         if !block.stmts.is_empty();
1951
1952         then {
1953             let for_span = get_span_of_entire_for_loop(expr);
1954             let mut block_str = snippet(cx, block.span, "..").into_owned();
1955             block_str.remove(0);
1956             block_str.pop();
1957
1958
1959             span_lint_and_sugg(
1960                 cx,
1961                 SINGLE_ELEMENT_LOOP,
1962                 for_span,
1963                 "for loop over a single element",
1964                 "try",
1965                 format!("{{\n{}let {} = &{};{}}}", " ".repeat(indent_of(cx, block.stmts[0].span).unwrap_or(0)), target.name, list_item_name, block_str),
1966                 Applicability::MachineApplicable
1967             )
1968         }
1969     }
1970 }
1971
1972 /// Check for unnecessary `if let` usage in a for loop where only the `Some` or `Ok` variant of the
1973 /// iterator element is used.
1974 fn check_manual_flatten<'tcx>(
1975     cx: &LateContext<'tcx>,
1976     pat: &'tcx Pat<'_>,
1977     arg: &'tcx Expr<'_>,
1978     body: &'tcx Expr<'_>,
1979     span: Span,
1980 ) {
1981     if let ExprKind::Block(ref block, _) = body.kind {
1982         // Ensure the `if let` statement is the only expression or statement in the for-loop
1983         let inner_expr = if block.stmts.len() == 1 && block.expr.is_none() {
1984             let match_stmt = &block.stmts[0];
1985             if let StmtKind::Semi(inner_expr) = match_stmt.kind {
1986                 Some(inner_expr)
1987             } else {
1988                 None
1989             }
1990         } else if block.stmts.is_empty() {
1991             block.expr
1992         } else {
1993             None
1994         };
1995
1996         if_chain! {
1997             if let Some(inner_expr) = inner_expr;
1998             if let ExprKind::Match(
1999                 ref match_expr, ref match_arms, MatchSource::IfLetDesugar{ contains_else_clause: false }
2000             ) = inner_expr.kind;
2001             // Ensure match_expr in `if let` statement is the same as the pat from the for-loop
2002             if let PatKind::Binding(_, pat_hir_id, _, _) = pat.kind;
2003             if path_to_local_id(match_expr, pat_hir_id);
2004             // Ensure the `if let` statement is for the `Some` variant of `Option` or the `Ok` variant of `Result`
2005             if let PatKind::TupleStruct(QPath::Resolved(None, path), _, _) = match_arms[0].pat.kind;
2006             let some_ctor = is_some_ctor(cx, path.res);
2007             let ok_ctor = is_ok_ctor(cx, path.res);
2008             if some_ctor || ok_ctor;
2009             let if_let_type = if some_ctor { "Some" } else { "Ok" };
2010
2011             then {
2012                 // Prepare the error message
2013                 let msg = format!("unnecessary `if let` since only the `{}` variant of the iterator element is used", if_let_type);
2014
2015                 // Prepare the help message
2016                 let mut applicability = Applicability::MaybeIncorrect;
2017                 let arg_snippet = make_iterator_snippet(cx, arg, &mut applicability);
2018
2019                 span_lint_and_then(
2020                     cx,
2021                     MANUAL_FLATTEN,
2022                     span,
2023                     &msg,
2024                     |diag| {
2025                         let sugg = format!("{}.flatten()", arg_snippet);
2026                         diag.span_suggestion(
2027                             arg.span,
2028                             "try",
2029                             sugg,
2030                             Applicability::MaybeIncorrect,
2031                         );
2032                         diag.span_help(
2033                             inner_expr.span,
2034                             "...and remove the `if let` statement in the for loop",
2035                         );
2036                     }
2037                 );
2038             }
2039         }
2040     }
2041 }
2042
2043 struct MutatePairDelegate<'a, 'tcx> {
2044     cx: &'a LateContext<'tcx>,
2045     hir_id_low: Option<HirId>,
2046     hir_id_high: Option<HirId>,
2047     span_low: Option<Span>,
2048     span_high: Option<Span>,
2049 }
2050
2051 impl<'tcx> Delegate<'tcx> for MutatePairDelegate<'_, 'tcx> {
2052     fn consume(&mut self, _: &PlaceWithHirId<'tcx>, _: HirId, _: ConsumeMode) {}
2053
2054     fn borrow(&mut self, cmt: &PlaceWithHirId<'tcx>, diag_expr_id: HirId, bk: ty::BorrowKind) {
2055         if let ty::BorrowKind::MutBorrow = bk {
2056             if let PlaceBase::Local(id) = cmt.place.base {
2057                 if Some(id) == self.hir_id_low {
2058                     self.span_low = Some(self.cx.tcx.hir().span(diag_expr_id))
2059                 }
2060                 if Some(id) == self.hir_id_high {
2061                     self.span_high = Some(self.cx.tcx.hir().span(diag_expr_id))
2062                 }
2063             }
2064         }
2065     }
2066
2067     fn mutate(&mut self, cmt: &PlaceWithHirId<'tcx>, diag_expr_id: HirId) {
2068         if let PlaceBase::Local(id) = cmt.place.base {
2069             if Some(id) == self.hir_id_low {
2070                 self.span_low = Some(self.cx.tcx.hir().span(diag_expr_id))
2071             }
2072             if Some(id) == self.hir_id_high {
2073                 self.span_high = Some(self.cx.tcx.hir().span(diag_expr_id))
2074             }
2075         }
2076     }
2077 }
2078
2079 impl MutatePairDelegate<'_, '_> {
2080     fn mutation_span(&self) -> (Option<Span>, Option<Span>) {
2081         (self.span_low, self.span_high)
2082     }
2083 }
2084
2085 fn check_for_mut_range_bound(cx: &LateContext<'_>, arg: &Expr<'_>, body: &Expr<'_>) {
2086     if let Some(higher::Range {
2087         start: Some(start),
2088         end: Some(end),
2089         ..
2090     }) = higher::range(arg)
2091     {
2092         let mut_ids = vec![check_for_mutability(cx, start), check_for_mutability(cx, end)];
2093         if mut_ids[0].is_some() || mut_ids[1].is_some() {
2094             let (span_low, span_high) = check_for_mutation(cx, body, &mut_ids);
2095             mut_warn_with_span(cx, span_low);
2096             mut_warn_with_span(cx, span_high);
2097         }
2098     }
2099 }
2100
2101 fn mut_warn_with_span(cx: &LateContext<'_>, span: Option<Span>) {
2102     if let Some(sp) = span {
2103         span_lint(
2104             cx,
2105             MUT_RANGE_BOUND,
2106             sp,
2107             "attempt to mutate range bound within loop; note that the range of the loop is unchanged",
2108         );
2109     }
2110 }
2111
2112 fn check_for_mutability(cx: &LateContext<'_>, bound: &Expr<'_>) -> Option<HirId> {
2113     if_chain! {
2114         if let Some(hir_id) = path_to_local(bound);
2115         if let Node::Binding(pat) = cx.tcx.hir().get(hir_id);
2116         if let PatKind::Binding(BindingAnnotation::Mutable, ..) = pat.kind;
2117         then {
2118             return Some(hir_id);
2119         }
2120     }
2121     None
2122 }
2123
2124 fn check_for_mutation<'tcx>(
2125     cx: &LateContext<'tcx>,
2126     body: &Expr<'_>,
2127     bound_ids: &[Option<HirId>],
2128 ) -> (Option<Span>, Option<Span>) {
2129     let mut delegate = MutatePairDelegate {
2130         cx,
2131         hir_id_low: bound_ids[0],
2132         hir_id_high: bound_ids[1],
2133         span_low: None,
2134         span_high: None,
2135     };
2136     cx.tcx.infer_ctxt().enter(|infcx| {
2137         ExprUseVisitor::new(
2138             &mut delegate,
2139             &infcx,
2140             body.hir_id.owner,
2141             cx.param_env,
2142             cx.typeck_results(),
2143         )
2144         .walk_expr(body);
2145     });
2146     delegate.mutation_span()
2147 }
2148
2149 /// Returns `true` if the pattern is a `PatWild` or an ident prefixed with `_`.
2150 fn pat_is_wild<'tcx>(cx: &LateContext<'tcx>, pat: &'tcx PatKind<'_>, body: &'tcx Expr<'_>) -> bool {
2151     match *pat {
2152         PatKind::Wild => true,
2153         PatKind::Binding(_, id, ident, None) if ident.as_str().starts_with('_') => {
2154             !LocalUsedVisitor::new(cx, id).check_expr(body)
2155         },
2156         _ => false,
2157     }
2158 }
2159
2160 struct VarVisitor<'a, 'tcx> {
2161     /// context reference
2162     cx: &'a LateContext<'tcx>,
2163     /// var name to look for as index
2164     var: HirId,
2165     /// indexed variables that are used mutably
2166     indexed_mut: FxHashSet<Symbol>,
2167     /// indirectly indexed variables (`v[(i + 4) % N]`), the extend is `None` for global
2168     indexed_indirectly: FxHashMap<Symbol, Option<region::Scope>>,
2169     /// subset of `indexed` of vars that are indexed directly: `v[i]`
2170     /// this will not contain cases like `v[calc_index(i)]` or `v[(i + 4) % N]`
2171     indexed_directly: FxHashMap<Symbol, (Option<region::Scope>, Ty<'tcx>)>,
2172     /// Any names that are used outside an index operation.
2173     /// Used to detect things like `&mut vec` used together with `vec[i]`
2174     referenced: FxHashSet<Symbol>,
2175     /// has the loop variable been used in expressions other than the index of
2176     /// an index op?
2177     nonindex: bool,
2178     /// Whether we are inside the `$` in `&mut $` or `$ = foo` or `$.bar`, where bar
2179     /// takes `&mut self`
2180     prefer_mutable: bool,
2181 }
2182
2183 impl<'a, 'tcx> VarVisitor<'a, 'tcx> {
2184     fn check(&mut self, idx: &'tcx Expr<'_>, seqexpr: &'tcx Expr<'_>, expr: &'tcx Expr<'_>) -> bool {
2185         if_chain! {
2186             // the indexed container is referenced by a name
2187             if let ExprKind::Path(ref seqpath) = seqexpr.kind;
2188             if let QPath::Resolved(None, ref seqvar) = *seqpath;
2189             if seqvar.segments.len() == 1;
2190             then {
2191                 let index_used_directly = path_to_local_id(idx, self.var);
2192                 let indexed_indirectly = {
2193                     let mut used_visitor = LocalUsedVisitor::new(self.cx, self.var);
2194                     walk_expr(&mut used_visitor, idx);
2195                     used_visitor.used
2196                 };
2197
2198                 if indexed_indirectly || index_used_directly {
2199                     if self.prefer_mutable {
2200                         self.indexed_mut.insert(seqvar.segments[0].ident.name);
2201                     }
2202                     let res = self.cx.qpath_res(seqpath, seqexpr.hir_id);
2203                     match res {
2204                         Res::Local(hir_id) => {
2205                             let parent_id = self.cx.tcx.hir().get_parent_item(expr.hir_id);
2206                             let parent_def_id = self.cx.tcx.hir().local_def_id(parent_id);
2207                             let extent = self.cx.tcx.region_scope_tree(parent_def_id).var_scope(hir_id.local_id);
2208                             if indexed_indirectly {
2209                                 self.indexed_indirectly.insert(seqvar.segments[0].ident.name, Some(extent));
2210                             }
2211                             if index_used_directly {
2212                                 self.indexed_directly.insert(
2213                                     seqvar.segments[0].ident.name,
2214                                     (Some(extent), self.cx.typeck_results().node_type(seqexpr.hir_id)),
2215                                 );
2216                             }
2217                             return false;  // no need to walk further *on the variable*
2218                         }
2219                         Res::Def(DefKind::Static | DefKind::Const, ..) => {
2220                             if indexed_indirectly {
2221                                 self.indexed_indirectly.insert(seqvar.segments[0].ident.name, None);
2222                             }
2223                             if index_used_directly {
2224                                 self.indexed_directly.insert(
2225                                     seqvar.segments[0].ident.name,
2226                                     (None, self.cx.typeck_results().node_type(seqexpr.hir_id)),
2227                                 );
2228                             }
2229                             return false;  // no need to walk further *on the variable*
2230                         }
2231                         _ => (),
2232                     }
2233                 }
2234             }
2235         }
2236         true
2237     }
2238 }
2239
2240 impl<'a, 'tcx> Visitor<'tcx> for VarVisitor<'a, 'tcx> {
2241     type Map = Map<'tcx>;
2242
2243     fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
2244         if_chain! {
2245             // a range index op
2246             if let ExprKind::MethodCall(ref meth, _, ref args, _) = expr.kind;
2247             if (meth.ident.name == sym::index && match_trait_method(self.cx, expr, &paths::INDEX))
2248                 || (meth.ident.name == sym::index_mut && match_trait_method(self.cx, expr, &paths::INDEX_MUT));
2249             if !self.check(&args[1], &args[0], expr);
2250             then { return }
2251         }
2252
2253         if_chain! {
2254             // an index op
2255             if let ExprKind::Index(ref seqexpr, ref idx) = expr.kind;
2256             if !self.check(idx, seqexpr, expr);
2257             then { return }
2258         }
2259
2260         if_chain! {
2261             // directly using a variable
2262             if let ExprKind::Path(QPath::Resolved(None, path)) = expr.kind;
2263             if let Res::Local(local_id) = path.res;
2264             then {
2265                 if local_id == self.var {
2266                     self.nonindex = true;
2267                 } else {
2268                     // not the correct variable, but still a variable
2269                     self.referenced.insert(path.segments[0].ident.name);
2270                 }
2271             }
2272         }
2273
2274         let old = self.prefer_mutable;
2275         match expr.kind {
2276             ExprKind::AssignOp(_, ref lhs, ref rhs) | ExprKind::Assign(ref lhs, ref rhs, _) => {
2277                 self.prefer_mutable = true;
2278                 self.visit_expr(lhs);
2279                 self.prefer_mutable = false;
2280                 self.visit_expr(rhs);
2281             },
2282             ExprKind::AddrOf(BorrowKind::Ref, mutbl, ref expr) => {
2283                 if mutbl == Mutability::Mut {
2284                     self.prefer_mutable = true;
2285                 }
2286                 self.visit_expr(expr);
2287             },
2288             ExprKind::Call(ref f, args) => {
2289                 self.visit_expr(f);
2290                 for expr in args {
2291                     let ty = self.cx.typeck_results().expr_ty_adjusted(expr);
2292                     self.prefer_mutable = false;
2293                     if let ty::Ref(_, _, mutbl) = *ty.kind() {
2294                         if mutbl == Mutability::Mut {
2295                             self.prefer_mutable = true;
2296                         }
2297                     }
2298                     self.visit_expr(expr);
2299                 }
2300             },
2301             ExprKind::MethodCall(_, _, args, _) => {
2302                 let def_id = self.cx.typeck_results().type_dependent_def_id(expr.hir_id).unwrap();
2303                 for (ty, expr) in self.cx.tcx.fn_sig(def_id).inputs().skip_binder().iter().zip(args) {
2304                     self.prefer_mutable = false;
2305                     if let ty::Ref(_, _, mutbl) = *ty.kind() {
2306                         if mutbl == Mutability::Mut {
2307                             self.prefer_mutable = true;
2308                         }
2309                     }
2310                     self.visit_expr(expr);
2311                 }
2312             },
2313             ExprKind::Closure(_, _, body_id, ..) => {
2314                 let body = self.cx.tcx.hir().body(body_id);
2315                 self.visit_expr(&body.value);
2316             },
2317             _ => walk_expr(self, expr),
2318         }
2319         self.prefer_mutable = old;
2320     }
2321     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
2322         NestedVisitorMap::None
2323     }
2324 }
2325
2326 fn is_used_inside<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, container: &'tcx Expr<'_>) -> bool {
2327     let def_id = match path_to_local(expr) {
2328         Some(id) => id,
2329         None => return false,
2330     };
2331     if let Some(used_mutably) = mutated_variables(container, cx) {
2332         if used_mutably.contains(&def_id) {
2333             return true;
2334         }
2335     }
2336     false
2337 }
2338
2339 fn is_iterator_used_after_while_let<'tcx>(cx: &LateContext<'tcx>, iter_expr: &'tcx Expr<'_>) -> bool {
2340     let def_id = match path_to_local(iter_expr) {
2341         Some(id) => id,
2342         None => return false,
2343     };
2344     let mut visitor = VarUsedAfterLoopVisitor {
2345         def_id,
2346         iter_expr_id: iter_expr.hir_id,
2347         past_while_let: false,
2348         var_used_after_while_let: false,
2349     };
2350     if let Some(enclosing_block) = get_enclosing_block(cx, def_id) {
2351         walk_block(&mut visitor, enclosing_block);
2352     }
2353     visitor.var_used_after_while_let
2354 }
2355
2356 struct VarUsedAfterLoopVisitor {
2357     def_id: HirId,
2358     iter_expr_id: HirId,
2359     past_while_let: bool,
2360     var_used_after_while_let: bool,
2361 }
2362
2363 impl<'tcx> Visitor<'tcx> for VarUsedAfterLoopVisitor {
2364     type Map = Map<'tcx>;
2365
2366     fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
2367         if self.past_while_let {
2368             if path_to_local_id(expr, self.def_id) {
2369                 self.var_used_after_while_let = true;
2370             }
2371         } else if self.iter_expr_id == expr.hir_id {
2372             self.past_while_let = true;
2373         }
2374         walk_expr(self, expr);
2375     }
2376     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
2377         NestedVisitorMap::None
2378     }
2379 }
2380
2381 /// Returns `true` if the type of expr is one that provides `IntoIterator` impls
2382 /// for `&T` and `&mut T`, such as `Vec`.
2383 #[rustfmt::skip]
2384 fn is_ref_iterable_type(cx: &LateContext<'_>, e: &Expr<'_>) -> bool {
2385     // no walk_ptrs_ty: calling iter() on a reference can make sense because it
2386     // will allow further borrows afterwards
2387     let ty = cx.typeck_results().expr_ty(e);
2388     is_iterable_array(ty, cx) ||
2389     is_type_diagnostic_item(cx, ty, sym::vec_type) ||
2390     match_type(cx, ty, &paths::LINKED_LIST) ||
2391     is_type_diagnostic_item(cx, ty, sym::hashmap_type) ||
2392     is_type_diagnostic_item(cx, ty, sym::hashset_type) ||
2393     is_type_diagnostic_item(cx, ty, sym::vecdeque_type) ||
2394     match_type(cx, ty, &paths::BINARY_HEAP) ||
2395     match_type(cx, ty, &paths::BTREEMAP) ||
2396     match_type(cx, ty, &paths::BTREESET)
2397 }
2398
2399 fn is_iterable_array<'tcx>(ty: Ty<'tcx>, cx: &LateContext<'tcx>) -> bool {
2400     // IntoIterator is currently only implemented for array sizes <= 32 in rustc
2401     match ty.kind() {
2402         ty::Array(_, n) => n
2403             .try_eval_usize(cx.tcx, cx.param_env)
2404             .map_or(false, |val| (0..=32).contains(&val)),
2405         _ => false,
2406     }
2407 }
2408
2409 /// If a block begins with a statement (possibly a `let` binding) and has an
2410 /// expression, return it.
2411 fn extract_expr_from_first_stmt<'tcx>(block: &Block<'tcx>) -> Option<&'tcx Expr<'tcx>> {
2412     if block.stmts.is_empty() {
2413         return None;
2414     }
2415     if let StmtKind::Local(ref local) = block.stmts[0].kind {
2416         local.init //.map(|expr| expr)
2417     } else {
2418         None
2419     }
2420 }
2421
2422 /// If a block begins with an expression (with or without semicolon), return it.
2423 fn extract_first_expr<'tcx>(block: &Block<'tcx>) -> Option<&'tcx Expr<'tcx>> {
2424     match block.expr {
2425         Some(ref expr) if block.stmts.is_empty() => Some(expr),
2426         None if !block.stmts.is_empty() => match block.stmts[0].kind {
2427             StmtKind::Expr(ref expr) | StmtKind::Semi(ref expr) => Some(expr),
2428             StmtKind::Local(..) | StmtKind::Item(..) => None,
2429         },
2430         _ => None,
2431     }
2432 }
2433
2434 /// Returns `true` if expr contains a single break expr without destination label
2435 /// and
2436 /// passed expression. The expression may be within a block.
2437 fn is_simple_break_expr(expr: &Expr<'_>) -> bool {
2438     match expr.kind {
2439         ExprKind::Break(dest, ref passed_expr) if dest.label.is_none() && passed_expr.is_none() => true,
2440         ExprKind::Block(ref b, _) => extract_first_expr(b).map_or(false, |subexpr| is_simple_break_expr(subexpr)),
2441         _ => false,
2442     }
2443 }
2444
2445 #[derive(Debug, PartialEq)]
2446 enum IncrementVisitorVarState {
2447     Initial,  // Not examined yet
2448     IncrOnce, // Incremented exactly once, may be a loop counter
2449     DontWarn,
2450 }
2451
2452 /// Scan a for loop for variables that are incremented exactly once and not used after that.
2453 struct IncrementVisitor<'a, 'tcx> {
2454     cx: &'a LateContext<'tcx>,                          // context reference
2455     states: FxHashMap<HirId, IncrementVisitorVarState>, // incremented variables
2456     depth: u32,                                         // depth of conditional expressions
2457     done: bool,
2458 }
2459
2460 impl<'a, 'tcx> IncrementVisitor<'a, 'tcx> {
2461     fn new(cx: &'a LateContext<'tcx>) -> Self {
2462         Self {
2463             cx,
2464             states: FxHashMap::default(),
2465             depth: 0,
2466             done: false,
2467         }
2468     }
2469
2470     fn into_results(self) -> impl Iterator<Item = HirId> {
2471         self.states.into_iter().filter_map(|(id, state)| {
2472             if state == IncrementVisitorVarState::IncrOnce {
2473                 Some(id)
2474             } else {
2475                 None
2476             }
2477         })
2478     }
2479 }
2480
2481 impl<'a, 'tcx> Visitor<'tcx> for IncrementVisitor<'a, 'tcx> {
2482     type Map = Map<'tcx>;
2483
2484     fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
2485         if self.done {
2486             return;
2487         }
2488
2489         // If node is a variable
2490         if let Some(def_id) = path_to_local(expr) {
2491             if let Some(parent) = get_parent_expr(self.cx, expr) {
2492                 let state = self.states.entry(def_id).or_insert(IncrementVisitorVarState::Initial);
2493                 if *state == IncrementVisitorVarState::IncrOnce {
2494                     *state = IncrementVisitorVarState::DontWarn;
2495                     return;
2496                 }
2497
2498                 match parent.kind {
2499                     ExprKind::AssignOp(op, ref lhs, ref rhs) => {
2500                         if lhs.hir_id == expr.hir_id {
2501                             *state = if op.node == BinOpKind::Add
2502                                 && is_integer_const(self.cx, rhs, 1)
2503                                 && *state == IncrementVisitorVarState::Initial
2504                                 && self.depth == 0
2505                             {
2506                                 IncrementVisitorVarState::IncrOnce
2507                             } else {
2508                                 // Assigned some other value or assigned multiple times
2509                                 IncrementVisitorVarState::DontWarn
2510                             };
2511                         }
2512                     },
2513                     ExprKind::Assign(ref lhs, _, _) if lhs.hir_id == expr.hir_id => {
2514                         *state = IncrementVisitorVarState::DontWarn
2515                     },
2516                     ExprKind::AddrOf(BorrowKind::Ref, mutability, _) if mutability == Mutability::Mut => {
2517                         *state = IncrementVisitorVarState::DontWarn
2518                     },
2519                     _ => (),
2520                 }
2521             }
2522
2523             walk_expr(self, expr);
2524         } else if is_loop(expr) || is_conditional(expr) {
2525             self.depth += 1;
2526             walk_expr(self, expr);
2527             self.depth -= 1;
2528         } else if let ExprKind::Continue(_) = expr.kind {
2529             self.done = true;
2530         } else {
2531             walk_expr(self, expr);
2532         }
2533     }
2534     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
2535         NestedVisitorMap::None
2536     }
2537 }
2538
2539 enum InitializeVisitorState<'hir> {
2540     Initial,          // Not examined yet
2541     Declared(Symbol), // Declared but not (yet) initialized
2542     Initialized {
2543         name: Symbol,
2544         initializer: &'hir Expr<'hir>,
2545     },
2546     DontWarn,
2547 }
2548
2549 /// Checks whether a variable is initialized at the start of a loop and not modified
2550 /// and used after the loop.
2551 struct InitializeVisitor<'a, 'tcx> {
2552     cx: &'a LateContext<'tcx>,  // context reference
2553     end_expr: &'tcx Expr<'tcx>, // the for loop. Stop scanning here.
2554     var_id: HirId,
2555     state: InitializeVisitorState<'tcx>,
2556     depth: u32, // depth of conditional expressions
2557     past_loop: bool,
2558 }
2559
2560 impl<'a, 'tcx> InitializeVisitor<'a, 'tcx> {
2561     fn new(cx: &'a LateContext<'tcx>, end_expr: &'tcx Expr<'tcx>, var_id: HirId) -> Self {
2562         Self {
2563             cx,
2564             end_expr,
2565             var_id,
2566             state: InitializeVisitorState::Initial,
2567             depth: 0,
2568             past_loop: false,
2569         }
2570     }
2571
2572     fn get_result(&self) -> Option<(Symbol, &'tcx Expr<'tcx>)> {
2573         if let InitializeVisitorState::Initialized { name, initializer } = self.state {
2574             Some((name, initializer))
2575         } else {
2576             None
2577         }
2578     }
2579 }
2580
2581 impl<'a, 'tcx> Visitor<'tcx> for InitializeVisitor<'a, 'tcx> {
2582     type Map = Map<'tcx>;
2583
2584     fn visit_stmt(&mut self, stmt: &'tcx Stmt<'_>) {
2585         // Look for declarations of the variable
2586         if_chain! {
2587             if let StmtKind::Local(ref local) = stmt.kind;
2588             if local.pat.hir_id == self.var_id;
2589             if let PatKind::Binding(.., ident, _) = local.pat.kind;
2590             then {
2591                 self.state = local.init.map_or(InitializeVisitorState::Declared(ident.name), |init| {
2592                     InitializeVisitorState::Initialized {
2593                         initializer: init,
2594                         name: ident.name,
2595                     }
2596                 })
2597             }
2598         }
2599         walk_stmt(self, stmt);
2600     }
2601
2602     fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
2603         if matches!(self.state, InitializeVisitorState::DontWarn) {
2604             return;
2605         }
2606         if expr.hir_id == self.end_expr.hir_id {
2607             self.past_loop = true;
2608             return;
2609         }
2610         // No need to visit expressions before the variable is
2611         // declared
2612         if matches!(self.state, InitializeVisitorState::Initial) {
2613             return;
2614         }
2615
2616         // If node is the desired variable, see how it's used
2617         if path_to_local_id(expr, self.var_id) {
2618             if self.past_loop {
2619                 self.state = InitializeVisitorState::DontWarn;
2620                 return;
2621             }
2622
2623             if let Some(parent) = get_parent_expr(self.cx, expr) {
2624                 match parent.kind {
2625                     ExprKind::AssignOp(_, ref lhs, _) if lhs.hir_id == expr.hir_id => {
2626                         self.state = InitializeVisitorState::DontWarn;
2627                     },
2628                     ExprKind::Assign(ref lhs, ref rhs, _) if lhs.hir_id == expr.hir_id => {
2629                         self.state = if_chain! {
2630                             if self.depth == 0;
2631                             if let InitializeVisitorState::Declared(name)
2632                                 | InitializeVisitorState::Initialized { name, ..} = self.state;
2633                             then {
2634                                 InitializeVisitorState::Initialized { initializer: rhs, name }
2635                             } else {
2636                                 InitializeVisitorState::DontWarn
2637                             }
2638                         }
2639                     },
2640                     ExprKind::AddrOf(BorrowKind::Ref, mutability, _) if mutability == Mutability::Mut => {
2641                         self.state = InitializeVisitorState::DontWarn
2642                     },
2643                     _ => (),
2644                 }
2645             }
2646
2647             walk_expr(self, expr);
2648         } else if !self.past_loop && is_loop(expr) {
2649             self.state = InitializeVisitorState::DontWarn;
2650         } else if is_conditional(expr) {
2651             self.depth += 1;
2652             walk_expr(self, expr);
2653             self.depth -= 1;
2654         } else {
2655             walk_expr(self, expr);
2656         }
2657     }
2658
2659     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
2660         NestedVisitorMap::OnlyBodies(self.cx.tcx.hir())
2661     }
2662 }
2663
2664 fn is_loop(expr: &Expr<'_>) -> bool {
2665     matches!(expr.kind, ExprKind::Loop(..))
2666 }
2667
2668 fn is_conditional(expr: &Expr<'_>) -> bool {
2669     matches!(expr.kind, ExprKind::If(..) | ExprKind::Match(..))
2670 }
2671
2672 fn is_nested(cx: &LateContext<'_>, match_expr: &Expr<'_>, iter_expr: &Expr<'_>) -> bool {
2673     if_chain! {
2674         if let Some(loop_block) = get_enclosing_block(cx, match_expr.hir_id);
2675         let parent_node = cx.tcx.hir().get_parent_node(loop_block.hir_id);
2676         if let Some(Node::Expr(loop_expr)) = cx.tcx.hir().find(parent_node);
2677         then {
2678             return is_loop_nested(cx, loop_expr, iter_expr)
2679         }
2680     }
2681     false
2682 }
2683
2684 fn is_loop_nested(cx: &LateContext<'_>, loop_expr: &Expr<'_>, iter_expr: &Expr<'_>) -> bool {
2685     let mut id = loop_expr.hir_id;
2686     let iter_id = if let Some(id) = path_to_local(iter_expr) {
2687         id
2688     } else {
2689         return true;
2690     };
2691     loop {
2692         let parent = cx.tcx.hir().get_parent_node(id);
2693         if parent == id {
2694             return false;
2695         }
2696         match cx.tcx.hir().find(parent) {
2697             Some(Node::Expr(expr)) => {
2698                 if let ExprKind::Loop(..) = expr.kind {
2699                     return true;
2700                 };
2701             },
2702             Some(Node::Block(block)) => {
2703                 let mut block_visitor = LoopNestVisitor {
2704                     hir_id: id,
2705                     iterator: iter_id,
2706                     nesting: Unknown,
2707                 };
2708                 walk_block(&mut block_visitor, block);
2709                 if block_visitor.nesting == RuledOut {
2710                     return false;
2711                 }
2712             },
2713             Some(Node::Stmt(_)) => (),
2714             _ => {
2715                 return false;
2716             },
2717         }
2718         id = parent;
2719     }
2720 }
2721
2722 #[derive(PartialEq, Eq)]
2723 enum Nesting {
2724     Unknown,     // no nesting detected yet
2725     RuledOut,    // the iterator is initialized or assigned within scope
2726     LookFurther, // no nesting detected, no further walk required
2727 }
2728
2729 use self::Nesting::{LookFurther, RuledOut, Unknown};
2730
2731 struct LoopNestVisitor {
2732     hir_id: HirId,
2733     iterator: HirId,
2734     nesting: Nesting,
2735 }
2736
2737 impl<'tcx> Visitor<'tcx> for LoopNestVisitor {
2738     type Map = Map<'tcx>;
2739
2740     fn visit_stmt(&mut self, stmt: &'tcx Stmt<'_>) {
2741         if stmt.hir_id == self.hir_id {
2742             self.nesting = LookFurther;
2743         } else if self.nesting == Unknown {
2744             walk_stmt(self, stmt);
2745         }
2746     }
2747
2748     fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
2749         if self.nesting != Unknown {
2750             return;
2751         }
2752         if expr.hir_id == self.hir_id {
2753             self.nesting = LookFurther;
2754             return;
2755         }
2756         match expr.kind {
2757             ExprKind::Assign(ref path, _, _) | ExprKind::AssignOp(_, ref path, _) => {
2758                 if path_to_local_id(path, self.iterator) {
2759                     self.nesting = RuledOut;
2760                 }
2761             },
2762             _ => walk_expr(self, expr),
2763         }
2764     }
2765
2766     fn visit_pat(&mut self, pat: &'tcx Pat<'_>) {
2767         if self.nesting != Unknown {
2768             return;
2769         }
2770         if let PatKind::Binding(_, id, ..) = pat.kind {
2771             if id == self.iterator {
2772                 self.nesting = RuledOut;
2773                 return;
2774             }
2775         }
2776         walk_pat(self, pat)
2777     }
2778
2779     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
2780         NestedVisitorMap::None
2781     }
2782 }
2783
2784 fn check_infinite_loop<'tcx>(cx: &LateContext<'tcx>, cond: &'tcx Expr<'_>, expr: &'tcx Expr<'_>) {
2785     if constant(cx, cx.typeck_results(), cond).is_some() {
2786         // A pure constant condition (e.g., `while false`) is not linted.
2787         return;
2788     }
2789
2790     let mut var_visitor = VarCollectorVisitor {
2791         cx,
2792         ids: FxHashSet::default(),
2793         def_ids: FxHashMap::default(),
2794         skip: false,
2795     };
2796     var_visitor.visit_expr(cond);
2797     if var_visitor.skip {
2798         return;
2799     }
2800     let used_in_condition = &var_visitor.ids;
2801     let no_cond_variable_mutated = if let Some(used_mutably) = mutated_variables(expr, cx) {
2802         used_in_condition.is_disjoint(&used_mutably)
2803     } else {
2804         return;
2805     };
2806     let mutable_static_in_cond = var_visitor.def_ids.iter().any(|(_, v)| *v);
2807
2808     let mut has_break_or_return_visitor = HasBreakOrReturnVisitor {
2809         has_break_or_return: false,
2810     };
2811     has_break_or_return_visitor.visit_expr(expr);
2812     let has_break_or_return = has_break_or_return_visitor.has_break_or_return;
2813
2814     if no_cond_variable_mutated && !mutable_static_in_cond {
2815         span_lint_and_then(
2816             cx,
2817             WHILE_IMMUTABLE_CONDITION,
2818             cond.span,
2819             "variables in the condition are not mutated in the loop body",
2820             |diag| {
2821                 diag.note("this may lead to an infinite or to a never running loop");
2822
2823                 if has_break_or_return {
2824                     diag.note("this loop contains `return`s or `break`s");
2825                     diag.help("rewrite it as `if cond { loop { } }`");
2826                 }
2827             },
2828         );
2829     }
2830 }
2831
2832 struct HasBreakOrReturnVisitor {
2833     has_break_or_return: bool,
2834 }
2835
2836 impl<'tcx> Visitor<'tcx> for HasBreakOrReturnVisitor {
2837     type Map = Map<'tcx>;
2838
2839     fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
2840         if self.has_break_or_return {
2841             return;
2842         }
2843
2844         match expr.kind {
2845             ExprKind::Ret(_) | ExprKind::Break(_, _) => {
2846                 self.has_break_or_return = true;
2847                 return;
2848             },
2849             _ => {},
2850         }
2851
2852         walk_expr(self, expr);
2853     }
2854
2855     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
2856         NestedVisitorMap::None
2857     }
2858 }
2859
2860 /// Collects the set of variables in an expression
2861 /// Stops analysis if a function call is found
2862 /// Note: In some cases such as `self`, there are no mutable annotation,
2863 /// All variables definition IDs are collected
2864 struct VarCollectorVisitor<'a, 'tcx> {
2865     cx: &'a LateContext<'tcx>,
2866     ids: FxHashSet<HirId>,
2867     def_ids: FxHashMap<def_id::DefId, bool>,
2868     skip: bool,
2869 }
2870
2871 impl<'a, 'tcx> VarCollectorVisitor<'a, 'tcx> {
2872     fn insert_def_id(&mut self, ex: &'tcx Expr<'_>) {
2873         if_chain! {
2874             if let ExprKind::Path(ref qpath) = ex.kind;
2875             if let QPath::Resolved(None, _) = *qpath;
2876             let res = self.cx.qpath_res(qpath, ex.hir_id);
2877             then {
2878                 match res {
2879                     Res::Local(hir_id) => {
2880                         self.ids.insert(hir_id);
2881                     },
2882                     Res::Def(DefKind::Static, def_id) => {
2883                         let mutable = self.cx.tcx.is_mutable_static(def_id);
2884                         self.def_ids.insert(def_id, mutable);
2885                     },
2886                     _ => {},
2887                 }
2888             }
2889         }
2890     }
2891 }
2892
2893 impl<'a, 'tcx> Visitor<'tcx> for VarCollectorVisitor<'a, 'tcx> {
2894     type Map = Map<'tcx>;
2895
2896     fn visit_expr(&mut self, ex: &'tcx Expr<'_>) {
2897         match ex.kind {
2898             ExprKind::Path(_) => self.insert_def_id(ex),
2899             // If there is any function/method call… we just stop analysis
2900             ExprKind::Call(..) | ExprKind::MethodCall(..) => self.skip = true,
2901
2902             _ => walk_expr(self, ex),
2903         }
2904     }
2905
2906     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
2907         NestedVisitorMap::None
2908     }
2909 }
2910
2911 const NEEDLESS_COLLECT_MSG: &str = "avoid using `collect()` when not needed";
2912
2913 fn check_needless_collect<'tcx>(expr: &'tcx Expr<'_>, cx: &LateContext<'tcx>) {
2914     check_needless_collect_direct_usage(expr, cx);
2915     check_needless_collect_indirect_usage(expr, cx);
2916 }
2917 fn check_needless_collect_direct_usage<'tcx>(expr: &'tcx Expr<'_>, cx: &LateContext<'tcx>) {
2918     if_chain! {
2919         if let ExprKind::MethodCall(ref method, _, ref args, _) = expr.kind;
2920         if let ExprKind::MethodCall(ref chain_method, _, _, _) = args[0].kind;
2921         if chain_method.ident.name == sym!(collect) && match_trait_method(cx, &args[0], &paths::ITERATOR);
2922         if let Some(ref generic_args) = chain_method.args;
2923         if let Some(GenericArg::Type(ref ty)) = generic_args.args.get(0);
2924         then {
2925             let ty = cx.typeck_results().node_type(ty.hir_id);
2926             if is_type_diagnostic_item(cx, ty, sym::vec_type) ||
2927                 is_type_diagnostic_item(cx, ty, sym::vecdeque_type) ||
2928                 match_type(cx, ty, &paths::BTREEMAP) ||
2929                 is_type_diagnostic_item(cx, ty, sym::hashmap_type) {
2930                 if method.ident.name == sym!(len) {
2931                     let span = shorten_needless_collect_span(expr);
2932                     span_lint_and_sugg(
2933                         cx,
2934                         NEEDLESS_COLLECT,
2935                         span,
2936                         NEEDLESS_COLLECT_MSG,
2937                         "replace with",
2938                         "count()".to_string(),
2939                         Applicability::MachineApplicable,
2940                     );
2941                 }
2942                 if method.ident.name == sym!(is_empty) {
2943                     let span = shorten_needless_collect_span(expr);
2944                     span_lint_and_sugg(
2945                         cx,
2946                         NEEDLESS_COLLECT,
2947                         span,
2948                         NEEDLESS_COLLECT_MSG,
2949                         "replace with",
2950                         "next().is_none()".to_string(),
2951                         Applicability::MachineApplicable,
2952                     );
2953                 }
2954                 if method.ident.name == sym!(contains) {
2955                     let contains_arg = snippet(cx, args[1].span, "??");
2956                     let span = shorten_needless_collect_span(expr);
2957                     span_lint_and_then(
2958                         cx,
2959                         NEEDLESS_COLLECT,
2960                         span,
2961                         NEEDLESS_COLLECT_MSG,
2962                         |diag| {
2963                             let (arg, pred) = contains_arg
2964                                     .strip_prefix('&')
2965                                     .map_or(("&x", &*contains_arg), |s| ("x", s));
2966                             diag.span_suggestion(
2967                                 span,
2968                                 "replace with",
2969                                 format!(
2970                                     "any(|{}| x == {})",
2971                                     arg, pred
2972                                 ),
2973                                 Applicability::MachineApplicable,
2974                             );
2975                         }
2976                     );
2977                 }
2978             }
2979         }
2980     }
2981 }
2982
2983 fn check_needless_collect_indirect_usage<'tcx>(expr: &'tcx Expr<'_>, cx: &LateContext<'tcx>) {
2984     if let ExprKind::Block(ref block, _) = expr.kind {
2985         for ref stmt in block.stmts {
2986             if_chain! {
2987                 if let StmtKind::Local(
2988                     Local { pat: Pat { hir_id: pat_id, kind: PatKind::Binding(_, _, ident, .. ), .. },
2989                     init: Some(ref init_expr), .. }
2990                 ) = stmt.kind;
2991                 if let ExprKind::MethodCall(ref method_name, _, &[ref iter_source], ..) = init_expr.kind;
2992                 if method_name.ident.name == sym!(collect) && match_trait_method(cx, &init_expr, &paths::ITERATOR);
2993                 if let Some(ref generic_args) = method_name.args;
2994                 if let Some(GenericArg::Type(ref ty)) = generic_args.args.get(0);
2995                 if let ty = cx.typeck_results().node_type(ty.hir_id);
2996                 if is_type_diagnostic_item(cx, ty, sym::vec_type) ||
2997                     is_type_diagnostic_item(cx, ty, sym::vecdeque_type) ||
2998                     match_type(cx, ty, &paths::LINKED_LIST);
2999                 if let Some(iter_calls) = detect_iter_and_into_iters(block, *ident);
3000                 if iter_calls.len() == 1;
3001                 then {
3002                     let mut used_count_visitor = UsedCountVisitor {
3003                         cx,
3004                         id: *pat_id,
3005                         count: 0,
3006                     };
3007                     walk_block(&mut used_count_visitor, block);
3008                     if used_count_visitor.count > 1 {
3009                         return;
3010                     }
3011
3012                     // Suggest replacing iter_call with iter_replacement, and removing stmt
3013                     let iter_call = &iter_calls[0];
3014                     span_lint_and_then(
3015                         cx,
3016                         NEEDLESS_COLLECT,
3017                         stmt.span.until(iter_call.span),
3018                         NEEDLESS_COLLECT_MSG,
3019                         |diag| {
3020                             let iter_replacement = format!("{}{}", Sugg::hir(cx, iter_source, ".."), iter_call.get_iter_method(cx));
3021                             diag.multipart_suggestion(
3022                                 iter_call.get_suggestion_text(),
3023                                 vec![
3024                                     (stmt.span, String::new()),
3025                                     (iter_call.span, iter_replacement)
3026                                 ],
3027                                 Applicability::MachineApplicable,// MaybeIncorrect,
3028                             ).emit();
3029                         },
3030                     );
3031                 }
3032             }
3033         }
3034     }
3035 }
3036
3037 struct IterFunction {
3038     func: IterFunctionKind,
3039     span: Span,
3040 }
3041 impl IterFunction {
3042     fn get_iter_method(&self, cx: &LateContext<'_>) -> String {
3043         match &self.func {
3044             IterFunctionKind::IntoIter => String::new(),
3045             IterFunctionKind::Len => String::from(".count()"),
3046             IterFunctionKind::IsEmpty => String::from(".next().is_none()"),
3047             IterFunctionKind::Contains(span) => {
3048                 let s = snippet(cx, *span, "..");
3049                 if let Some(stripped) = s.strip_prefix('&') {
3050                     format!(".any(|x| x == {})", stripped)
3051                 } else {
3052                     format!(".any(|x| x == *{})", s)
3053                 }
3054             },
3055         }
3056     }
3057     fn get_suggestion_text(&self) -> &'static str {
3058         match &self.func {
3059             IterFunctionKind::IntoIter => {
3060                 "Use the original Iterator instead of collecting it and then producing a new one"
3061             },
3062             IterFunctionKind::Len => {
3063                 "Take the original Iterator's count instead of collecting it and finding the length"
3064             },
3065             IterFunctionKind::IsEmpty => {
3066                 "Check if the original Iterator has anything instead of collecting it and seeing if it's empty"
3067             },
3068             IterFunctionKind::Contains(_) => {
3069                 "Check if the original Iterator contains an element instead of collecting then checking"
3070             },
3071         }
3072     }
3073 }
3074 enum IterFunctionKind {
3075     IntoIter,
3076     Len,
3077     IsEmpty,
3078     Contains(Span),
3079 }
3080
3081 struct IterFunctionVisitor {
3082     uses: Vec<IterFunction>,
3083     seen_other: bool,
3084     target: Ident,
3085 }
3086 impl<'tcx> Visitor<'tcx> for IterFunctionVisitor {
3087     fn visit_expr(&mut self, expr: &'tcx Expr<'tcx>) {
3088         // Check function calls on our collection
3089         if_chain! {
3090             if let ExprKind::MethodCall(method_name, _, ref args, _) = &expr.kind;
3091             if let Some(Expr { kind: ExprKind::Path(QPath::Resolved(_, ref path)), .. }) = args.get(0);
3092             if let &[name] = &path.segments;
3093             if name.ident == self.target;
3094             then {
3095                 let len = sym!(len);
3096                 let is_empty = sym!(is_empty);
3097                 let contains = sym!(contains);
3098                 match method_name.ident.name {
3099                     sym::into_iter => self.uses.push(
3100                         IterFunction { func: IterFunctionKind::IntoIter, span: expr.span }
3101                     ),
3102                     name if name == len => self.uses.push(
3103                         IterFunction { func: IterFunctionKind::Len, span: expr.span }
3104                     ),
3105                     name if name == is_empty => self.uses.push(
3106                         IterFunction { func: IterFunctionKind::IsEmpty, span: expr.span }
3107                     ),
3108                     name if name == contains => self.uses.push(
3109                         IterFunction { func: IterFunctionKind::Contains(args[1].span), span: expr.span }
3110                     ),
3111                     _ => self.seen_other = true,
3112                 }
3113                 return
3114             }
3115         }
3116         // Check if the collection is used for anything else
3117         if_chain! {
3118             if let Expr { kind: ExprKind::Path(QPath::Resolved(_, ref path)), .. } = expr;
3119             if let &[name] = &path.segments;
3120             if name.ident == self.target;
3121             then {
3122                 self.seen_other = true;
3123             } else {
3124                 walk_expr(self, expr);
3125             }
3126         }
3127     }
3128
3129     type Map = Map<'tcx>;
3130     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
3131         NestedVisitorMap::None
3132     }
3133 }
3134
3135 struct UsedCountVisitor<'a, 'tcx> {
3136     cx: &'a LateContext<'tcx>,
3137     id: HirId,
3138     count: usize,
3139 }
3140
3141 impl<'a, 'tcx> Visitor<'tcx> for UsedCountVisitor<'a, 'tcx> {
3142     type Map = Map<'tcx>;
3143
3144     fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
3145         if path_to_local_id(expr, self.id) {
3146             self.count += 1;
3147         } else {
3148             walk_expr(self, expr);
3149         }
3150     }
3151
3152     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
3153         NestedVisitorMap::OnlyBodies(self.cx.tcx.hir())
3154     }
3155 }
3156
3157 /// Detect the occurrences of calls to `iter` or `into_iter` for the
3158 /// given identifier
3159 fn detect_iter_and_into_iters<'tcx>(block: &'tcx Block<'tcx>, identifier: Ident) -> Option<Vec<IterFunction>> {
3160     let mut visitor = IterFunctionVisitor {
3161         uses: Vec::new(),
3162         target: identifier,
3163         seen_other: false,
3164     };
3165     visitor.visit_block(block);
3166     if visitor.seen_other {
3167         None
3168     } else {
3169         Some(visitor.uses)
3170     }
3171 }
3172
3173 fn shorten_needless_collect_span(expr: &Expr<'_>) -> Span {
3174     if_chain! {
3175         if let ExprKind::MethodCall(.., args, _) = &expr.kind;
3176         if let ExprKind::MethodCall(_, span, ..) = &args[0].kind;
3177         then {
3178             return expr.span.with_lo(span.lo());
3179         }
3180     }
3181     unreachable!();
3182 }