]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/loops.rs
Merge branch 'master' into fix_manual_memcpy
[rust.git] / clippy_lints / src / loops.rs
1 use crate::consts::{constant, Constant};
2 use crate::reexport::Name;
3 use crate::utils::paths;
4 use crate::utils::usage::{is_unused, mutated_variables};
5 use crate::utils::{
6     get_enclosing_block, get_parent_expr, get_trait_def_id, has_iter_method, higher, implements_trait,
7     is_integer_const, is_no_std_crate, is_refutable, last_path_segment, match_trait_method, match_type, match_var,
8     multispan_sugg, snippet, snippet_opt, snippet_with_applicability, span_lint, span_lint_and_help,
9     span_lint_and_sugg, span_lint_and_then, SpanlessEq,
10 };
11 use crate::utils::{is_type_diagnostic_item, qpath_res, same_tys, sext, sugg};
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, LoopSource,
20     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};
28 use rustc_session::{declare_lint_pass, declare_tool_lint};
29 use rustc_span::source_map::Span;
30 use rustc_span::BytePos;
31 use rustc_typeck::expr_use_visitor::{ConsumeMode, Delegate, ExprUseVisitor, Place, PlaceBase};
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` 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     /// ```ignore
180     /// for x in option {
181     ///     ..
182     /// }
183     /// ```
184     ///
185     /// This should be
186     /// ```ignore
187     /// if let Some(x) = option {
188     ///     ..
189     /// }
190     /// ```
191     pub FOR_LOOP_OVER_OPTION,
192     correctness,
193     "for-looping over an `Option`, which is more clearly expressed as an `if let`"
194 }
195
196 declare_clippy_lint! {
197     /// **What it does:** Checks for `for` loops over `Result` values.
198     ///
199     /// **Why is this bad?** Readability. This is more clearly expressed as an `if
200     /// let`.
201     ///
202     /// **Known problems:** None.
203     ///
204     /// **Example:**
205     /// ```ignore
206     /// for x in result {
207     ///     ..
208     /// }
209     /// ```
210     ///
211     /// This should be
212     /// ```ignore
213     /// if let Ok(x) = result {
214     ///     ..
215     /// }
216     /// ```
217     pub FOR_LOOP_OVER_RESULT,
218     correctness,
219     "for-looping over a `Result`, which is more clearly expressed as an `if let`"
220 }
221
222 declare_clippy_lint! {
223     /// **What it does:** Detects `loop + match` combinations that are easier
224     /// written as a `while let` loop.
225     ///
226     /// **Why is this bad?** The `while let` loop is usually shorter and more
227     /// readable.
228     ///
229     /// **Known problems:** Sometimes the wrong binding is displayed (#383).
230     ///
231     /// **Example:**
232     /// ```rust,no_run
233     /// # let y = Some(1);
234     /// loop {
235     ///     let x = match y {
236     ///         Some(x) => x,
237     ///         None => break,
238     ///     };
239     ///     // .. do something with x
240     /// }
241     /// // is easier written as
242     /// while let Some(x) = y {
243     ///     // .. do something with x
244     /// };
245     /// ```
246     pub WHILE_LET_LOOP,
247     complexity,
248     "`loop { if let { ... } else break }`, which can be written as a `while let` loop"
249 }
250
251 declare_clippy_lint! {
252     /// **What it does:** Checks for functions collecting an iterator when collect
253     /// is not needed.
254     ///
255     /// **Why is this bad?** `collect` causes the allocation of a new data structure,
256     /// when this allocation may not be needed.
257     ///
258     /// **Known problems:**
259     /// None
260     ///
261     /// **Example:**
262     /// ```rust
263     /// # let iterator = vec![1].into_iter();
264     /// let len = iterator.clone().collect::<Vec<_>>().len();
265     /// // should be
266     /// let len = iterator.count();
267     /// ```
268     pub NEEDLESS_COLLECT,
269     perf,
270     "collecting an iterator when collect is not needed"
271 }
272
273 declare_clippy_lint! {
274     /// **What it does:** Checks for loops over ranges `x..y` where both `x` and `y`
275     /// are constant and `x` is greater or equal to `y`, unless the range is
276     /// reversed or has a negative `.step_by(_)`.
277     ///
278     /// **Why is it bad?** Such loops will either be skipped or loop until
279     /// wrap-around (in debug code, this may `panic!()`). Both options are probably
280     /// not intended.
281     ///
282     /// **Known problems:** The lint cannot catch loops over dynamically defined
283     /// ranges. Doing this would require simulating all possible inputs and code
284     /// paths through the program, which would be complex and error-prone.
285     ///
286     /// **Example:**
287     /// ```ignore
288     /// for x in 5..10 - 5 {
289     ///     ..
290     /// } // oops, stray `-`
291     /// ```
292     pub REVERSE_RANGE_LOOP,
293     correctness,
294     "iteration over an empty range, such as `10..0` or `5..5`"
295 }
296
297 declare_clippy_lint! {
298     /// **What it does:** Checks `for` loops over slices with an explicit counter
299     /// and suggests the use of `.enumerate()`.
300     ///
301     /// **Why is it bad?** Using `.enumerate()` makes the intent more clear,
302     /// declutters the code and may be faster in some instances.
303     ///
304     /// **Known problems:** None.
305     ///
306     /// **Example:**
307     /// ```rust
308     /// # let v = vec![1];
309     /// # fn bar(bar: usize, baz: usize) {}
310     /// let mut i = 0;
311     /// for item in &v {
312     ///     bar(i, *item);
313     ///     i += 1;
314     /// }
315     /// ```
316     /// Could be written as
317     /// ```rust
318     /// # let v = vec![1];
319     /// # fn bar(bar: usize, baz: usize) {}
320     /// for (i, item) in v.iter().enumerate() { bar(i, *item); }
321     /// ```
322     pub EXPLICIT_COUNTER_LOOP,
323     complexity,
324     "for-looping with an explicit counter when `_.enumerate()` would do"
325 }
326
327 declare_clippy_lint! {
328     /// **What it does:** Checks for empty `loop` expressions.
329     ///
330     /// **Why is this bad?** Those busy loops burn CPU cycles without doing
331     /// anything. Think of the environment and either block on something or at least
332     /// make the thread sleep for some microseconds.
333     ///
334     /// **Known problems:** None.
335     ///
336     /// **Example:**
337     /// ```no_run
338     /// loop {}
339     /// ```
340     pub EMPTY_LOOP,
341     style,
342     "empty `loop {}`, which should block or sleep"
343 }
344
345 declare_clippy_lint! {
346     /// **What it does:** Checks for `while let` expressions on iterators.
347     ///
348     /// **Why is this bad?** Readability. A simple `for` loop is shorter and conveys
349     /// the intent better.
350     ///
351     /// **Known problems:** None.
352     ///
353     /// **Example:**
354     /// ```ignore
355     /// while let Some(val) = iter() {
356     ///     ..
357     /// }
358     /// ```
359     pub WHILE_LET_ON_ITERATOR,
360     style,
361     "using a while-let loop instead of a for loop on an iterator"
362 }
363
364 declare_clippy_lint! {
365     /// **What it does:** Checks for iterating a map (`HashMap` or `BTreeMap`) and
366     /// ignoring either the keys or values.
367     ///
368     /// **Why is this bad?** Readability. There are `keys` and `values` methods that
369     /// can be used to express that don't need the values or keys.
370     ///
371     /// **Known problems:** None.
372     ///
373     /// **Example:**
374     /// ```ignore
375     /// for (k, _) in &map {
376     ///     ..
377     /// }
378     /// ```
379     ///
380     /// could be replaced by
381     ///
382     /// ```ignore
383     /// for k in map.keys() {
384     ///     ..
385     /// }
386     /// ```
387     pub FOR_KV_MAP,
388     style,
389     "looping on a map using `iter` when `keys` or `values` would do"
390 }
391
392 declare_clippy_lint! {
393     /// **What it does:** Checks for loops that will always `break`, `return` or
394     /// `continue` an outer loop.
395     ///
396     /// **Why is this bad?** This loop never loops, all it does is obfuscating the
397     /// code.
398     ///
399     /// **Known problems:** None
400     ///
401     /// **Example:**
402     /// ```rust
403     /// loop {
404     ///     ..;
405     ///     break;
406     /// }
407     /// ```
408     pub NEVER_LOOP,
409     correctness,
410     "any loop that will always `break` or `return`"
411 }
412
413 declare_clippy_lint! {
414     /// **What it does:** Checks for loops which have a range bound that is a mutable variable
415     ///
416     /// **Why is this bad?** One might think that modifying the mutable variable changes the loop bounds
417     ///
418     /// **Known problems:** None
419     ///
420     /// **Example:**
421     /// ```rust
422     /// let mut foo = 42;
423     /// for i in 0..foo {
424     ///     foo -= 1;
425     ///     println!("{}", i); // prints numbers from 0 to 42, not 0 to 21
426     /// }
427     /// ```
428     pub MUT_RANGE_BOUND,
429     complexity,
430     "for loop over a range where one of the bounds is a mutable variable"
431 }
432
433 declare_clippy_lint! {
434     /// **What it does:** Checks whether variables used within while loop condition
435     /// can be (and are) mutated in the body.
436     ///
437     /// **Why is this bad?** If the condition is unchanged, entering the body of the loop
438     /// will lead to an infinite loop.
439     ///
440     /// **Known problems:** If the `while`-loop is in a closure, the check for mutation of the
441     /// condition variables in the body can cause false negatives. For example when only `Upvar` `a` is
442     /// in the condition and only `Upvar` `b` gets mutated in the body, the lint will not trigger.
443     ///
444     /// **Example:**
445     /// ```rust
446     /// let i = 0;
447     /// while i > 10 {
448     ///     println!("let me loop forever!");
449     /// }
450     /// ```
451     pub WHILE_IMMUTABLE_CONDITION,
452     correctness,
453     "variables used within while expression are not mutated in the body"
454 }
455
456 declare_lint_pass!(Loops => [
457     MANUAL_MEMCPY,
458     NEEDLESS_RANGE_LOOP,
459     EXPLICIT_ITER_LOOP,
460     EXPLICIT_INTO_ITER_LOOP,
461     ITER_NEXT_LOOP,
462     FOR_LOOP_OVER_RESULT,
463     FOR_LOOP_OVER_OPTION,
464     WHILE_LET_LOOP,
465     NEEDLESS_COLLECT,
466     REVERSE_RANGE_LOOP,
467     EXPLICIT_COUNTER_LOOP,
468     EMPTY_LOOP,
469     WHILE_LET_ON_ITERATOR,
470     FOR_KV_MAP,
471     NEVER_LOOP,
472     MUT_RANGE_BOUND,
473     WHILE_IMMUTABLE_CONDITION,
474 ]);
475
476 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Loops {
477     #[allow(clippy::too_many_lines)]
478     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'_>) {
479         if let Some((pat, arg, body)) = higher::for_loop(expr) {
480             // we don't want to check expanded macros
481             // this check is not at the top of the function
482             // since higher::for_loop expressions are marked as expansions
483             if body.span.from_expansion() {
484                 return;
485             }
486             check_for_loop(cx, pat, arg, body, expr);
487         }
488
489         // we don't want to check expanded macros
490         if expr.span.from_expansion() {
491             return;
492         }
493
494         // check for never_loop
495         if let ExprKind::Loop(ref block, _, _) = expr.kind {
496             match never_loop_block(block, expr.hir_id) {
497                 NeverLoopResult::AlwaysBreak => span_lint(cx, NEVER_LOOP, expr.span, "this loop never actually loops"),
498                 NeverLoopResult::MayContinueMainLoop | NeverLoopResult::Otherwise => (),
499             }
500         }
501
502         // check for `loop { if let {} else break }` that could be `while let`
503         // (also matches an explicit "match" instead of "if let")
504         // (even if the "match" or "if let" is used for declaration)
505         if let ExprKind::Loop(ref block, _, LoopSource::Loop) = expr.kind {
506             // also check for empty `loop {}` statements
507             if block.stmts.is_empty() && block.expr.is_none() && !is_no_std_crate(cx.tcx.hir().krate()) {
508                 span_lint(
509                     cx,
510                     EMPTY_LOOP,
511                     expr.span,
512                     "empty `loop {}` detected. You may want to either use `panic!()` or add \
513                      `std::thread::sleep(..);` to the loop body.",
514                 );
515             }
516
517             // extract the expression from the first statement (if any) in a block
518             let inner_stmt_expr = extract_expr_from_first_stmt(block);
519             // or extract the first expression (if any) from the block
520             if let Some(inner) = inner_stmt_expr.or_else(|| extract_first_expr(block)) {
521                 if let ExprKind::Match(ref matchexpr, ref arms, ref source) = inner.kind {
522                     // ensure "if let" compatible match structure
523                     match *source {
524                         MatchSource::Normal | MatchSource::IfLetDesugar { .. } => {
525                             if arms.len() == 2
526                                 && arms[0].guard.is_none()
527                                 && arms[1].guard.is_none()
528                                 && is_simple_break_expr(&arms[1].body)
529                             {
530                                 if in_external_macro(cx.sess(), expr.span) {
531                                     return;
532                                 }
533
534                                 // NOTE: we used to build a body here instead of using
535                                 // ellipsis, this was removed because:
536                                 // 1) it was ugly with big bodies;
537                                 // 2) it was not indented properly;
538                                 // 3) it wasn’t very smart (see #675).
539                                 let mut applicability = Applicability::HasPlaceholders;
540                                 span_lint_and_sugg(
541                                     cx,
542                                     WHILE_LET_LOOP,
543                                     expr.span,
544                                     "this loop could be written as a `while let` loop",
545                                     "try",
546                                     format!(
547                                         "while let {} = {} {{ .. }}",
548                                         snippet_with_applicability(cx, arms[0].pat.span, "..", &mut applicability),
549                                         snippet_with_applicability(cx, matchexpr.span, "..", &mut applicability),
550                                     ),
551                                     applicability,
552                                 );
553                             }
554                         },
555                         _ => (),
556                     }
557                 }
558             }
559         }
560         if let ExprKind::Match(ref match_expr, ref arms, MatchSource::WhileLetDesugar) = expr.kind {
561             let pat = &arms[0].pat.kind;
562             if let (
563                 &PatKind::TupleStruct(ref qpath, ref pat_args, _),
564                 &ExprKind::MethodCall(ref method_path, _, ref method_args),
565             ) = (pat, &match_expr.kind)
566             {
567                 let iter_expr = &method_args[0];
568
569                 // Don't lint when the iterator is recreated on every iteration
570                 if_chain! {
571                     if let ExprKind::MethodCall(..) | ExprKind::Call(..) = iter_expr.kind;
572                     if let Some(iter_def_id) = get_trait_def_id(cx, &paths::ITERATOR);
573                     if implements_trait(cx, cx.tables.expr_ty(iter_expr), iter_def_id, &[]);
574                     then {
575                         return;
576                     }
577                 }
578
579                 let lhs_constructor = last_path_segment(qpath);
580                 if method_path.ident.name == sym!(next)
581                     && match_trait_method(cx, match_expr, &paths::ITERATOR)
582                     && lhs_constructor.ident.name == sym!(Some)
583                     && (pat_args.is_empty()
584                         || !is_refutable(cx, &pat_args[0])
585                             && !is_used_inside(cx, iter_expr, &arms[0].body)
586                             && !is_iterator_used_after_while_let(cx, iter_expr)
587                             && !is_nested(cx, expr, &method_args[0]))
588                 {
589                     let mut applicability = Applicability::MachineApplicable;
590                     let iterator = snippet_with_applicability(cx, method_args[0].span, "_", &mut applicability);
591                     let loop_var = if pat_args.is_empty() {
592                         "_".to_string()
593                     } else {
594                         snippet_with_applicability(cx, pat_args[0].span, "_", &mut applicability).into_owned()
595                     };
596                     span_lint_and_sugg(
597                         cx,
598                         WHILE_LET_ON_ITERATOR,
599                         expr.span.with_hi(match_expr.span.hi()),
600                         "this loop could be written as a `for` loop",
601                         "try",
602                         format!("for {} in {}", loop_var, iterator),
603                         applicability,
604                     );
605                 }
606             }
607         }
608
609         if let Some((cond, body)) = higher::while_loop(&expr) {
610             check_infinite_loop(cx, cond, body);
611         }
612
613         check_needless_collect(expr, cx);
614     }
615 }
616
617 enum NeverLoopResult {
618     // A break/return always get triggered but not necessarily for the main loop.
619     AlwaysBreak,
620     // A continue may occur for the main loop.
621     MayContinueMainLoop,
622     Otherwise,
623 }
624
625 #[must_use]
626 fn absorb_break(arg: &NeverLoopResult) -> NeverLoopResult {
627     match *arg {
628         NeverLoopResult::AlwaysBreak | NeverLoopResult::Otherwise => NeverLoopResult::Otherwise,
629         NeverLoopResult::MayContinueMainLoop => NeverLoopResult::MayContinueMainLoop,
630     }
631 }
632
633 // Combine two results for parts that are called in order.
634 #[must_use]
635 fn combine_seq(first: NeverLoopResult, second: NeverLoopResult) -> NeverLoopResult {
636     match first {
637         NeverLoopResult::AlwaysBreak | NeverLoopResult::MayContinueMainLoop => first,
638         NeverLoopResult::Otherwise => second,
639     }
640 }
641
642 // Combine two results where both parts are called but not necessarily in order.
643 #[must_use]
644 fn combine_both(left: NeverLoopResult, right: NeverLoopResult) -> NeverLoopResult {
645     match (left, right) {
646         (NeverLoopResult::MayContinueMainLoop, _) | (_, NeverLoopResult::MayContinueMainLoop) => {
647             NeverLoopResult::MayContinueMainLoop
648         },
649         (NeverLoopResult::AlwaysBreak, _) | (_, NeverLoopResult::AlwaysBreak) => NeverLoopResult::AlwaysBreak,
650         (NeverLoopResult::Otherwise, NeverLoopResult::Otherwise) => NeverLoopResult::Otherwise,
651     }
652 }
653
654 // Combine two results where only one of the part may have been executed.
655 #[must_use]
656 fn combine_branches(b1: NeverLoopResult, b2: NeverLoopResult) -> NeverLoopResult {
657     match (b1, b2) {
658         (NeverLoopResult::AlwaysBreak, NeverLoopResult::AlwaysBreak) => NeverLoopResult::AlwaysBreak,
659         (NeverLoopResult::MayContinueMainLoop, _) | (_, NeverLoopResult::MayContinueMainLoop) => {
660             NeverLoopResult::MayContinueMainLoop
661         },
662         (NeverLoopResult::Otherwise, _) | (_, NeverLoopResult::Otherwise) => NeverLoopResult::Otherwise,
663     }
664 }
665
666 fn never_loop_block(block: &Block<'_>, main_loop_id: HirId) -> NeverLoopResult {
667     let stmts = block.stmts.iter().map(stmt_to_expr);
668     let expr = once(block.expr.as_deref());
669     let mut iter = stmts.chain(expr).filter_map(|e| e);
670     never_loop_expr_seq(&mut iter, main_loop_id)
671 }
672
673 fn stmt_to_expr<'tcx>(stmt: &Stmt<'tcx>) -> Option<&'tcx Expr<'tcx>> {
674     match stmt.kind {
675         StmtKind::Semi(ref e, ..) | StmtKind::Expr(ref e, ..) => Some(e),
676         StmtKind::Local(ref local) => local.init.as_deref(),
677         _ => None,
678     }
679 }
680
681 fn never_loop_expr(expr: &Expr<'_>, main_loop_id: HirId) -> NeverLoopResult {
682     match expr.kind {
683         ExprKind::Box(ref e)
684         | ExprKind::Unary(_, ref e)
685         | ExprKind::Cast(ref e, _)
686         | ExprKind::Type(ref e, _)
687         | ExprKind::Field(ref e, _)
688         | ExprKind::AddrOf(_, _, ref e)
689         | ExprKind::Struct(_, _, Some(ref e))
690         | ExprKind::Repeat(ref e, _)
691         | ExprKind::DropTemps(ref e) => never_loop_expr(e, main_loop_id),
692         ExprKind::Array(ref es) | ExprKind::MethodCall(_, _, ref es) | ExprKind::Tup(ref es) => {
693             never_loop_expr_all(&mut es.iter(), main_loop_id)
694         },
695         ExprKind::Call(ref e, ref es) => never_loop_expr_all(&mut once(&**e).chain(es.iter()), main_loop_id),
696         ExprKind::Binary(_, ref e1, ref e2)
697         | ExprKind::Assign(ref e1, ref e2, _)
698         | ExprKind::AssignOp(_, ref e1, ref e2)
699         | ExprKind::Index(ref e1, ref e2) => never_loop_expr_all(&mut [&**e1, &**e2].iter().cloned(), main_loop_id),
700         ExprKind::Loop(ref b, _, _) => {
701             // Break can come from the inner loop so remove them.
702             absorb_break(&never_loop_block(b, main_loop_id))
703         },
704         ExprKind::Match(ref e, ref arms, _) => {
705             let e = never_loop_expr(e, main_loop_id);
706             if arms.is_empty() {
707                 e
708             } else {
709                 let arms = never_loop_expr_branch(&mut arms.iter().map(|a| &*a.body), main_loop_id);
710                 combine_seq(e, arms)
711             }
712         },
713         ExprKind::Block(ref b, _) => never_loop_block(b, main_loop_id),
714         ExprKind::Continue(d) => {
715             let id = d
716                 .target_id
717                 .expect("target ID can only be missing in the presence of compilation errors");
718             if id == main_loop_id {
719                 NeverLoopResult::MayContinueMainLoop
720             } else {
721                 NeverLoopResult::AlwaysBreak
722             }
723         },
724         ExprKind::Break(_, ref e) | ExprKind::Ret(ref e) => {
725             if let Some(ref e) = *e {
726                 combine_seq(never_loop_expr(e, main_loop_id), NeverLoopResult::AlwaysBreak)
727             } else {
728                 NeverLoopResult::AlwaysBreak
729             }
730         },
731         ExprKind::Struct(_, _, None)
732         | ExprKind::Yield(_, _)
733         | ExprKind::Closure(_, _, _, _, _)
734         | ExprKind::LlvmInlineAsm(_)
735         | ExprKind::Path(_)
736         | ExprKind::Lit(_)
737         | ExprKind::Err => NeverLoopResult::Otherwise,
738     }
739 }
740
741 fn never_loop_expr_seq<'a, T: Iterator<Item = &'a Expr<'a>>>(es: &mut T, main_loop_id: HirId) -> NeverLoopResult {
742     es.map(|e| never_loop_expr(e, main_loop_id))
743         .fold(NeverLoopResult::Otherwise, combine_seq)
744 }
745
746 fn never_loop_expr_all<'a, T: Iterator<Item = &'a Expr<'a>>>(es: &mut T, main_loop_id: HirId) -> NeverLoopResult {
747     es.map(|e| never_loop_expr(e, main_loop_id))
748         .fold(NeverLoopResult::Otherwise, combine_both)
749 }
750
751 fn never_loop_expr_branch<'a, T: Iterator<Item = &'a Expr<'a>>>(e: &mut T, main_loop_id: HirId) -> NeverLoopResult {
752     e.map(|e| never_loop_expr(e, main_loop_id))
753         .fold(NeverLoopResult::AlwaysBreak, combine_branches)
754 }
755
756 fn check_for_loop<'a, 'tcx>(
757     cx: &LateContext<'a, 'tcx>,
758     pat: &'tcx Pat<'_>,
759     arg: &'tcx Expr<'_>,
760     body: &'tcx Expr<'_>,
761     expr: &'tcx Expr<'_>,
762 ) {
763     check_for_loop_range(cx, pat, arg, body, expr);
764     check_for_loop_reverse_range(cx, arg, expr);
765     check_for_loop_arg(cx, pat, arg, expr);
766     check_for_loop_explicit_counter(cx, pat, arg, body, expr);
767     check_for_loop_over_map_kv(cx, pat, arg, body, expr);
768     check_for_mut_range_bound(cx, arg, body);
769     detect_manual_memcpy(cx, pat, arg, body, expr);
770 }
771
772 fn same_var<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &Expr<'_>, var: HirId) -> bool {
773     if_chain! {
774         if let ExprKind::Path(qpath) = &expr.kind;
775         if let QPath::Resolved(None, path) = qpath;
776         if path.segments.len() == 1;
777         if let Res::Local(local_id) = qpath_res(cx, qpath, expr.hir_id);
778         // our variable!
779         if local_id == var;
780         then {
781             true
782         } else {
783             false
784         }
785     }
786 }
787
788 #[derive(Clone, Copy)]
789 enum OffsetSign {
790     Positive,
791     Negative,
792 }
793
794 struct Offset {
795     value: String,
796     sign: OffsetSign,
797 }
798
799 impl Offset {
800     fn negative(value: String) -> Self {
801         Self {
802             value,
803             sign: OffsetSign::Negative,
804         }
805     }
806
807     fn positive(value: String) -> Self {
808         Self {
809             value,
810             sign: OffsetSign::Positive,
811         }
812     }
813 }
814
815 struct FixedOffsetVar<'hir> {
816     var: &'hir Expr<'hir>,
817     offset: Offset,
818 }
819
820 fn is_slice_like<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, ty: Ty<'_>) -> bool {
821     let is_slice = match ty.kind {
822         ty::Ref(_, subty, _) => is_slice_like(cx, subty),
823         ty::Slice(..) | ty::Array(..) => true,
824         _ => false,
825     };
826
827     is_slice || is_type_diagnostic_item(cx, ty, sym!(vec_type)) || is_type_diagnostic_item(cx, ty, sym!(vecdeque_type))
828 }
829
830 fn fetch_cloned_expr<'tcx>(expr: &'tcx Expr<'tcx>) -> &'tcx Expr<'tcx> {
831     if_chain! {
832         if let ExprKind::MethodCall(method, _, args) = expr.kind;
833         if method.ident.name == sym!(clone);
834         if args.len() == 1;
835         if let Some(arg) = args.get(0);
836         then { arg } else { expr }
837     }
838 }
839
840 fn get_offset<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, idx: &Expr<'_>, var: HirId) -> Option<Offset> {
841     fn extract_offset<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, e: &Expr<'_>, var: HirId) -> Option<String> {
842         match &e.kind {
843             ExprKind::Lit(l) => match l.node {
844                 ast::LitKind::Int(x, _ty) => Some(x.to_string()),
845                 _ => None,
846             },
847             ExprKind::Path(..) if !same_var(cx, e, var) => Some(snippet_opt(cx, e.span).unwrap_or_else(|| "??".into())),
848             _ => None,
849         }
850     }
851
852     match idx.kind {
853         ExprKind::Binary(op, lhs, rhs) => match op.node {
854             BinOpKind::Add => {
855                 let offset_opt = if same_var(cx, lhs, var) {
856                     extract_offset(cx, rhs, var)
857                 } else if same_var(cx, rhs, var) {
858                     extract_offset(cx, lhs, var)
859                 } else {
860                     None
861                 };
862
863                 offset_opt.map(Offset::positive)
864             },
865             BinOpKind::Sub if same_var(cx, lhs, var) => extract_offset(cx, rhs, var).map(Offset::negative),
866             _ => None,
867         },
868         ExprKind::Path(..) if same_var(cx, idx, var) => Some(Offset::positive("0".into())),
869         _ => None,
870     }
871 }
872
873 fn get_assignments<'a, 'tcx>(
874     body: &'tcx Expr<'tcx>,
875 ) -> impl Iterator<Item = Option<(&'tcx Expr<'tcx>, &'tcx Expr<'tcx>)>> {
876     fn get_assignment<'a, 'tcx>(e: &'tcx Expr<'tcx>) -> Option<(&'tcx Expr<'tcx>, &'tcx Expr<'tcx>)> {
877         if let ExprKind::Assign(lhs, rhs, _) = e.kind {
878             Some((lhs, rhs))
879         } else {
880             None
881         }
882     }
883
884     // This is one of few ways to return different iterators
885     // derived from: https://stackoverflow.com/questions/29760668/conditionally-iterate-over-one-of-several-possible-iterators/52064434#52064434
886     let mut iter_a = None;
887     let mut iter_b = None;
888
889     if let ExprKind::Block(b, _) = body.kind {
890         let Block { stmts, expr, .. } = *b;
891
892         iter_a = stmts
893             .iter()
894             .filter_map(|stmt| match stmt.kind {
895                 StmtKind::Local(..) | StmtKind::Item(..) => None,
896                 StmtKind::Expr(e) | StmtKind::Semi(e) => Some(e),
897             })
898             .chain(expr.into_iter())
899             .map(get_assignment)
900             .into()
901     } else {
902         iter_b = Some(get_assignment(body))
903     }
904
905     iter_a.into_iter().flatten().chain(iter_b.into_iter())
906 }
907
908 fn build_manual_memcpy_suggestion<'a, 'tcx>(
909     cx: &LateContext<'a, 'tcx>,
910     start: &Expr<'_>,
911     end: &Expr<'_>,
912     limits: ast::RangeLimits,
913     dst_var: FixedOffsetVar<'_>,
914     src_var: FixedOffsetVar<'_>,
915 ) -> String {
916     fn print_sum(arg1: &str, arg2: &Offset) -> String {
917         match (arg1, &arg2.value[..], arg2.sign) {
918             ("0", "0", _) => "0".into(),
919             ("0", x, OffsetSign::Positive) | (x, "0", _) => x.into(),
920             ("0", x, OffsetSign::Negative) => format!("-{}", x),
921             (x, y, OffsetSign::Positive) => format!("({} + {})", x, y),
922             (x, y, OffsetSign::Negative) => {
923                 if x == y {
924                     "0".into()
925                 } else {
926                     format!("({} - {})", x, y)
927                 }
928             },
929         }
930     }
931
932     fn print_offset(start_str: &str, inline_offset: &Offset) -> String {
933         let offset = print_sum(start_str, inline_offset);
934         if offset.as_str() == "0" {
935             "".into()
936         } else {
937             offset
938         }
939     }
940
941     let print_limit = |end: &Expr<'_>, offset: Offset, var: &Expr<'_>| {
942         if_chain! {
943             if let ExprKind::MethodCall(method, _, len_args) = end.kind;
944             if method.ident.name == sym!(len);
945             if len_args.len() == 1;
946             if let Some(arg) = len_args.get(0);
947             if var_def_id(cx, arg) == var_def_id(cx, var);
948             then {
949                 match offset.sign {
950                     OffsetSign::Negative => format!("({} - {})", snippet(cx, end.span, "<src>.len()"), offset.value),
951                     OffsetSign::Positive => "".into(),
952                 }
953             } else {
954                 let end_str = match limits {
955                     ast::RangeLimits::Closed => {
956                         let end = sugg::Sugg::hir(cx, end, "<count>");
957                         format!("{}", end + sugg::ONE)
958                     },
959                     ast::RangeLimits::HalfOpen => format!("{}", snippet(cx, end.span, "..")),
960                 };
961
962                 print_sum(&end_str, &offset)
963             }
964         }
965     };
966
967     let start_str = snippet(cx, start.span, "").to_string();
968     let dst_offset = print_offset(&start_str, &dst_var.offset);
969     let dst_limit = print_limit(end, dst_var.offset, dst_var.var);
970     let src_offset = print_offset(&start_str, &src_var.offset);
971     let src_limit = print_limit(end, src_var.offset, src_var.var);
972
973     let dst_var_name = snippet_opt(cx, dst_var.var.span).unwrap_or_else(|| "???".into());
974     let src_var_name = snippet_opt(cx, src_var.var.span).unwrap_or_else(|| "???".into());
975
976     let dst = if dst_offset == "" && dst_limit == "" {
977         dst_var_name
978     } else {
979         format!("{}[{}..{}]", dst_var_name, dst_offset, dst_limit)
980     };
981
982     format!(
983         "{}.clone_from_slice(&{}[{}..{}])",
984         dst, src_var_name, src_offset, src_limit
985     )
986 }
987 /// Checks for for loops that sequentially copy items from one slice-like
988 /// object to another.
989 fn detect_manual_memcpy<'a, 'tcx>(
990     cx: &LateContext<'a, 'tcx>,
991     pat: &'tcx Pat<'_>,
992     arg: &'tcx Expr<'_>,
993     body: &'tcx Expr<'_>,
994     expr: &'tcx Expr<'_>,
995 ) {
996     if let Some(higher::Range {
997         start: Some(start),
998         end: Some(end),
999         limits,
1000     }) = higher::range(cx, arg)
1001     {
1002         // the var must be a single name
1003         if let PatKind::Binding(_, canonical_id, _, _) = pat.kind {
1004             // The only statements in the for loops can be indexed assignments from
1005             // indexed retrievals.
1006             let big_sugg = get_assignments(body)
1007                 .map(|o| {
1008                     o.and_then(|(lhs, rhs)| {
1009                         let rhs = fetch_cloned_expr(rhs);
1010                         if_chain! {
1011                             if let ExprKind::Index(seqexpr_left, idx_left) = lhs.kind;
1012                             if let ExprKind::Index(seqexpr_right, idx_right) = rhs.kind;
1013                             if is_slice_like(cx, cx.tables.expr_ty(seqexpr_left))
1014                                 && is_slice_like(cx, cx.tables.expr_ty(seqexpr_right));
1015                             if let Some(offset_left) = get_offset(cx, &idx_left, canonical_id);
1016                             if let Some(offset_right) = get_offset(cx, &idx_right, canonical_id);
1017
1018                             // Source and destination must be different
1019                             if var_def_id(cx, seqexpr_left) != var_def_id(cx, seqexpr_right);
1020                             then {
1021                                 Some((FixedOffsetVar { var: seqexpr_left, offset: offset_left },
1022                                     FixedOffsetVar { var: seqexpr_right, offset: offset_right }))
1023                             } else {
1024                                 None
1025                             }
1026                         }
1027                     })
1028                 })
1029                 .map(|o| o.map(|(dst, src)| build_manual_memcpy_suggestion(cx, start, end, limits, dst, src)))
1030                 .collect::<Option<Vec<_>>>()
1031                 .filter(|v| !v.is_empty())
1032                 .map(|v| v.join("\n    "));
1033
1034             if let Some(big_sugg) = big_sugg {
1035                 span_lint_and_sugg(
1036                     cx,
1037                     MANUAL_MEMCPY,
1038                     expr.span,
1039                     "it looks like you're manually copying between slices",
1040                     "try replacing the loop by",
1041                     big_sugg,
1042                     Applicability::Unspecified,
1043                 );
1044             }
1045         }
1046     }
1047 }
1048
1049 /// Checks for looping over a range and then indexing a sequence with it.
1050 /// The iteratee must be a range literal.
1051 #[allow(clippy::too_many_lines)]
1052 fn check_for_loop_range<'a, 'tcx>(
1053     cx: &LateContext<'a, 'tcx>,
1054     pat: &'tcx Pat<'_>,
1055     arg: &'tcx Expr<'_>,
1056     body: &'tcx Expr<'_>,
1057     expr: &'tcx Expr<'_>,
1058 ) {
1059     if let Some(higher::Range {
1060         start: Some(start),
1061         ref end,
1062         limits,
1063     }) = higher::range(cx, arg)
1064     {
1065         // the var must be a single name
1066         if let PatKind::Binding(_, canonical_id, ident, _) = pat.kind {
1067             let mut visitor = VarVisitor {
1068                 cx,
1069                 var: canonical_id,
1070                 indexed_mut: FxHashSet::default(),
1071                 indexed_indirectly: FxHashMap::default(),
1072                 indexed_directly: FxHashMap::default(),
1073                 referenced: FxHashSet::default(),
1074                 nonindex: false,
1075                 prefer_mutable: false,
1076             };
1077             walk_expr(&mut visitor, body);
1078
1079             // linting condition: we only indexed one variable, and indexed it directly
1080             if visitor.indexed_indirectly.is_empty() && visitor.indexed_directly.len() == 1 {
1081                 let (indexed, (indexed_extent, indexed_ty)) = visitor
1082                     .indexed_directly
1083                     .into_iter()
1084                     .next()
1085                     .expect("already checked that we have exactly 1 element");
1086
1087                 // ensure that the indexed variable was declared before the loop, see #601
1088                 if let Some(indexed_extent) = indexed_extent {
1089                     let parent_id = cx.tcx.hir().get_parent_item(expr.hir_id);
1090                     let parent_def_id = cx.tcx.hir().local_def_id(parent_id);
1091                     let region_scope_tree = cx.tcx.region_scope_tree(parent_def_id);
1092                     let pat_extent = region_scope_tree.var_scope(pat.hir_id.local_id);
1093                     if region_scope_tree.is_subscope_of(indexed_extent, pat_extent) {
1094                         return;
1095                     }
1096                 }
1097
1098                 // don't lint if the container that is indexed does not have .iter() method
1099                 let has_iter = has_iter_method(cx, indexed_ty);
1100                 if has_iter.is_none() {
1101                     return;
1102                 }
1103
1104                 // don't lint if the container that is indexed into is also used without
1105                 // indexing
1106                 if visitor.referenced.contains(&indexed) {
1107                     return;
1108                 }
1109
1110                 let starts_at_zero = is_integer_const(cx, start, 0);
1111
1112                 let skip = if starts_at_zero {
1113                     String::new()
1114                 } else {
1115                     format!(".skip({})", snippet(cx, start.span, ".."))
1116                 };
1117
1118                 let mut end_is_start_plus_val = false;
1119
1120                 let take = if let Some(end) = *end {
1121                     let mut take_expr = end;
1122
1123                     if let ExprKind::Binary(ref op, ref left, ref right) = end.kind {
1124                         if let BinOpKind::Add = op.node {
1125                             let start_equal_left = SpanlessEq::new(cx).eq_expr(start, left);
1126                             let start_equal_right = SpanlessEq::new(cx).eq_expr(start, right);
1127
1128                             if start_equal_left {
1129                                 take_expr = right;
1130                             } else if start_equal_right {
1131                                 take_expr = left;
1132                             }
1133
1134                             end_is_start_plus_val = start_equal_left | start_equal_right;
1135                         }
1136                     }
1137
1138                     if is_len_call(end, indexed) || is_end_eq_array_len(cx, end, limits, indexed_ty) {
1139                         String::new()
1140                     } else {
1141                         match limits {
1142                             ast::RangeLimits::Closed => {
1143                                 let take_expr = sugg::Sugg::hir(cx, take_expr, "<count>");
1144                                 format!(".take({})", take_expr + sugg::ONE)
1145                             },
1146                             ast::RangeLimits::HalfOpen => format!(".take({})", snippet(cx, take_expr.span, "..")),
1147                         }
1148                     }
1149                 } else {
1150                     String::new()
1151                 };
1152
1153                 let (ref_mut, method) = if visitor.indexed_mut.contains(&indexed) {
1154                     ("mut ", "iter_mut")
1155                 } else {
1156                     ("", "iter")
1157                 };
1158
1159                 let take_is_empty = take.is_empty();
1160                 let mut method_1 = take;
1161                 let mut method_2 = skip;
1162
1163                 if end_is_start_plus_val {
1164                     mem::swap(&mut method_1, &mut method_2);
1165                 }
1166
1167                 if visitor.nonindex {
1168                     span_lint_and_then(
1169                         cx,
1170                         NEEDLESS_RANGE_LOOP,
1171                         expr.span,
1172                         &format!("the loop variable `{}` is used to index `{}`", ident.name, indexed),
1173                         |diag| {
1174                             multispan_sugg(
1175                                 diag,
1176                                 "consider using an iterator".to_string(),
1177                                 vec![
1178                                     (pat.span, format!("({}, <item>)", ident.name)),
1179                                     (
1180                                         arg.span,
1181                                         format!("{}.{}().enumerate(){}{}", indexed, method, method_1, method_2),
1182                                     ),
1183                                 ],
1184                             );
1185                         },
1186                     );
1187                 } else {
1188                     let repl = if starts_at_zero && take_is_empty {
1189                         format!("&{}{}", ref_mut, indexed)
1190                     } else {
1191                         format!("{}.{}(){}{}", indexed, method, method_1, method_2)
1192                     };
1193
1194                     span_lint_and_then(
1195                         cx,
1196                         NEEDLESS_RANGE_LOOP,
1197                         expr.span,
1198                         &format!(
1199                             "the loop variable `{}` is only used to index `{}`.",
1200                             ident.name, indexed
1201                         ),
1202                         |diag| {
1203                             multispan_sugg(
1204                                 diag,
1205                                 "consider using an iterator".to_string(),
1206                                 vec![(pat.span, "<item>".to_string()), (arg.span, repl)],
1207                             );
1208                         },
1209                     );
1210                 }
1211             }
1212         }
1213     }
1214 }
1215
1216 fn is_len_call(expr: &Expr<'_>, var: Name) -> bool {
1217     if_chain! {
1218         if let ExprKind::MethodCall(ref method, _, ref len_args) = expr.kind;
1219         if len_args.len() == 1;
1220         if method.ident.name == sym!(len);
1221         if let ExprKind::Path(QPath::Resolved(_, ref path)) = len_args[0].kind;
1222         if path.segments.len() == 1;
1223         if path.segments[0].ident.name == var;
1224         then {
1225             return true;
1226         }
1227     }
1228
1229     false
1230 }
1231
1232 fn is_end_eq_array_len<'tcx>(
1233     cx: &LateContext<'_, 'tcx>,
1234     end: &Expr<'_>,
1235     limits: ast::RangeLimits,
1236     indexed_ty: Ty<'tcx>,
1237 ) -> bool {
1238     if_chain! {
1239         if let ExprKind::Lit(ref lit) = end.kind;
1240         if let ast::LitKind::Int(end_int, _) = lit.node;
1241         if let ty::Array(_, arr_len_const) = indexed_ty.kind;
1242         if let Some(arr_len) = arr_len_const.try_eval_usize(cx.tcx, cx.param_env);
1243         then {
1244             return match limits {
1245                 ast::RangeLimits::Closed => end_int + 1 >= arr_len.into(),
1246                 ast::RangeLimits::HalfOpen => end_int >= arr_len.into(),
1247             };
1248         }
1249     }
1250
1251     false
1252 }
1253
1254 fn check_for_loop_reverse_range<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, arg: &'tcx Expr<'_>, expr: &'tcx Expr<'_>) {
1255     // if this for loop is iterating over a two-sided range...
1256     if let Some(higher::Range {
1257         start: Some(start),
1258         end: Some(end),
1259         limits,
1260     }) = higher::range(cx, arg)
1261     {
1262         // ...and both sides are compile-time constant integers...
1263         if let Some((start_idx, _)) = constant(cx, cx.tables, start) {
1264             if let Some((end_idx, _)) = constant(cx, cx.tables, end) {
1265                 // ...and the start index is greater than the end index,
1266                 // this loop will never run. This is often confusing for developers
1267                 // who think that this will iterate from the larger value to the
1268                 // smaller value.
1269                 let ty = cx.tables.expr_ty(start);
1270                 let (sup, eq) = match (start_idx, end_idx) {
1271                     (Constant::Int(start_idx), Constant::Int(end_idx)) => (
1272                         match ty.kind {
1273                             ty::Int(ity) => sext(cx.tcx, start_idx, ity) > sext(cx.tcx, end_idx, ity),
1274                             ty::Uint(_) => start_idx > end_idx,
1275                             _ => false,
1276                         },
1277                         start_idx == end_idx,
1278                     ),
1279                     _ => (false, false),
1280                 };
1281
1282                 if sup {
1283                     let start_snippet = snippet(cx, start.span, "_");
1284                     let end_snippet = snippet(cx, end.span, "_");
1285                     let dots = if limits == ast::RangeLimits::Closed {
1286                         "..="
1287                     } else {
1288                         ".."
1289                     };
1290
1291                     span_lint_and_then(
1292                         cx,
1293                         REVERSE_RANGE_LOOP,
1294                         expr.span,
1295                         "this range is empty so this for loop will never run",
1296                         |diag| {
1297                             diag.span_suggestion(
1298                                 arg.span,
1299                                 "consider using the following if you are attempting to iterate over this \
1300                                  range in reverse",
1301                                 format!(
1302                                     "({end}{dots}{start}).rev()",
1303                                     end = end_snippet,
1304                                     dots = dots,
1305                                     start = start_snippet
1306                                 ),
1307                                 Applicability::MaybeIncorrect,
1308                             );
1309                         },
1310                     );
1311                 } else if eq && limits != ast::RangeLimits::Closed {
1312                     // if they are equal, it's also problematic - this loop
1313                     // will never run.
1314                     span_lint(
1315                         cx,
1316                         REVERSE_RANGE_LOOP,
1317                         expr.span,
1318                         "this range is empty so this for loop will never run",
1319                     );
1320                 }
1321             }
1322         }
1323     }
1324 }
1325
1326 fn lint_iter_method(cx: &LateContext<'_, '_>, args: &[Expr<'_>], arg: &Expr<'_>, method_name: &str) {
1327     let mut applicability = Applicability::MachineApplicable;
1328     let object = snippet_with_applicability(cx, args[0].span, "_", &mut applicability);
1329     let muta = if method_name == "iter_mut" { "mut " } else { "" };
1330     span_lint_and_sugg(
1331         cx,
1332         EXPLICIT_ITER_LOOP,
1333         arg.span,
1334         "it is more concise to loop over references to containers instead of using explicit \
1335          iteration methods",
1336         "to write this more concisely, try",
1337         format!("&{}{}", muta, object),
1338         applicability,
1339     )
1340 }
1341
1342 fn check_for_loop_arg(cx: &LateContext<'_, '_>, pat: &Pat<'_>, arg: &Expr<'_>, expr: &Expr<'_>) {
1343     let mut next_loop_linted = false; // whether or not ITER_NEXT_LOOP lint was used
1344     if let ExprKind::MethodCall(ref method, _, ref args) = arg.kind {
1345         // just the receiver, no arguments
1346         if args.len() == 1 {
1347             let method_name = &*method.ident.as_str();
1348             // check for looping over x.iter() or x.iter_mut(), could use &x or &mut x
1349             if method_name == "iter" || method_name == "iter_mut" {
1350                 if is_ref_iterable_type(cx, &args[0]) {
1351                     lint_iter_method(cx, args, arg, method_name);
1352                 }
1353             } else if method_name == "into_iter" && match_trait_method(cx, arg, &paths::INTO_ITERATOR) {
1354                 let receiver_ty = cx.tables.expr_ty(&args[0]);
1355                 let receiver_ty_adjusted = cx.tables.expr_ty_adjusted(&args[0]);
1356                 if same_tys(cx, receiver_ty, receiver_ty_adjusted) {
1357                     let mut applicability = Applicability::MachineApplicable;
1358                     let object = snippet_with_applicability(cx, args[0].span, "_", &mut applicability);
1359                     span_lint_and_sugg(
1360                         cx,
1361                         EXPLICIT_INTO_ITER_LOOP,
1362                         arg.span,
1363                         "it is more concise to loop over containers instead of using explicit \
1364                          iteration methods",
1365                         "to write this more concisely, try",
1366                         object.to_string(),
1367                         applicability,
1368                     );
1369                 } else {
1370                     let ref_receiver_ty = cx.tcx.mk_ref(
1371                         cx.tcx.lifetimes.re_erased,
1372                         ty::TypeAndMut {
1373                             ty: receiver_ty,
1374                             mutbl: Mutability::Not,
1375                         },
1376                     );
1377                     if same_tys(cx, receiver_ty_adjusted, ref_receiver_ty) {
1378                         lint_iter_method(cx, args, arg, method_name)
1379                     }
1380                 }
1381             } else if method_name == "next" && match_trait_method(cx, arg, &paths::ITERATOR) {
1382                 span_lint(
1383                     cx,
1384                     ITER_NEXT_LOOP,
1385                     expr.span,
1386                     "you are iterating over `Iterator::next()` which is an Option; this will compile but is \
1387                      probably not what you want",
1388                 );
1389                 next_loop_linted = true;
1390             }
1391         }
1392     }
1393     if !next_loop_linted {
1394         check_arg_type(cx, pat, arg);
1395     }
1396 }
1397
1398 /// Checks for `for` loops over `Option`s and `Result`s.
1399 fn check_arg_type(cx: &LateContext<'_, '_>, pat: &Pat<'_>, arg: &Expr<'_>) {
1400     let ty = cx.tables.expr_ty(arg);
1401     if is_type_diagnostic_item(cx, ty, sym!(option_type)) {
1402         span_lint_and_help(
1403             cx,
1404             FOR_LOOP_OVER_OPTION,
1405             arg.span,
1406             &format!(
1407                 "for loop over `{0}`, which is an `Option`. This is more readably written as an \
1408                  `if let` statement.",
1409                 snippet(cx, arg.span, "_")
1410             ),
1411             None,
1412             &format!(
1413                 "consider replacing `for {0} in {1}` with `if let Some({0}) = {1}`",
1414                 snippet(cx, pat.span, "_"),
1415                 snippet(cx, arg.span, "_")
1416             ),
1417         );
1418     } else if is_type_diagnostic_item(cx, ty, sym!(result_type)) {
1419         span_lint_and_help(
1420             cx,
1421             FOR_LOOP_OVER_RESULT,
1422             arg.span,
1423             &format!(
1424                 "for loop over `{0}`, which is a `Result`. This is more readably written as an \
1425                  `if let` statement.",
1426                 snippet(cx, arg.span, "_")
1427             ),
1428             None,
1429             &format!(
1430                 "consider replacing `for {0} in {1}` with `if let Ok({0}) = {1}`",
1431                 snippet(cx, pat.span, "_"),
1432                 snippet(cx, arg.span, "_")
1433             ),
1434         );
1435     }
1436 }
1437
1438 fn check_for_loop_explicit_counter<'a, 'tcx>(
1439     cx: &LateContext<'a, 'tcx>,
1440     pat: &'tcx Pat<'_>,
1441     arg: &'tcx Expr<'_>,
1442     body: &'tcx Expr<'_>,
1443     expr: &'tcx Expr<'_>,
1444 ) {
1445     // Look for variables that are incremented once per loop iteration.
1446     let mut visitor = IncrementVisitor {
1447         cx,
1448         states: FxHashMap::default(),
1449         depth: 0,
1450         done: false,
1451     };
1452     walk_expr(&mut visitor, body);
1453
1454     // For each candidate, check the parent block to see if
1455     // it's initialized to zero at the start of the loop.
1456     if let Some(block) = get_enclosing_block(&cx, expr.hir_id) {
1457         for (id, _) in visitor.states.iter().filter(|&(_, v)| *v == VarState::IncrOnce) {
1458             let mut visitor2 = InitializeVisitor {
1459                 cx,
1460                 end_expr: expr,
1461                 var_id: *id,
1462                 state: VarState::IncrOnce,
1463                 name: None,
1464                 depth: 0,
1465                 past_loop: false,
1466             };
1467             walk_block(&mut visitor2, block);
1468
1469             if visitor2.state == VarState::Warn {
1470                 if let Some(name) = visitor2.name {
1471                     let mut applicability = Applicability::MachineApplicable;
1472
1473                     // for some reason this is the only way to get the `Span`
1474                     // of the entire `for` loop
1475                     let for_span = if let ExprKind::Match(_, arms, _) = &expr.kind {
1476                         arms[0].body.span
1477                     } else {
1478                         unreachable!()
1479                     };
1480
1481                     span_lint_and_sugg(
1482                         cx,
1483                         EXPLICIT_COUNTER_LOOP,
1484                         for_span.with_hi(arg.span.hi()),
1485                         &format!("the variable `{}` is used as a loop counter.", name),
1486                         "consider using",
1487                         format!(
1488                             "for ({}, {}) in {}.enumerate()",
1489                             name,
1490                             snippet_with_applicability(cx, pat.span, "item", &mut applicability),
1491                             make_iterator_snippet(cx, arg, &mut applicability),
1492                         ),
1493                         applicability,
1494                     );
1495                 }
1496             }
1497         }
1498     }
1499 }
1500
1501 /// If `arg` was the argument to a `for` loop, return the "cleanest" way of writing the
1502 /// actual `Iterator` that the loop uses.
1503 fn make_iterator_snippet(cx: &LateContext<'_, '_>, arg: &Expr<'_>, applic_ref: &mut Applicability) -> String {
1504     let impls_iterator = get_trait_def_id(cx, &paths::ITERATOR)
1505         .map_or(false, |id| implements_trait(cx, cx.tables.expr_ty(arg), id, &[]));
1506     if impls_iterator {
1507         format!(
1508             "{}",
1509             sugg::Sugg::hir_with_applicability(cx, arg, "_", applic_ref).maybe_par()
1510         )
1511     } else {
1512         // (&x).into_iter() ==> x.iter()
1513         // (&mut x).into_iter() ==> x.iter_mut()
1514         match &arg.kind {
1515             ExprKind::AddrOf(BorrowKind::Ref, mutability, arg_inner)
1516                 if has_iter_method(cx, cx.tables.expr_ty(&arg_inner)).is_some() =>
1517             {
1518                 let meth_name = match mutability {
1519                     Mutability::Mut => "iter_mut",
1520                     Mutability::Not => "iter",
1521                 };
1522                 format!(
1523                     "{}.{}()",
1524                     sugg::Sugg::hir_with_applicability(cx, &arg_inner, "_", applic_ref).maybe_par(),
1525                     meth_name,
1526                 )
1527             }
1528             _ => format!(
1529                 "{}.into_iter()",
1530                 sugg::Sugg::hir_with_applicability(cx, arg, "_", applic_ref).maybe_par()
1531             ),
1532         }
1533     }
1534 }
1535
1536 /// Checks for the `FOR_KV_MAP` lint.
1537 fn check_for_loop_over_map_kv<'a, 'tcx>(
1538     cx: &LateContext<'a, 'tcx>,
1539     pat: &'tcx Pat<'_>,
1540     arg: &'tcx Expr<'_>,
1541     body: &'tcx Expr<'_>,
1542     expr: &'tcx Expr<'_>,
1543 ) {
1544     let pat_span = pat.span;
1545
1546     if let PatKind::Tuple(ref pat, _) = pat.kind {
1547         if pat.len() == 2 {
1548             let arg_span = arg.span;
1549             let (new_pat_span, kind, ty, mutbl) = match cx.tables.expr_ty(arg).kind {
1550                 ty::Ref(_, ty, mutbl) => match (&pat[0].kind, &pat[1].kind) {
1551                     (key, _) if pat_is_wild(key, body) => (pat[1].span, "value", ty, mutbl),
1552                     (_, value) if pat_is_wild(value, body) => (pat[0].span, "key", ty, Mutability::Not),
1553                     _ => return,
1554                 },
1555                 _ => return,
1556             };
1557             let mutbl = match mutbl {
1558                 Mutability::Not => "",
1559                 Mutability::Mut => "_mut",
1560             };
1561             let arg = match arg.kind {
1562                 ExprKind::AddrOf(BorrowKind::Ref, _, ref expr) => &**expr,
1563                 _ => arg,
1564             };
1565
1566             if is_type_diagnostic_item(cx, ty, sym!(hashmap_type)) || match_type(cx, ty, &paths::BTREEMAP) {
1567                 span_lint_and_then(
1568                     cx,
1569                     FOR_KV_MAP,
1570                     expr.span,
1571                     &format!("you seem to want to iterate on a map's {}s", kind),
1572                     |diag| {
1573                         let map = sugg::Sugg::hir(cx, arg, "map");
1574                         multispan_sugg(
1575                             diag,
1576                             "use the corresponding method".into(),
1577                             vec![
1578                                 (pat_span, snippet(cx, new_pat_span, kind).into_owned()),
1579                                 (arg_span, format!("{}.{}s{}()", map.maybe_par(), kind, mutbl)),
1580                             ],
1581                         );
1582                     },
1583                 );
1584             }
1585         }
1586     }
1587 }
1588
1589 struct MutatePairDelegate {
1590     hir_id_low: Option<HirId>,
1591     hir_id_high: Option<HirId>,
1592     span_low: Option<Span>,
1593     span_high: Option<Span>,
1594 }
1595
1596 impl<'tcx> Delegate<'tcx> for MutatePairDelegate {
1597     fn consume(&mut self, _: &Place<'tcx>, _: ConsumeMode) {}
1598
1599     fn borrow(&mut self, cmt: &Place<'tcx>, bk: ty::BorrowKind) {
1600         if let ty::BorrowKind::MutBorrow = bk {
1601             if let PlaceBase::Local(id) = cmt.base {
1602                 if Some(id) == self.hir_id_low {
1603                     self.span_low = Some(cmt.span)
1604                 }
1605                 if Some(id) == self.hir_id_high {
1606                     self.span_high = Some(cmt.span)
1607                 }
1608             }
1609         }
1610     }
1611
1612     fn mutate(&mut self, cmt: &Place<'tcx>) {
1613         if let PlaceBase::Local(id) = cmt.base {
1614             if Some(id) == self.hir_id_low {
1615                 self.span_low = Some(cmt.span)
1616             }
1617             if Some(id) == self.hir_id_high {
1618                 self.span_high = Some(cmt.span)
1619             }
1620         }
1621     }
1622 }
1623
1624 impl<'tcx> MutatePairDelegate {
1625     fn mutation_span(&self) -> (Option<Span>, Option<Span>) {
1626         (self.span_low, self.span_high)
1627     }
1628 }
1629
1630 fn check_for_mut_range_bound(cx: &LateContext<'_, '_>, arg: &Expr<'_>, body: &Expr<'_>) {
1631     if let Some(higher::Range {
1632         start: Some(start),
1633         end: Some(end),
1634         ..
1635     }) = higher::range(cx, arg)
1636     {
1637         let mut_ids = vec![check_for_mutability(cx, start), check_for_mutability(cx, end)];
1638         if mut_ids[0].is_some() || mut_ids[1].is_some() {
1639             let (span_low, span_high) = check_for_mutation(cx, body, &mut_ids);
1640             mut_warn_with_span(cx, span_low);
1641             mut_warn_with_span(cx, span_high);
1642         }
1643     }
1644 }
1645
1646 fn mut_warn_with_span(cx: &LateContext<'_, '_>, span: Option<Span>) {
1647     if let Some(sp) = span {
1648         span_lint(
1649             cx,
1650             MUT_RANGE_BOUND,
1651             sp,
1652             "attempt to mutate range bound within loop; note that the range of the loop is unchanged",
1653         );
1654     }
1655 }
1656
1657 fn check_for_mutability(cx: &LateContext<'_, '_>, bound: &Expr<'_>) -> Option<HirId> {
1658     if_chain! {
1659         if let ExprKind::Path(ref qpath) = bound.kind;
1660         if let QPath::Resolved(None, _) = *qpath;
1661         then {
1662             let res = qpath_res(cx, qpath, bound.hir_id);
1663             if let Res::Local(hir_id) = res {
1664                 let node_str = cx.tcx.hir().get(hir_id);
1665                 if_chain! {
1666                     if let Node::Binding(pat) = node_str;
1667                     if let PatKind::Binding(bind_ann, ..) = pat.kind;
1668                     if let BindingAnnotation::Mutable = bind_ann;
1669                     then {
1670                         return Some(hir_id);
1671                     }
1672                 }
1673             }
1674         }
1675     }
1676     None
1677 }
1678
1679 fn check_for_mutation(
1680     cx: &LateContext<'_, '_>,
1681     body: &Expr<'_>,
1682     bound_ids: &[Option<HirId>],
1683 ) -> (Option<Span>, Option<Span>) {
1684     let mut delegate = MutatePairDelegate {
1685         hir_id_low: bound_ids[0],
1686         hir_id_high: bound_ids[1],
1687         span_low: None,
1688         span_high: None,
1689     };
1690     let def_id = body.hir_id.owner.to_def_id();
1691     cx.tcx.infer_ctxt().enter(|infcx| {
1692         ExprUseVisitor::new(&mut delegate, &infcx, def_id, cx.param_env, cx.tables).walk_expr(body);
1693     });
1694     delegate.mutation_span()
1695 }
1696
1697 /// Returns `true` if the pattern is a `PatWild` or an ident prefixed with `_`.
1698 fn pat_is_wild<'tcx>(pat: &'tcx PatKind<'_>, body: &'tcx Expr<'_>) -> bool {
1699     match *pat {
1700         PatKind::Wild => true,
1701         PatKind::Binding(.., ident, None) if ident.as_str().starts_with('_') => is_unused(&ident, body),
1702         _ => false,
1703     }
1704 }
1705
1706 struct LocalUsedVisitor<'a, 'tcx> {
1707     cx: &'a LateContext<'a, 'tcx>,
1708     local: HirId,
1709     used: bool,
1710 }
1711
1712 impl<'a, 'tcx> Visitor<'tcx> for LocalUsedVisitor<'a, 'tcx> {
1713     type Map = Map<'tcx>;
1714
1715     fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
1716         if same_var(self.cx, expr, self.local) {
1717             self.used = true;
1718         } else {
1719             walk_expr(self, expr);
1720         }
1721     }
1722
1723     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
1724         NestedVisitorMap::None
1725     }
1726 }
1727
1728 struct VarVisitor<'a, 'tcx> {
1729     /// context reference
1730     cx: &'a LateContext<'a, 'tcx>,
1731     /// var name to look for as index
1732     var: HirId,
1733     /// indexed variables that are used mutably
1734     indexed_mut: FxHashSet<Name>,
1735     /// indirectly indexed variables (`v[(i + 4) % N]`), the extend is `None` for global
1736     indexed_indirectly: FxHashMap<Name, Option<region::Scope>>,
1737     /// subset of `indexed` of vars that are indexed directly: `v[i]`
1738     /// this will not contain cases like `v[calc_index(i)]` or `v[(i + 4) % N]`
1739     indexed_directly: FxHashMap<Name, (Option<region::Scope>, Ty<'tcx>)>,
1740     /// Any names that are used outside an index operation.
1741     /// Used to detect things like `&mut vec` used together with `vec[i]`
1742     referenced: FxHashSet<Name>,
1743     /// has the loop variable been used in expressions other than the index of
1744     /// an index op?
1745     nonindex: bool,
1746     /// Whether we are inside the `$` in `&mut $` or `$ = foo` or `$.bar`, where bar
1747     /// takes `&mut self`
1748     prefer_mutable: bool,
1749 }
1750
1751 impl<'a, 'tcx> VarVisitor<'a, 'tcx> {
1752     fn check(&mut self, idx: &'tcx Expr<'_>, seqexpr: &'tcx Expr<'_>, expr: &'tcx Expr<'_>) -> bool {
1753         if_chain! {
1754             // the indexed container is referenced by a name
1755             if let ExprKind::Path(ref seqpath) = seqexpr.kind;
1756             if let QPath::Resolved(None, ref seqvar) = *seqpath;
1757             if seqvar.segments.len() == 1;
1758             then {
1759                 let index_used_directly = same_var(self.cx, idx, self.var);
1760                 let indexed_indirectly = {
1761                     let mut used_visitor = LocalUsedVisitor {
1762                         cx: self.cx,
1763                         local: self.var,
1764                         used: false,
1765                     };
1766                     walk_expr(&mut used_visitor, idx);
1767                     used_visitor.used
1768                 };
1769
1770                 if indexed_indirectly || index_used_directly {
1771                     if self.prefer_mutable {
1772                         self.indexed_mut.insert(seqvar.segments[0].ident.name);
1773                     }
1774                     let res = qpath_res(self.cx, seqpath, seqexpr.hir_id);
1775                     match res {
1776                         Res::Local(hir_id) => {
1777                             let parent_id = self.cx.tcx.hir().get_parent_item(expr.hir_id);
1778                             let parent_def_id = self.cx.tcx.hir().local_def_id(parent_id);
1779                             let extent = self.cx.tcx.region_scope_tree(parent_def_id).var_scope(hir_id.local_id);
1780                             if indexed_indirectly {
1781                                 self.indexed_indirectly.insert(seqvar.segments[0].ident.name, Some(extent));
1782                             }
1783                             if index_used_directly {
1784                                 self.indexed_directly.insert(
1785                                     seqvar.segments[0].ident.name,
1786                                     (Some(extent), self.cx.tables.node_type(seqexpr.hir_id)),
1787                                 );
1788                             }
1789                             return false;  // no need to walk further *on the variable*
1790                         }
1791                         Res::Def(DefKind::Static | DefKind::Const, ..) => {
1792                             if indexed_indirectly {
1793                                 self.indexed_indirectly.insert(seqvar.segments[0].ident.name, None);
1794                             }
1795                             if index_used_directly {
1796                                 self.indexed_directly.insert(
1797                                     seqvar.segments[0].ident.name,
1798                                     (None, self.cx.tables.node_type(seqexpr.hir_id)),
1799                                 );
1800                             }
1801                             return false;  // no need to walk further *on the variable*
1802                         }
1803                         _ => (),
1804                     }
1805                 }
1806             }
1807         }
1808         true
1809     }
1810 }
1811
1812 impl<'a, 'tcx> Visitor<'tcx> for VarVisitor<'a, 'tcx> {
1813     type Map = Map<'tcx>;
1814
1815     fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
1816         if_chain! {
1817             // a range index op
1818             if let ExprKind::MethodCall(ref meth, _, ref args) = expr.kind;
1819             if (meth.ident.name == sym!(index) && match_trait_method(self.cx, expr, &paths::INDEX))
1820                 || (meth.ident.name == sym!(index_mut) && match_trait_method(self.cx, expr, &paths::INDEX_MUT));
1821             if !self.check(&args[1], &args[0], expr);
1822             then { return }
1823         }
1824
1825         if_chain! {
1826             // an index op
1827             if let ExprKind::Index(ref seqexpr, ref idx) = expr.kind;
1828             if !self.check(idx, seqexpr, expr);
1829             then { return }
1830         }
1831
1832         if_chain! {
1833             // directly using a variable
1834             if let ExprKind::Path(ref qpath) = expr.kind;
1835             if let QPath::Resolved(None, ref path) = *qpath;
1836             if path.segments.len() == 1;
1837             then {
1838                 if let Res::Local(local_id) = qpath_res(self.cx, qpath, expr.hir_id) {
1839                     if local_id == self.var {
1840                         self.nonindex = true;
1841                     } else {
1842                         // not the correct variable, but still a variable
1843                         self.referenced.insert(path.segments[0].ident.name);
1844                     }
1845                 }
1846             }
1847         }
1848
1849         let old = self.prefer_mutable;
1850         match expr.kind {
1851             ExprKind::AssignOp(_, ref lhs, ref rhs) | ExprKind::Assign(ref lhs, ref rhs, _) => {
1852                 self.prefer_mutable = true;
1853                 self.visit_expr(lhs);
1854                 self.prefer_mutable = false;
1855                 self.visit_expr(rhs);
1856             },
1857             ExprKind::AddrOf(BorrowKind::Ref, mutbl, ref expr) => {
1858                 if mutbl == Mutability::Mut {
1859                     self.prefer_mutable = true;
1860                 }
1861                 self.visit_expr(expr);
1862             },
1863             ExprKind::Call(ref f, args) => {
1864                 self.visit_expr(f);
1865                 for expr in args {
1866                     let ty = self.cx.tables.expr_ty_adjusted(expr);
1867                     self.prefer_mutable = false;
1868                     if let ty::Ref(_, _, mutbl) = ty.kind {
1869                         if mutbl == Mutability::Mut {
1870                             self.prefer_mutable = true;
1871                         }
1872                     }
1873                     self.visit_expr(expr);
1874                 }
1875             },
1876             ExprKind::MethodCall(_, _, args) => {
1877                 let def_id = self.cx.tables.type_dependent_def_id(expr.hir_id).unwrap();
1878                 for (ty, expr) in self.cx.tcx.fn_sig(def_id).inputs().skip_binder().iter().zip(args) {
1879                     self.prefer_mutable = false;
1880                     if let ty::Ref(_, _, mutbl) = ty.kind {
1881                         if mutbl == Mutability::Mut {
1882                             self.prefer_mutable = true;
1883                         }
1884                     }
1885                     self.visit_expr(expr);
1886                 }
1887             },
1888             ExprKind::Closure(_, _, body_id, ..) => {
1889                 let body = self.cx.tcx.hir().body(body_id);
1890                 self.visit_expr(&body.value);
1891             },
1892             _ => walk_expr(self, expr),
1893         }
1894         self.prefer_mutable = old;
1895     }
1896     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
1897         NestedVisitorMap::None
1898     }
1899 }
1900
1901 fn is_used_inside<'a, 'tcx>(cx: &'a LateContext<'a, 'tcx>, expr: &'tcx Expr<'_>, container: &'tcx Expr<'_>) -> bool {
1902     let def_id = match var_def_id(cx, expr) {
1903         Some(id) => id,
1904         None => return false,
1905     };
1906     if let Some(used_mutably) = mutated_variables(container, cx) {
1907         if used_mutably.contains(&def_id) {
1908             return true;
1909         }
1910     }
1911     false
1912 }
1913
1914 fn is_iterator_used_after_while_let<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, iter_expr: &'tcx Expr<'_>) -> bool {
1915     let def_id = match var_def_id(cx, iter_expr) {
1916         Some(id) => id,
1917         None => return false,
1918     };
1919     let mut visitor = VarUsedAfterLoopVisitor {
1920         cx,
1921         def_id,
1922         iter_expr_id: iter_expr.hir_id,
1923         past_while_let: false,
1924         var_used_after_while_let: false,
1925     };
1926     if let Some(enclosing_block) = get_enclosing_block(cx, def_id) {
1927         walk_block(&mut visitor, enclosing_block);
1928     }
1929     visitor.var_used_after_while_let
1930 }
1931
1932 struct VarUsedAfterLoopVisitor<'a, 'tcx> {
1933     cx: &'a LateContext<'a, 'tcx>,
1934     def_id: HirId,
1935     iter_expr_id: HirId,
1936     past_while_let: bool,
1937     var_used_after_while_let: bool,
1938 }
1939
1940 impl<'a, 'tcx> Visitor<'tcx> for VarUsedAfterLoopVisitor<'a, 'tcx> {
1941     type Map = Map<'tcx>;
1942
1943     fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
1944         if self.past_while_let {
1945             if Some(self.def_id) == var_def_id(self.cx, expr) {
1946                 self.var_used_after_while_let = true;
1947             }
1948         } else if self.iter_expr_id == expr.hir_id {
1949             self.past_while_let = true;
1950         }
1951         walk_expr(self, expr);
1952     }
1953     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
1954         NestedVisitorMap::None
1955     }
1956 }
1957
1958 /// Returns `true` if the type of expr is one that provides `IntoIterator` impls
1959 /// for `&T` and `&mut T`, such as `Vec`.
1960 #[rustfmt::skip]
1961 fn is_ref_iterable_type(cx: &LateContext<'_, '_>, e: &Expr<'_>) -> bool {
1962     // no walk_ptrs_ty: calling iter() on a reference can make sense because it
1963     // will allow further borrows afterwards
1964     let ty = cx.tables.expr_ty(e);
1965     is_iterable_array(ty, cx) ||
1966     is_type_diagnostic_item(cx, ty, sym!(vec_type)) ||
1967     match_type(cx, ty, &paths::LINKED_LIST) ||
1968     is_type_diagnostic_item(cx, ty, sym!(hashmap_type)) ||
1969     is_type_diagnostic_item(cx, ty, sym!(hashset_type)) ||
1970     is_type_diagnostic_item(cx, ty, sym!(vecdeque_type)) ||
1971     match_type(cx, ty, &paths::BINARY_HEAP) ||
1972     match_type(cx, ty, &paths::BTREEMAP) ||
1973     match_type(cx, ty, &paths::BTREESET)
1974 }
1975
1976 fn is_iterable_array<'tcx>(ty: Ty<'tcx>, cx: &LateContext<'_, 'tcx>) -> bool {
1977     // IntoIterator is currently only implemented for array sizes <= 32 in rustc
1978     match ty.kind {
1979         ty::Array(_, n) => {
1980             if let Some(val) = n.try_eval_usize(cx.tcx, cx.param_env) {
1981                 (0..=32).contains(&val)
1982             } else {
1983                 false
1984             }
1985         },
1986         _ => false,
1987     }
1988 }
1989
1990 /// If a block begins with a statement (possibly a `let` binding) and has an
1991 /// expression, return it.
1992 fn extract_expr_from_first_stmt<'tcx>(block: &Block<'tcx>) -> Option<&'tcx Expr<'tcx>> {
1993     if block.stmts.is_empty() {
1994         return None;
1995     }
1996     if let StmtKind::Local(ref local) = block.stmts[0].kind {
1997         if let Some(expr) = local.init {
1998             Some(expr)
1999         } else {
2000             None
2001         }
2002     } else {
2003         None
2004     }
2005 }
2006
2007 /// If a block begins with an expression (with or without semicolon), return it.
2008 fn extract_first_expr<'tcx>(block: &Block<'tcx>) -> Option<&'tcx Expr<'tcx>> {
2009     match block.expr {
2010         Some(ref expr) if block.stmts.is_empty() => Some(expr),
2011         None if !block.stmts.is_empty() => match block.stmts[0].kind {
2012             StmtKind::Expr(ref expr) | StmtKind::Semi(ref expr) => Some(expr),
2013             StmtKind::Local(..) | StmtKind::Item(..) => None,
2014         },
2015         _ => None,
2016     }
2017 }
2018
2019 /// Returns `true` if expr contains a single break expr without destination label
2020 /// and
2021 /// passed expression. The expression may be within a block.
2022 fn is_simple_break_expr(expr: &Expr<'_>) -> bool {
2023     match expr.kind {
2024         ExprKind::Break(dest, ref passed_expr) if dest.label.is_none() && passed_expr.is_none() => true,
2025         ExprKind::Block(ref b, _) => extract_first_expr(b).map_or(false, |subexpr| is_simple_break_expr(subexpr)),
2026         _ => false,
2027     }
2028 }
2029
2030 // To trigger the EXPLICIT_COUNTER_LOOP lint, a variable must be
2031 // incremented exactly once in the loop body, and initialized to zero
2032 // at the start of the loop.
2033 #[derive(Debug, PartialEq)]
2034 enum VarState {
2035     Initial,  // Not examined yet
2036     IncrOnce, // Incremented exactly once, may be a loop counter
2037     Declared, // Declared but not (yet) initialized to zero
2038     Warn,
2039     DontWarn,
2040 }
2041
2042 /// Scan a for loop for variables that are incremented exactly once.
2043 struct IncrementVisitor<'a, 'tcx> {
2044     cx: &'a LateContext<'a, 'tcx>,      // context reference
2045     states: FxHashMap<HirId, VarState>, // incremented variables
2046     depth: u32,                         // depth of conditional expressions
2047     done: bool,
2048 }
2049
2050 impl<'a, 'tcx> Visitor<'tcx> for IncrementVisitor<'a, 'tcx> {
2051     type Map = Map<'tcx>;
2052
2053     fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
2054         if self.done {
2055             return;
2056         }
2057
2058         // If node is a variable
2059         if let Some(def_id) = var_def_id(self.cx, expr) {
2060             if let Some(parent) = get_parent_expr(self.cx, expr) {
2061                 let state = self.states.entry(def_id).or_insert(VarState::Initial);
2062
2063                 match parent.kind {
2064                     ExprKind::AssignOp(op, ref lhs, ref rhs) => {
2065                         if lhs.hir_id == expr.hir_id {
2066                             if op.node == BinOpKind::Add && is_integer_const(self.cx, rhs, 1) {
2067                                 *state = match *state {
2068                                     VarState::Initial if self.depth == 0 => VarState::IncrOnce,
2069                                     _ => VarState::DontWarn,
2070                                 };
2071                             } else {
2072                                 // Assigned some other value
2073                                 *state = VarState::DontWarn;
2074                             }
2075                         }
2076                     },
2077                     ExprKind::Assign(ref lhs, _, _) if lhs.hir_id == expr.hir_id => *state = VarState::DontWarn,
2078                     ExprKind::AddrOf(BorrowKind::Ref, mutability, _) if mutability == Mutability::Mut => {
2079                         *state = VarState::DontWarn
2080                     },
2081                     _ => (),
2082                 }
2083             }
2084         } else if is_loop(expr) || is_conditional(expr) {
2085             self.depth += 1;
2086             walk_expr(self, expr);
2087             self.depth -= 1;
2088             return;
2089         } else if let ExprKind::Continue(_) = expr.kind {
2090             self.done = true;
2091             return;
2092         }
2093         walk_expr(self, expr);
2094     }
2095     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
2096         NestedVisitorMap::None
2097     }
2098 }
2099
2100 /// Checks whether a variable is initialized to zero at the start of a loop.
2101 struct InitializeVisitor<'a, 'tcx> {
2102     cx: &'a LateContext<'a, 'tcx>, // context reference
2103     end_expr: &'tcx Expr<'tcx>,    // the for loop. Stop scanning here.
2104     var_id: HirId,
2105     state: VarState,
2106     name: Option<Name>,
2107     depth: u32, // depth of conditional expressions
2108     past_loop: bool,
2109 }
2110
2111 impl<'a, 'tcx> Visitor<'tcx> for InitializeVisitor<'a, 'tcx> {
2112     type Map = Map<'tcx>;
2113
2114     fn visit_stmt(&mut self, stmt: &'tcx Stmt<'_>) {
2115         // Look for declarations of the variable
2116         if let StmtKind::Local(ref local) = stmt.kind {
2117             if local.pat.hir_id == self.var_id {
2118                 if let PatKind::Binding(.., ident, _) = local.pat.kind {
2119                     self.name = Some(ident.name);
2120
2121                     self.state = if let Some(ref init) = local.init {
2122                         if is_integer_const(&self.cx, init, 0) {
2123                             VarState::Warn
2124                         } else {
2125                             VarState::Declared
2126                         }
2127                     } else {
2128                         VarState::Declared
2129                     }
2130                 }
2131             }
2132         }
2133         walk_stmt(self, stmt);
2134     }
2135
2136     fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
2137         if self.state == VarState::DontWarn {
2138             return;
2139         }
2140         if SpanlessEq::new(self.cx).eq_expr(&expr, self.end_expr) {
2141             self.past_loop = true;
2142             return;
2143         }
2144         // No need to visit expressions before the variable is
2145         // declared
2146         if self.state == VarState::IncrOnce {
2147             return;
2148         }
2149
2150         // If node is the desired variable, see how it's used
2151         if var_def_id(self.cx, expr) == Some(self.var_id) {
2152             if let Some(parent) = get_parent_expr(self.cx, expr) {
2153                 match parent.kind {
2154                     ExprKind::AssignOp(_, ref lhs, _) if lhs.hir_id == expr.hir_id => {
2155                         self.state = VarState::DontWarn;
2156                     },
2157                     ExprKind::Assign(ref lhs, ref rhs, _) if lhs.hir_id == expr.hir_id => {
2158                         self.state = if is_integer_const(&self.cx, rhs, 0) && self.depth == 0 {
2159                             VarState::Warn
2160                         } else {
2161                             VarState::DontWarn
2162                         }
2163                     },
2164                     ExprKind::AddrOf(BorrowKind::Ref, mutability, _) if mutability == Mutability::Mut => {
2165                         self.state = VarState::DontWarn
2166                     },
2167                     _ => (),
2168                 }
2169             }
2170
2171             if self.past_loop {
2172                 self.state = VarState::DontWarn;
2173                 return;
2174             }
2175         } else if !self.past_loop && is_loop(expr) {
2176             self.state = VarState::DontWarn;
2177             return;
2178         } else if is_conditional(expr) {
2179             self.depth += 1;
2180             walk_expr(self, expr);
2181             self.depth -= 1;
2182             return;
2183         }
2184         walk_expr(self, expr);
2185     }
2186
2187     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
2188         NestedVisitorMap::OnlyBodies(self.cx.tcx.hir())
2189     }
2190 }
2191
2192 fn var_def_id(cx: &LateContext<'_, '_>, expr: &Expr<'_>) -> Option<HirId> {
2193     if let ExprKind::Path(ref qpath) = expr.kind {
2194         let path_res = qpath_res(cx, qpath, expr.hir_id);
2195         if let Res::Local(hir_id) = path_res {
2196             return Some(hir_id);
2197         }
2198     }
2199     None
2200 }
2201
2202 fn is_loop(expr: &Expr<'_>) -> bool {
2203     match expr.kind {
2204         ExprKind::Loop(..) => true,
2205         _ => false,
2206     }
2207 }
2208
2209 fn is_conditional(expr: &Expr<'_>) -> bool {
2210     match expr.kind {
2211         ExprKind::Match(..) => true,
2212         _ => false,
2213     }
2214 }
2215
2216 fn is_nested(cx: &LateContext<'_, '_>, match_expr: &Expr<'_>, iter_expr: &Expr<'_>) -> bool {
2217     if_chain! {
2218         if let Some(loop_block) = get_enclosing_block(cx, match_expr.hir_id);
2219         let parent_node = cx.tcx.hir().get_parent_node(loop_block.hir_id);
2220         if let Some(Node::Expr(loop_expr)) = cx.tcx.hir().find(parent_node);
2221         then {
2222             return is_loop_nested(cx, loop_expr, iter_expr)
2223         }
2224     }
2225     false
2226 }
2227
2228 fn is_loop_nested(cx: &LateContext<'_, '_>, loop_expr: &Expr<'_>, iter_expr: &Expr<'_>) -> bool {
2229     let mut id = loop_expr.hir_id;
2230     let iter_name = if let Some(name) = path_name(iter_expr) {
2231         name
2232     } else {
2233         return true;
2234     };
2235     loop {
2236         let parent = cx.tcx.hir().get_parent_node(id);
2237         if parent == id {
2238             return false;
2239         }
2240         match cx.tcx.hir().find(parent) {
2241             Some(Node::Expr(expr)) => {
2242                 if let ExprKind::Loop(..) = expr.kind {
2243                     return true;
2244                 };
2245             },
2246             Some(Node::Block(block)) => {
2247                 let mut block_visitor = LoopNestVisitor {
2248                     hir_id: id,
2249                     iterator: iter_name,
2250                     nesting: Unknown,
2251                 };
2252                 walk_block(&mut block_visitor, block);
2253                 if block_visitor.nesting == RuledOut {
2254                     return false;
2255                 }
2256             },
2257             Some(Node::Stmt(_)) => (),
2258             _ => {
2259                 return false;
2260             },
2261         }
2262         id = parent;
2263     }
2264 }
2265
2266 #[derive(PartialEq, Eq)]
2267 enum Nesting {
2268     Unknown,     // no nesting detected yet
2269     RuledOut,    // the iterator is initialized or assigned within scope
2270     LookFurther, // no nesting detected, no further walk required
2271 }
2272
2273 use self::Nesting::{LookFurther, RuledOut, Unknown};
2274
2275 struct LoopNestVisitor {
2276     hir_id: HirId,
2277     iterator: Name,
2278     nesting: Nesting,
2279 }
2280
2281 impl<'tcx> Visitor<'tcx> for LoopNestVisitor {
2282     type Map = Map<'tcx>;
2283
2284     fn visit_stmt(&mut self, stmt: &'tcx Stmt<'_>) {
2285         if stmt.hir_id == self.hir_id {
2286             self.nesting = LookFurther;
2287         } else if self.nesting == Unknown {
2288             walk_stmt(self, stmt);
2289         }
2290     }
2291
2292     fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
2293         if self.nesting != Unknown {
2294             return;
2295         }
2296         if expr.hir_id == self.hir_id {
2297             self.nesting = LookFurther;
2298             return;
2299         }
2300         match expr.kind {
2301             ExprKind::Assign(ref path, _, _) | ExprKind::AssignOp(_, ref path, _) => {
2302                 if match_var(path, self.iterator) {
2303                     self.nesting = RuledOut;
2304                 }
2305             },
2306             _ => walk_expr(self, expr),
2307         }
2308     }
2309
2310     fn visit_pat(&mut self, pat: &'tcx Pat<'_>) {
2311         if self.nesting != Unknown {
2312             return;
2313         }
2314         if let PatKind::Binding(.., span_name, _) = pat.kind {
2315             if self.iterator == span_name.name {
2316                 self.nesting = RuledOut;
2317                 return;
2318             }
2319         }
2320         walk_pat(self, pat)
2321     }
2322
2323     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
2324         NestedVisitorMap::None
2325     }
2326 }
2327
2328 fn path_name(e: &Expr<'_>) -> Option<Name> {
2329     if let ExprKind::Path(QPath::Resolved(_, ref path)) = e.kind {
2330         let segments = &path.segments;
2331         if segments.len() == 1 {
2332             return Some(segments[0].ident.name);
2333         }
2334     };
2335     None
2336 }
2337
2338 fn check_infinite_loop<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, cond: &'tcx Expr<'_>, expr: &'tcx Expr<'_>) {
2339     if constant(cx, cx.tables, cond).is_some() {
2340         // A pure constant condition (e.g., `while false`) is not linted.
2341         return;
2342     }
2343
2344     let mut var_visitor = VarCollectorVisitor {
2345         cx,
2346         ids: FxHashSet::default(),
2347         def_ids: FxHashMap::default(),
2348         skip: false,
2349     };
2350     var_visitor.visit_expr(cond);
2351     if var_visitor.skip {
2352         return;
2353     }
2354     let used_in_condition = &var_visitor.ids;
2355     let no_cond_variable_mutated = if let Some(used_mutably) = mutated_variables(expr, cx) {
2356         used_in_condition.is_disjoint(&used_mutably)
2357     } else {
2358         return;
2359     };
2360     let mutable_static_in_cond = var_visitor.def_ids.iter().any(|(_, v)| *v);
2361
2362     let mut has_break_or_return_visitor = HasBreakOrReturnVisitor {
2363         has_break_or_return: false,
2364     };
2365     has_break_or_return_visitor.visit_expr(expr);
2366     let has_break_or_return = has_break_or_return_visitor.has_break_or_return;
2367
2368     if no_cond_variable_mutated && !mutable_static_in_cond {
2369         span_lint_and_then(
2370             cx,
2371             WHILE_IMMUTABLE_CONDITION,
2372             cond.span,
2373             "variables in the condition are not mutated in the loop body",
2374             |diag| {
2375                 diag.note("this may lead to an infinite or to a never running loop");
2376
2377                 if has_break_or_return {
2378                     diag.note("this loop contains `return`s or `break`s");
2379                     diag.help("rewrite it as `if cond { loop { } }`");
2380                 }
2381             },
2382         );
2383     }
2384 }
2385
2386 struct HasBreakOrReturnVisitor {
2387     has_break_or_return: bool,
2388 }
2389
2390 impl<'a, 'tcx> Visitor<'tcx> for HasBreakOrReturnVisitor {
2391     type Map = Map<'tcx>;
2392
2393     fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
2394         if self.has_break_or_return {
2395             return;
2396         }
2397
2398         match expr.kind {
2399             ExprKind::Ret(_) | ExprKind::Break(_, _) => {
2400                 self.has_break_or_return = true;
2401                 return;
2402             },
2403             _ => {},
2404         }
2405
2406         walk_expr(self, expr);
2407     }
2408
2409     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
2410         NestedVisitorMap::None
2411     }
2412 }
2413
2414 /// Collects the set of variables in an expression
2415 /// Stops analysis if a function call is found
2416 /// Note: In some cases such as `self`, there are no mutable annotation,
2417 /// All variables definition IDs are collected
2418 struct VarCollectorVisitor<'a, 'tcx> {
2419     cx: &'a LateContext<'a, 'tcx>,
2420     ids: FxHashSet<HirId>,
2421     def_ids: FxHashMap<def_id::DefId, bool>,
2422     skip: bool,
2423 }
2424
2425 impl<'a, 'tcx> VarCollectorVisitor<'a, 'tcx> {
2426     fn insert_def_id(&mut self, ex: &'tcx Expr<'_>) {
2427         if_chain! {
2428             if let ExprKind::Path(ref qpath) = ex.kind;
2429             if let QPath::Resolved(None, _) = *qpath;
2430             let res = qpath_res(self.cx, qpath, ex.hir_id);
2431             then {
2432                 match res {
2433                     Res::Local(hir_id) => {
2434                         self.ids.insert(hir_id);
2435                     },
2436                     Res::Def(DefKind::Static, def_id) => {
2437                         let mutable = self.cx.tcx.is_mutable_static(def_id);
2438                         self.def_ids.insert(def_id, mutable);
2439                     },
2440                     _ => {},
2441                 }
2442             }
2443         }
2444     }
2445 }
2446
2447 impl<'a, 'tcx> Visitor<'tcx> for VarCollectorVisitor<'a, 'tcx> {
2448     type Map = Map<'tcx>;
2449
2450     fn visit_expr(&mut self, ex: &'tcx Expr<'_>) {
2451         match ex.kind {
2452             ExprKind::Path(_) => self.insert_def_id(ex),
2453             // If there is any function/method call… we just stop analysis
2454             ExprKind::Call(..) | ExprKind::MethodCall(..) => self.skip = true,
2455
2456             _ => walk_expr(self, ex),
2457         }
2458     }
2459
2460     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
2461         NestedVisitorMap::None
2462     }
2463 }
2464
2465 const NEEDLESS_COLLECT_MSG: &str = "avoid using `collect()` when not needed";
2466
2467 fn check_needless_collect<'a, 'tcx>(expr: &'tcx Expr<'_>, cx: &LateContext<'a, 'tcx>) {
2468     if_chain! {
2469         if let ExprKind::MethodCall(ref method, _, ref args) = expr.kind;
2470         if let ExprKind::MethodCall(ref chain_method, _, _) = args[0].kind;
2471         if chain_method.ident.name == sym!(collect) && match_trait_method(cx, &args[0], &paths::ITERATOR);
2472         if let Some(ref generic_args) = chain_method.args;
2473         if let Some(GenericArg::Type(ref ty)) = generic_args.args.get(0);
2474         then {
2475             let ty = cx.tables.node_type(ty.hir_id);
2476             if is_type_diagnostic_item(cx, ty, sym!(vec_type)) ||
2477                 is_type_diagnostic_item(cx, ty, sym!(vecdeque_type)) ||
2478                 match_type(cx, ty, &paths::BTREEMAP) ||
2479                 is_type_diagnostic_item(cx, ty, sym!(hashmap_type)) {
2480                 if method.ident.name == sym!(len) {
2481                     let span = shorten_needless_collect_span(expr);
2482                     span_lint_and_sugg(
2483                         cx,
2484                         NEEDLESS_COLLECT,
2485                         span,
2486                         NEEDLESS_COLLECT_MSG,
2487                         "replace with",
2488                         ".count()".to_string(),
2489                         Applicability::MachineApplicable,
2490                     );
2491                 }
2492                 if method.ident.name == sym!(is_empty) {
2493                     let span = shorten_needless_collect_span(expr);
2494                     span_lint_and_sugg(
2495                         cx,
2496                         NEEDLESS_COLLECT,
2497                         span,
2498                         NEEDLESS_COLLECT_MSG,
2499                         "replace with",
2500                         ".next().is_none()".to_string(),
2501                         Applicability::MachineApplicable,
2502                     );
2503                 }
2504                 if method.ident.name == sym!(contains) {
2505                     let contains_arg = snippet(cx, args[1].span, "??");
2506                     let span = shorten_needless_collect_span(expr);
2507                     span_lint_and_then(
2508                         cx,
2509                         NEEDLESS_COLLECT,
2510                         span,
2511                         NEEDLESS_COLLECT_MSG,
2512                         |diag| {
2513                             let (arg, pred) = if contains_arg.starts_with('&') {
2514                                 ("x", &contains_arg[1..])
2515                             } else {
2516                                 ("&x", &*contains_arg)
2517                             };
2518                             diag.span_suggestion(
2519                                 span,
2520                                 "replace with",
2521                                 format!(
2522                                     ".any(|{}| x == {})",
2523                                     arg, pred
2524                                 ),
2525                                 Applicability::MachineApplicable,
2526                             );
2527                         }
2528                     );
2529                 }
2530             }
2531         }
2532     }
2533 }
2534
2535 fn shorten_needless_collect_span(expr: &Expr<'_>) -> Span {
2536     if_chain! {
2537         if let ExprKind::MethodCall(_, _, ref args) = expr.kind;
2538         if let ExprKind::MethodCall(_, ref span, _) = args[0].kind;
2539         then {
2540             return expr.span.with_lo(span.lo() - BytePos(1));
2541         }
2542     }
2543     unreachable!()
2544 }