]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/loops.rs
Merge commit '43a1777b89cf6791f9e20878b4e5e3ae907867a5' into clippyup
[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         then {
779             // our variable!
780             local_id == var
781         } else {
782             false
783         }
784     }
785 }
786
787 #[derive(Clone, Copy)]
788 enum OffsetSign {
789     Positive,
790     Negative,
791 }
792
793 struct Offset {
794     value: String,
795     sign: OffsetSign,
796 }
797
798 impl Offset {
799     fn negative(value: String) -> Self {
800         Self {
801             value,
802             sign: OffsetSign::Negative,
803         }
804     }
805
806     fn positive(value: String) -> Self {
807         Self {
808             value,
809             sign: OffsetSign::Positive,
810         }
811     }
812 }
813
814 struct FixedOffsetVar<'hir> {
815     var: &'hir Expr<'hir>,
816     offset: Offset,
817 }
818
819 fn is_slice_like<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, ty: Ty<'_>) -> bool {
820     let is_slice = match ty.kind {
821         ty::Ref(_, subty, _) => is_slice_like(cx, subty),
822         ty::Slice(..) | ty::Array(..) => true,
823         _ => false,
824     };
825
826     is_slice || is_type_diagnostic_item(cx, ty, sym!(vec_type)) || is_type_diagnostic_item(cx, ty, sym!(vecdeque_type))
827 }
828
829 fn fetch_cloned_expr<'tcx>(expr: &'tcx Expr<'tcx>) -> &'tcx Expr<'tcx> {
830     if_chain! {
831         if let ExprKind::MethodCall(method, _, args) = expr.kind;
832         if method.ident.name == sym!(clone);
833         if args.len() == 1;
834         if let Some(arg) = args.get(0);
835         then { arg } else { expr }
836     }
837 }
838
839 fn get_offset<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, idx: &Expr<'_>, var: HirId) -> Option<Offset> {
840     fn extract_offset<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, e: &Expr<'_>, var: HirId) -> Option<String> {
841         match &e.kind {
842             ExprKind::Lit(l) => match l.node {
843                 ast::LitKind::Int(x, _ty) => Some(x.to_string()),
844                 _ => None,
845             },
846             ExprKind::Path(..) if !same_var(cx, e, var) => Some(snippet_opt(cx, e.span).unwrap_or_else(|| "??".into())),
847             _ => None,
848         }
849     }
850
851     match idx.kind {
852         ExprKind::Binary(op, lhs, rhs) => match op.node {
853             BinOpKind::Add => {
854                 let offset_opt = if same_var(cx, lhs, var) {
855                     extract_offset(cx, rhs, var)
856                 } else if same_var(cx, rhs, var) {
857                     extract_offset(cx, lhs, var)
858                 } else {
859                     None
860                 };
861
862                 offset_opt.map(Offset::positive)
863             },
864             BinOpKind::Sub if same_var(cx, lhs, var) => extract_offset(cx, rhs, var).map(Offset::negative),
865             _ => None,
866         },
867         ExprKind::Path(..) if same_var(cx, idx, var) => Some(Offset::positive("0".into())),
868         _ => None,
869     }
870 }
871
872 fn get_assignments<'tcx>(body: &'tcx Expr<'tcx>) -> impl Iterator<Item = Option<(&'tcx Expr<'tcx>, &'tcx Expr<'tcx>)>> {
873     fn get_assignment<'tcx>(e: &'tcx Expr<'tcx>) -> Option<(&'tcx Expr<'tcx>, &'tcx Expr<'tcx>)> {
874         if let ExprKind::Assign(lhs, rhs, _) = e.kind {
875             Some((lhs, rhs))
876         } else {
877             None
878         }
879     }
880
881     // This is one of few ways to return different iterators
882     // derived from: https://stackoverflow.com/questions/29760668/conditionally-iterate-over-one-of-several-possible-iterators/52064434#52064434
883     let mut iter_a = None;
884     let mut iter_b = None;
885
886     if let ExprKind::Block(b, _) = body.kind {
887         let Block { stmts, expr, .. } = *b;
888
889         iter_a = stmts
890             .iter()
891             .filter_map(|stmt| match stmt.kind {
892                 StmtKind::Local(..) | StmtKind::Item(..) => None,
893                 StmtKind::Expr(e) | StmtKind::Semi(e) => Some(e),
894             })
895             .chain(expr.into_iter())
896             .map(get_assignment)
897             .into()
898     } else {
899         iter_b = Some(get_assignment(body))
900     }
901
902     iter_a.into_iter().flatten().chain(iter_b.into_iter())
903 }
904
905 fn build_manual_memcpy_suggestion<'a, 'tcx>(
906     cx: &LateContext<'a, 'tcx>,
907     start: &Expr<'_>,
908     end: &Expr<'_>,
909     limits: ast::RangeLimits,
910     dst_var: FixedOffsetVar<'_>,
911     src_var: FixedOffsetVar<'_>,
912 ) -> String {
913     fn print_sum(arg1: &str, arg2: &Offset) -> String {
914         match (arg1, &arg2.value[..], arg2.sign) {
915             ("0", "0", _) => "0".into(),
916             ("0", x, OffsetSign::Positive) | (x, "0", _) => x.into(),
917             ("0", x, OffsetSign::Negative) => format!("-{}", x),
918             (x, y, OffsetSign::Positive) => format!("({} + {})", x, y),
919             (x, y, OffsetSign::Negative) => {
920                 if x == y {
921                     "0".into()
922                 } else {
923                     format!("({} - {})", x, y)
924                 }
925             },
926         }
927     }
928
929     fn print_offset(start_str: &str, inline_offset: &Offset) -> String {
930         let offset = print_sum(start_str, inline_offset);
931         if offset.as_str() == "0" {
932             "".into()
933         } else {
934             offset
935         }
936     }
937
938     let print_limit = |end: &Expr<'_>, offset: Offset, var: &Expr<'_>| {
939         if_chain! {
940             if let ExprKind::MethodCall(method, _, len_args) = end.kind;
941             if method.ident.name == sym!(len);
942             if len_args.len() == 1;
943             if let Some(arg) = len_args.get(0);
944             if var_def_id(cx, arg) == var_def_id(cx, var);
945             then {
946                 match offset.sign {
947                     OffsetSign::Negative => format!("({} - {})", snippet(cx, end.span, "<src>.len()"), offset.value),
948                     OffsetSign::Positive => "".into(),
949                 }
950             } else {
951                 let end_str = match limits {
952                     ast::RangeLimits::Closed => {
953                         let end = sugg::Sugg::hir(cx, end, "<count>");
954                         format!("{}", end + sugg::ONE)
955                     },
956                     ast::RangeLimits::HalfOpen => format!("{}", snippet(cx, end.span, "..")),
957                 };
958
959                 print_sum(&end_str, &offset)
960             }
961         }
962     };
963
964     let start_str = snippet(cx, start.span, "").to_string();
965     let dst_offset = print_offset(&start_str, &dst_var.offset);
966     let dst_limit = print_limit(end, dst_var.offset, dst_var.var);
967     let src_offset = print_offset(&start_str, &src_var.offset);
968     let src_limit = print_limit(end, src_var.offset, src_var.var);
969
970     let dst_var_name = snippet_opt(cx, dst_var.var.span).unwrap_or_else(|| "???".into());
971     let src_var_name = snippet_opt(cx, src_var.var.span).unwrap_or_else(|| "???".into());
972
973     let dst = if dst_offset == "" && dst_limit == "" {
974         dst_var_name
975     } else {
976         format!("{}[{}..{}]", dst_var_name, dst_offset, dst_limit)
977     };
978
979     format!(
980         "{}.clone_from_slice(&{}[{}..{}])",
981         dst, src_var_name, src_offset, src_limit
982     )
983 }
984 /// Checks for for loops that sequentially copy items from one slice-like
985 /// object to another.
986 fn detect_manual_memcpy<'a, 'tcx>(
987     cx: &LateContext<'a, 'tcx>,
988     pat: &'tcx Pat<'_>,
989     arg: &'tcx Expr<'_>,
990     body: &'tcx Expr<'_>,
991     expr: &'tcx Expr<'_>,
992 ) {
993     if let Some(higher::Range {
994         start: Some(start),
995         end: Some(end),
996         limits,
997     }) = higher::range(cx, arg)
998     {
999         // the var must be a single name
1000         if let PatKind::Binding(_, canonical_id, _, _) = pat.kind {
1001             // The only statements in the for loops can be indexed assignments from
1002             // indexed retrievals.
1003             let big_sugg = get_assignments(body)
1004                 .map(|o| {
1005                     o.and_then(|(lhs, rhs)| {
1006                         let rhs = fetch_cloned_expr(rhs);
1007                         if_chain! {
1008                             if let ExprKind::Index(seqexpr_left, idx_left) = lhs.kind;
1009                             if let ExprKind::Index(seqexpr_right, idx_right) = rhs.kind;
1010                             if is_slice_like(cx, cx.tables.expr_ty(seqexpr_left))
1011                                 && is_slice_like(cx, cx.tables.expr_ty(seqexpr_right));
1012                             if let Some(offset_left) = get_offset(cx, &idx_left, canonical_id);
1013                             if let Some(offset_right) = get_offset(cx, &idx_right, canonical_id);
1014
1015                             // Source and destination must be different
1016                             if var_def_id(cx, seqexpr_left) != var_def_id(cx, seqexpr_right);
1017                             then {
1018                                 Some((FixedOffsetVar { var: seqexpr_left, offset: offset_left },
1019                                     FixedOffsetVar { var: seqexpr_right, offset: offset_right }))
1020                             } else {
1021                                 None
1022                             }
1023                         }
1024                     })
1025                 })
1026                 .map(|o| o.map(|(dst, src)| build_manual_memcpy_suggestion(cx, start, end, limits, dst, src)))
1027                 .collect::<Option<Vec<_>>>()
1028                 .filter(|v| !v.is_empty())
1029                 .map(|v| v.join("\n    "));
1030
1031             if let Some(big_sugg) = big_sugg {
1032                 span_lint_and_sugg(
1033                     cx,
1034                     MANUAL_MEMCPY,
1035                     expr.span,
1036                     "it looks like you're manually copying between slices",
1037                     "try replacing the loop by",
1038                     big_sugg,
1039                     Applicability::Unspecified,
1040                 );
1041             }
1042         }
1043     }
1044 }
1045
1046 /// Checks for looping over a range and then indexing a sequence with it.
1047 /// The iteratee must be a range literal.
1048 #[allow(clippy::too_many_lines)]
1049 fn check_for_loop_range<'a, 'tcx>(
1050     cx: &LateContext<'a, 'tcx>,
1051     pat: &'tcx Pat<'_>,
1052     arg: &'tcx Expr<'_>,
1053     body: &'tcx Expr<'_>,
1054     expr: &'tcx Expr<'_>,
1055 ) {
1056     if let Some(higher::Range {
1057         start: Some(start),
1058         ref end,
1059         limits,
1060     }) = higher::range(cx, arg)
1061     {
1062         // the var must be a single name
1063         if let PatKind::Binding(_, canonical_id, ident, _) = pat.kind {
1064             let mut visitor = VarVisitor {
1065                 cx,
1066                 var: canonical_id,
1067                 indexed_mut: FxHashSet::default(),
1068                 indexed_indirectly: FxHashMap::default(),
1069                 indexed_directly: FxHashMap::default(),
1070                 referenced: FxHashSet::default(),
1071                 nonindex: false,
1072                 prefer_mutable: false,
1073             };
1074             walk_expr(&mut visitor, body);
1075
1076             // linting condition: we only indexed one variable, and indexed it directly
1077             if visitor.indexed_indirectly.is_empty() && visitor.indexed_directly.len() == 1 {
1078                 let (indexed, (indexed_extent, indexed_ty)) = visitor
1079                     .indexed_directly
1080                     .into_iter()
1081                     .next()
1082                     .expect("already checked that we have exactly 1 element");
1083
1084                 // ensure that the indexed variable was declared before the loop, see #601
1085                 if let Some(indexed_extent) = indexed_extent {
1086                     let parent_id = cx.tcx.hir().get_parent_item(expr.hir_id);
1087                     let parent_def_id = cx.tcx.hir().local_def_id(parent_id);
1088                     let region_scope_tree = cx.tcx.region_scope_tree(parent_def_id);
1089                     let pat_extent = region_scope_tree.var_scope(pat.hir_id.local_id);
1090                     if region_scope_tree.is_subscope_of(indexed_extent, pat_extent) {
1091                         return;
1092                     }
1093                 }
1094
1095                 // don't lint if the container that is indexed does not have .iter() method
1096                 let has_iter = has_iter_method(cx, indexed_ty);
1097                 if has_iter.is_none() {
1098                     return;
1099                 }
1100
1101                 // don't lint if the container that is indexed into is also used without
1102                 // indexing
1103                 if visitor.referenced.contains(&indexed) {
1104                     return;
1105                 }
1106
1107                 let starts_at_zero = is_integer_const(cx, start, 0);
1108
1109                 let skip = if starts_at_zero {
1110                     String::new()
1111                 } else {
1112                     format!(".skip({})", snippet(cx, start.span, ".."))
1113                 };
1114
1115                 let mut end_is_start_plus_val = false;
1116
1117                 let take = if let Some(end) = *end {
1118                     let mut take_expr = end;
1119
1120                     if let ExprKind::Binary(ref op, ref left, ref right) = end.kind {
1121                         if let BinOpKind::Add = op.node {
1122                             let start_equal_left = SpanlessEq::new(cx).eq_expr(start, left);
1123                             let start_equal_right = SpanlessEq::new(cx).eq_expr(start, right);
1124
1125                             if start_equal_left {
1126                                 take_expr = right;
1127                             } else if start_equal_right {
1128                                 take_expr = left;
1129                             }
1130
1131                             end_is_start_plus_val = start_equal_left | start_equal_right;
1132                         }
1133                     }
1134
1135                     if is_len_call(end, indexed) || is_end_eq_array_len(cx, end, limits, indexed_ty) {
1136                         String::new()
1137                     } else {
1138                         match limits {
1139                             ast::RangeLimits::Closed => {
1140                                 let take_expr = sugg::Sugg::hir(cx, take_expr, "<count>");
1141                                 format!(".take({})", take_expr + sugg::ONE)
1142                             },
1143                             ast::RangeLimits::HalfOpen => format!(".take({})", snippet(cx, take_expr.span, "..")),
1144                         }
1145                     }
1146                 } else {
1147                     String::new()
1148                 };
1149
1150                 let (ref_mut, method) = if visitor.indexed_mut.contains(&indexed) {
1151                     ("mut ", "iter_mut")
1152                 } else {
1153                     ("", "iter")
1154                 };
1155
1156                 let take_is_empty = take.is_empty();
1157                 let mut method_1 = take;
1158                 let mut method_2 = skip;
1159
1160                 if end_is_start_plus_val {
1161                     mem::swap(&mut method_1, &mut method_2);
1162                 }
1163
1164                 if visitor.nonindex {
1165                     span_lint_and_then(
1166                         cx,
1167                         NEEDLESS_RANGE_LOOP,
1168                         expr.span,
1169                         &format!("the loop variable `{}` is used to index `{}`", ident.name, indexed),
1170                         |diag| {
1171                             multispan_sugg(
1172                                 diag,
1173                                 "consider using an iterator".to_string(),
1174                                 vec![
1175                                     (pat.span, format!("({}, <item>)", ident.name)),
1176                                     (
1177                                         arg.span,
1178                                         format!("{}.{}().enumerate(){}{}", indexed, method, method_1, method_2),
1179                                     ),
1180                                 ],
1181                             );
1182                         },
1183                     );
1184                 } else {
1185                     let repl = if starts_at_zero && take_is_empty {
1186                         format!("&{}{}", ref_mut, indexed)
1187                     } else {
1188                         format!("{}.{}(){}{}", indexed, method, method_1, method_2)
1189                     };
1190
1191                     span_lint_and_then(
1192                         cx,
1193                         NEEDLESS_RANGE_LOOP,
1194                         expr.span,
1195                         &format!(
1196                             "the loop variable `{}` is only used to index `{}`.",
1197                             ident.name, indexed
1198                         ),
1199                         |diag| {
1200                             multispan_sugg(
1201                                 diag,
1202                                 "consider using an iterator".to_string(),
1203                                 vec![(pat.span, "<item>".to_string()), (arg.span, repl)],
1204                             );
1205                         },
1206                     );
1207                 }
1208             }
1209         }
1210     }
1211 }
1212
1213 fn is_len_call(expr: &Expr<'_>, var: Name) -> bool {
1214     if_chain! {
1215         if let ExprKind::MethodCall(ref method, _, ref len_args) = expr.kind;
1216         if len_args.len() == 1;
1217         if method.ident.name == sym!(len);
1218         if let ExprKind::Path(QPath::Resolved(_, ref path)) = len_args[0].kind;
1219         if path.segments.len() == 1;
1220         if path.segments[0].ident.name == var;
1221         then {
1222             return true;
1223         }
1224     }
1225
1226     false
1227 }
1228
1229 fn is_end_eq_array_len<'tcx>(
1230     cx: &LateContext<'_, 'tcx>,
1231     end: &Expr<'_>,
1232     limits: ast::RangeLimits,
1233     indexed_ty: Ty<'tcx>,
1234 ) -> bool {
1235     if_chain! {
1236         if let ExprKind::Lit(ref lit) = end.kind;
1237         if let ast::LitKind::Int(end_int, _) = lit.node;
1238         if let ty::Array(_, arr_len_const) = indexed_ty.kind;
1239         if let Some(arr_len) = arr_len_const.try_eval_usize(cx.tcx, cx.param_env);
1240         then {
1241             return match limits {
1242                 ast::RangeLimits::Closed => end_int + 1 >= arr_len.into(),
1243                 ast::RangeLimits::HalfOpen => end_int >= arr_len.into(),
1244             };
1245         }
1246     }
1247
1248     false
1249 }
1250
1251 fn check_for_loop_reverse_range<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, arg: &'tcx Expr<'_>, expr: &'tcx Expr<'_>) {
1252     // if this for loop is iterating over a two-sided range...
1253     if let Some(higher::Range {
1254         start: Some(start),
1255         end: Some(end),
1256         limits,
1257     }) = higher::range(cx, arg)
1258     {
1259         // ...and both sides are compile-time constant integers...
1260         if let Some((start_idx, _)) = constant(cx, cx.tables, start) {
1261             if let Some((end_idx, _)) = constant(cx, cx.tables, end) {
1262                 // ...and the start index is greater than the end index,
1263                 // this loop will never run. This is often confusing for developers
1264                 // who think that this will iterate from the larger value to the
1265                 // smaller value.
1266                 let ty = cx.tables.expr_ty(start);
1267                 let (sup, eq) = match (start_idx, end_idx) {
1268                     (Constant::Int(start_idx), Constant::Int(end_idx)) => (
1269                         match ty.kind {
1270                             ty::Int(ity) => sext(cx.tcx, start_idx, ity) > sext(cx.tcx, end_idx, ity),
1271                             ty::Uint(_) => start_idx > end_idx,
1272                             _ => false,
1273                         },
1274                         start_idx == end_idx,
1275                     ),
1276                     _ => (false, false),
1277                 };
1278
1279                 if sup {
1280                     let start_snippet = snippet(cx, start.span, "_");
1281                     let end_snippet = snippet(cx, end.span, "_");
1282                     let dots = if limits == ast::RangeLimits::Closed {
1283                         "..="
1284                     } else {
1285                         ".."
1286                     };
1287
1288                     span_lint_and_then(
1289                         cx,
1290                         REVERSE_RANGE_LOOP,
1291                         expr.span,
1292                         "this range is empty so this for loop will never run",
1293                         |diag| {
1294                             diag.span_suggestion(
1295                                 arg.span,
1296                                 "consider using the following if you are attempting to iterate over this \
1297                                  range in reverse",
1298                                 format!(
1299                                     "({end}{dots}{start}).rev()",
1300                                     end = end_snippet,
1301                                     dots = dots,
1302                                     start = start_snippet
1303                                 ),
1304                                 Applicability::MaybeIncorrect,
1305                             );
1306                         },
1307                     );
1308                 } else if eq && limits != ast::RangeLimits::Closed {
1309                     // if they are equal, it's also problematic - this loop
1310                     // will never run.
1311                     span_lint(
1312                         cx,
1313                         REVERSE_RANGE_LOOP,
1314                         expr.span,
1315                         "this range is empty so this for loop will never run",
1316                     );
1317                 }
1318             }
1319         }
1320     }
1321 }
1322
1323 fn lint_iter_method(cx: &LateContext<'_, '_>, args: &[Expr<'_>], arg: &Expr<'_>, method_name: &str) {
1324     let mut applicability = Applicability::MachineApplicable;
1325     let object = snippet_with_applicability(cx, args[0].span, "_", &mut applicability);
1326     let muta = if method_name == "iter_mut" { "mut " } else { "" };
1327     span_lint_and_sugg(
1328         cx,
1329         EXPLICIT_ITER_LOOP,
1330         arg.span,
1331         "it is more concise to loop over references to containers instead of using explicit \
1332          iteration methods",
1333         "to write this more concisely, try",
1334         format!("&{}{}", muta, object),
1335         applicability,
1336     )
1337 }
1338
1339 fn check_for_loop_arg(cx: &LateContext<'_, '_>, pat: &Pat<'_>, arg: &Expr<'_>, expr: &Expr<'_>) {
1340     let mut next_loop_linted = false; // whether or not ITER_NEXT_LOOP lint was used
1341     if let ExprKind::MethodCall(ref method, _, ref args) = arg.kind {
1342         // just the receiver, no arguments
1343         if args.len() == 1 {
1344             let method_name = &*method.ident.as_str();
1345             // check for looping over x.iter() or x.iter_mut(), could use &x or &mut x
1346             if method_name == "iter" || method_name == "iter_mut" {
1347                 if is_ref_iterable_type(cx, &args[0]) {
1348                     lint_iter_method(cx, args, arg, method_name);
1349                 }
1350             } else if method_name == "into_iter" && match_trait_method(cx, arg, &paths::INTO_ITERATOR) {
1351                 let receiver_ty = cx.tables.expr_ty(&args[0]);
1352                 let receiver_ty_adjusted = cx.tables.expr_ty_adjusted(&args[0]);
1353                 if same_tys(cx, receiver_ty, receiver_ty_adjusted) {
1354                     let mut applicability = Applicability::MachineApplicable;
1355                     let object = snippet_with_applicability(cx, args[0].span, "_", &mut applicability);
1356                     span_lint_and_sugg(
1357                         cx,
1358                         EXPLICIT_INTO_ITER_LOOP,
1359                         arg.span,
1360                         "it is more concise to loop over containers instead of using explicit \
1361                          iteration methods",
1362                         "to write this more concisely, try",
1363                         object.to_string(),
1364                         applicability,
1365                     );
1366                 } else {
1367                     let ref_receiver_ty = cx.tcx.mk_ref(
1368                         cx.tcx.lifetimes.re_erased,
1369                         ty::TypeAndMut {
1370                             ty: receiver_ty,
1371                             mutbl: Mutability::Not,
1372                         },
1373                     );
1374                     if same_tys(cx, receiver_ty_adjusted, ref_receiver_ty) {
1375                         lint_iter_method(cx, args, arg, method_name)
1376                     }
1377                 }
1378             } else if method_name == "next" && match_trait_method(cx, arg, &paths::ITERATOR) {
1379                 span_lint(
1380                     cx,
1381                     ITER_NEXT_LOOP,
1382                     expr.span,
1383                     "you are iterating over `Iterator::next()` which is an Option; this will compile but is \
1384                      probably not what you want",
1385                 );
1386                 next_loop_linted = true;
1387             }
1388         }
1389     }
1390     if !next_loop_linted {
1391         check_arg_type(cx, pat, arg);
1392     }
1393 }
1394
1395 /// Checks for `for` loops over `Option`s and `Result`s.
1396 fn check_arg_type(cx: &LateContext<'_, '_>, pat: &Pat<'_>, arg: &Expr<'_>) {
1397     let ty = cx.tables.expr_ty(arg);
1398     if is_type_diagnostic_item(cx, ty, sym!(option_type)) {
1399         span_lint_and_help(
1400             cx,
1401             FOR_LOOP_OVER_OPTION,
1402             arg.span,
1403             &format!(
1404                 "for loop over `{0}`, which is an `Option`. This is more readably written as an \
1405                  `if let` statement.",
1406                 snippet(cx, arg.span, "_")
1407             ),
1408             None,
1409             &format!(
1410                 "consider replacing `for {0} in {1}` with `if let Some({0}) = {1}`",
1411                 snippet(cx, pat.span, "_"),
1412                 snippet(cx, arg.span, "_")
1413             ),
1414         );
1415     } else if is_type_diagnostic_item(cx, ty, sym!(result_type)) {
1416         span_lint_and_help(
1417             cx,
1418             FOR_LOOP_OVER_RESULT,
1419             arg.span,
1420             &format!(
1421                 "for loop over `{0}`, which is a `Result`. This is more readably written as an \
1422                  `if let` statement.",
1423                 snippet(cx, arg.span, "_")
1424             ),
1425             None,
1426             &format!(
1427                 "consider replacing `for {0} in {1}` with `if let Ok({0}) = {1}`",
1428                 snippet(cx, pat.span, "_"),
1429                 snippet(cx, arg.span, "_")
1430             ),
1431         );
1432     }
1433 }
1434
1435 fn check_for_loop_explicit_counter<'a, 'tcx>(
1436     cx: &LateContext<'a, 'tcx>,
1437     pat: &'tcx Pat<'_>,
1438     arg: &'tcx Expr<'_>,
1439     body: &'tcx Expr<'_>,
1440     expr: &'tcx Expr<'_>,
1441 ) {
1442     // Look for variables that are incremented once per loop iteration.
1443     let mut visitor = IncrementVisitor {
1444         cx,
1445         states: FxHashMap::default(),
1446         depth: 0,
1447         done: false,
1448     };
1449     walk_expr(&mut visitor, body);
1450
1451     // For each candidate, check the parent block to see if
1452     // it's initialized to zero at the start of the loop.
1453     if let Some(block) = get_enclosing_block(&cx, expr.hir_id) {
1454         for (id, _) in visitor.states.iter().filter(|&(_, v)| *v == VarState::IncrOnce) {
1455             let mut visitor2 = InitializeVisitor {
1456                 cx,
1457                 end_expr: expr,
1458                 var_id: *id,
1459                 state: VarState::IncrOnce,
1460                 name: None,
1461                 depth: 0,
1462                 past_loop: false,
1463             };
1464             walk_block(&mut visitor2, block);
1465
1466             if visitor2.state == VarState::Warn {
1467                 if let Some(name) = visitor2.name {
1468                     let mut applicability = Applicability::MachineApplicable;
1469
1470                     // for some reason this is the only way to get the `Span`
1471                     // of the entire `for` loop
1472                     let for_span = if let ExprKind::Match(_, arms, _) = &expr.kind {
1473                         arms[0].body.span
1474                     } else {
1475                         unreachable!()
1476                     };
1477
1478                     span_lint_and_sugg(
1479                         cx,
1480                         EXPLICIT_COUNTER_LOOP,
1481                         for_span.with_hi(arg.span.hi()),
1482                         &format!("the variable `{}` is used as a loop counter.", name),
1483                         "consider using",
1484                         format!(
1485                             "for ({}, {}) in {}.enumerate()",
1486                             name,
1487                             snippet_with_applicability(cx, pat.span, "item", &mut applicability),
1488                             make_iterator_snippet(cx, arg, &mut applicability),
1489                         ),
1490                         applicability,
1491                     );
1492                 }
1493             }
1494         }
1495     }
1496 }
1497
1498 /// If `arg` was the argument to a `for` loop, return the "cleanest" way of writing the
1499 /// actual `Iterator` that the loop uses.
1500 fn make_iterator_snippet(cx: &LateContext<'_, '_>, arg: &Expr<'_>, applic_ref: &mut Applicability) -> String {
1501     let impls_iterator = get_trait_def_id(cx, &paths::ITERATOR)
1502         .map_or(false, |id| implements_trait(cx, cx.tables.expr_ty(arg), id, &[]));
1503     if impls_iterator {
1504         format!(
1505             "{}",
1506             sugg::Sugg::hir_with_applicability(cx, arg, "_", applic_ref).maybe_par()
1507         )
1508     } else {
1509         // (&x).into_iter() ==> x.iter()
1510         // (&mut x).into_iter() ==> x.iter_mut()
1511         match &arg.kind {
1512             ExprKind::AddrOf(BorrowKind::Ref, mutability, arg_inner)
1513                 if has_iter_method(cx, cx.tables.expr_ty(&arg_inner)).is_some() =>
1514             {
1515                 let meth_name = match mutability {
1516                     Mutability::Mut => "iter_mut",
1517                     Mutability::Not => "iter",
1518                 };
1519                 format!(
1520                     "{}.{}()",
1521                     sugg::Sugg::hir_with_applicability(cx, &arg_inner, "_", applic_ref).maybe_par(),
1522                     meth_name,
1523                 )
1524             }
1525             _ => format!(
1526                 "{}.into_iter()",
1527                 sugg::Sugg::hir_with_applicability(cx, arg, "_", applic_ref).maybe_par()
1528             ),
1529         }
1530     }
1531 }
1532
1533 /// Checks for the `FOR_KV_MAP` lint.
1534 fn check_for_loop_over_map_kv<'a, 'tcx>(
1535     cx: &LateContext<'a, 'tcx>,
1536     pat: &'tcx Pat<'_>,
1537     arg: &'tcx Expr<'_>,
1538     body: &'tcx Expr<'_>,
1539     expr: &'tcx Expr<'_>,
1540 ) {
1541     let pat_span = pat.span;
1542
1543     if let PatKind::Tuple(ref pat, _) = pat.kind {
1544         if pat.len() == 2 {
1545             let arg_span = arg.span;
1546             let (new_pat_span, kind, ty, mutbl) = match cx.tables.expr_ty(arg).kind {
1547                 ty::Ref(_, ty, mutbl) => match (&pat[0].kind, &pat[1].kind) {
1548                     (key, _) if pat_is_wild(key, body) => (pat[1].span, "value", ty, mutbl),
1549                     (_, value) if pat_is_wild(value, body) => (pat[0].span, "key", ty, Mutability::Not),
1550                     _ => return,
1551                 },
1552                 _ => return,
1553             };
1554             let mutbl = match mutbl {
1555                 Mutability::Not => "",
1556                 Mutability::Mut => "_mut",
1557             };
1558             let arg = match arg.kind {
1559                 ExprKind::AddrOf(BorrowKind::Ref, _, ref expr) => &**expr,
1560                 _ => arg,
1561             };
1562
1563             if is_type_diagnostic_item(cx, ty, sym!(hashmap_type)) || match_type(cx, ty, &paths::BTREEMAP) {
1564                 span_lint_and_then(
1565                     cx,
1566                     FOR_KV_MAP,
1567                     expr.span,
1568                     &format!("you seem to want to iterate on a map's {}s", kind),
1569                     |diag| {
1570                         let map = sugg::Sugg::hir(cx, arg, "map");
1571                         multispan_sugg(
1572                             diag,
1573                             "use the corresponding method".into(),
1574                             vec![
1575                                 (pat_span, snippet(cx, new_pat_span, kind).into_owned()),
1576                                 (arg_span, format!("{}.{}s{}()", map.maybe_par(), kind, mutbl)),
1577                             ],
1578                         );
1579                     },
1580                 );
1581             }
1582         }
1583     }
1584 }
1585
1586 struct MutatePairDelegate {
1587     hir_id_low: Option<HirId>,
1588     hir_id_high: Option<HirId>,
1589     span_low: Option<Span>,
1590     span_high: Option<Span>,
1591 }
1592
1593 impl<'tcx> Delegate<'tcx> for MutatePairDelegate {
1594     fn consume(&mut self, _: &Place<'tcx>, _: ConsumeMode) {}
1595
1596     fn borrow(&mut self, cmt: &Place<'tcx>, bk: ty::BorrowKind) {
1597         if let ty::BorrowKind::MutBorrow = bk {
1598             if let PlaceBase::Local(id) = cmt.base {
1599                 if Some(id) == self.hir_id_low {
1600                     self.span_low = Some(cmt.span)
1601                 }
1602                 if Some(id) == self.hir_id_high {
1603                     self.span_high = Some(cmt.span)
1604                 }
1605             }
1606         }
1607     }
1608
1609     fn mutate(&mut self, cmt: &Place<'tcx>) {
1610         if let PlaceBase::Local(id) = cmt.base {
1611             if Some(id) == self.hir_id_low {
1612                 self.span_low = Some(cmt.span)
1613             }
1614             if Some(id) == self.hir_id_high {
1615                 self.span_high = Some(cmt.span)
1616             }
1617         }
1618     }
1619 }
1620
1621 impl<'tcx> MutatePairDelegate {
1622     fn mutation_span(&self) -> (Option<Span>, Option<Span>) {
1623         (self.span_low, self.span_high)
1624     }
1625 }
1626
1627 fn check_for_mut_range_bound(cx: &LateContext<'_, '_>, arg: &Expr<'_>, body: &Expr<'_>) {
1628     if let Some(higher::Range {
1629         start: Some(start),
1630         end: Some(end),
1631         ..
1632     }) = higher::range(cx, arg)
1633     {
1634         let mut_ids = vec![check_for_mutability(cx, start), check_for_mutability(cx, end)];
1635         if mut_ids[0].is_some() || mut_ids[1].is_some() {
1636             let (span_low, span_high) = check_for_mutation(cx, body, &mut_ids);
1637             mut_warn_with_span(cx, span_low);
1638             mut_warn_with_span(cx, span_high);
1639         }
1640     }
1641 }
1642
1643 fn mut_warn_with_span(cx: &LateContext<'_, '_>, span: Option<Span>) {
1644     if let Some(sp) = span {
1645         span_lint(
1646             cx,
1647             MUT_RANGE_BOUND,
1648             sp,
1649             "attempt to mutate range bound within loop; note that the range of the loop is unchanged",
1650         );
1651     }
1652 }
1653
1654 fn check_for_mutability(cx: &LateContext<'_, '_>, bound: &Expr<'_>) -> Option<HirId> {
1655     if_chain! {
1656         if let ExprKind::Path(ref qpath) = bound.kind;
1657         if let QPath::Resolved(None, _) = *qpath;
1658         then {
1659             let res = qpath_res(cx, qpath, bound.hir_id);
1660             if let Res::Local(hir_id) = res {
1661                 let node_str = cx.tcx.hir().get(hir_id);
1662                 if_chain! {
1663                     if let Node::Binding(pat) = node_str;
1664                     if let PatKind::Binding(bind_ann, ..) = pat.kind;
1665                     if let BindingAnnotation::Mutable = bind_ann;
1666                     then {
1667                         return Some(hir_id);
1668                     }
1669                 }
1670             }
1671         }
1672     }
1673     None
1674 }
1675
1676 fn check_for_mutation(
1677     cx: &LateContext<'_, '_>,
1678     body: &Expr<'_>,
1679     bound_ids: &[Option<HirId>],
1680 ) -> (Option<Span>, Option<Span>) {
1681     let mut delegate = MutatePairDelegate {
1682         hir_id_low: bound_ids[0],
1683         hir_id_high: bound_ids[1],
1684         span_low: None,
1685         span_high: None,
1686     };
1687     let def_id = body.hir_id.owner.to_def_id();
1688     cx.tcx.infer_ctxt().enter(|infcx| {
1689         ExprUseVisitor::new(&mut delegate, &infcx, def_id.expect_local(), cx.param_env, cx.tables).walk_expr(body);
1690     });
1691     delegate.mutation_span()
1692 }
1693
1694 /// Returns `true` if the pattern is a `PatWild` or an ident prefixed with `_`.
1695 fn pat_is_wild<'tcx>(pat: &'tcx PatKind<'_>, body: &'tcx Expr<'_>) -> bool {
1696     match *pat {
1697         PatKind::Wild => true,
1698         PatKind::Binding(.., ident, None) if ident.as_str().starts_with('_') => is_unused(&ident, body),
1699         _ => false,
1700     }
1701 }
1702
1703 struct LocalUsedVisitor<'a, 'tcx> {
1704     cx: &'a LateContext<'a, 'tcx>,
1705     local: HirId,
1706     used: bool,
1707 }
1708
1709 impl<'a, 'tcx> Visitor<'tcx> for LocalUsedVisitor<'a, 'tcx> {
1710     type Map = Map<'tcx>;
1711
1712     fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
1713         if same_var(self.cx, expr, self.local) {
1714             self.used = true;
1715         } else {
1716             walk_expr(self, expr);
1717         }
1718     }
1719
1720     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
1721         NestedVisitorMap::None
1722     }
1723 }
1724
1725 struct VarVisitor<'a, 'tcx> {
1726     /// context reference
1727     cx: &'a LateContext<'a, 'tcx>,
1728     /// var name to look for as index
1729     var: HirId,
1730     /// indexed variables that are used mutably
1731     indexed_mut: FxHashSet<Name>,
1732     /// indirectly indexed variables (`v[(i + 4) % N]`), the extend is `None` for global
1733     indexed_indirectly: FxHashMap<Name, Option<region::Scope>>,
1734     /// subset of `indexed` of vars that are indexed directly: `v[i]`
1735     /// this will not contain cases like `v[calc_index(i)]` or `v[(i + 4) % N]`
1736     indexed_directly: FxHashMap<Name, (Option<region::Scope>, Ty<'tcx>)>,
1737     /// Any names that are used outside an index operation.
1738     /// Used to detect things like `&mut vec` used together with `vec[i]`
1739     referenced: FxHashSet<Name>,
1740     /// has the loop variable been used in expressions other than the index of
1741     /// an index op?
1742     nonindex: bool,
1743     /// Whether we are inside the `$` in `&mut $` or `$ = foo` or `$.bar`, where bar
1744     /// takes `&mut self`
1745     prefer_mutable: bool,
1746 }
1747
1748 impl<'a, 'tcx> VarVisitor<'a, 'tcx> {
1749     fn check(&mut self, idx: &'tcx Expr<'_>, seqexpr: &'tcx Expr<'_>, expr: &'tcx Expr<'_>) -> bool {
1750         if_chain! {
1751             // the indexed container is referenced by a name
1752             if let ExprKind::Path(ref seqpath) = seqexpr.kind;
1753             if let QPath::Resolved(None, ref seqvar) = *seqpath;
1754             if seqvar.segments.len() == 1;
1755             then {
1756                 let index_used_directly = same_var(self.cx, idx, self.var);
1757                 let indexed_indirectly = {
1758                     let mut used_visitor = LocalUsedVisitor {
1759                         cx: self.cx,
1760                         local: self.var,
1761                         used: false,
1762                     };
1763                     walk_expr(&mut used_visitor, idx);
1764                     used_visitor.used
1765                 };
1766
1767                 if indexed_indirectly || index_used_directly {
1768                     if self.prefer_mutable {
1769                         self.indexed_mut.insert(seqvar.segments[0].ident.name);
1770                     }
1771                     let res = qpath_res(self.cx, seqpath, seqexpr.hir_id);
1772                     match res {
1773                         Res::Local(hir_id) => {
1774                             let parent_id = self.cx.tcx.hir().get_parent_item(expr.hir_id);
1775                             let parent_def_id = self.cx.tcx.hir().local_def_id(parent_id);
1776                             let extent = self.cx.tcx.region_scope_tree(parent_def_id).var_scope(hir_id.local_id);
1777                             if indexed_indirectly {
1778                                 self.indexed_indirectly.insert(seqvar.segments[0].ident.name, Some(extent));
1779                             }
1780                             if index_used_directly {
1781                                 self.indexed_directly.insert(
1782                                     seqvar.segments[0].ident.name,
1783                                     (Some(extent), self.cx.tables.node_type(seqexpr.hir_id)),
1784                                 );
1785                             }
1786                             return false;  // no need to walk further *on the variable*
1787                         }
1788                         Res::Def(DefKind::Static | DefKind::Const, ..) => {
1789                             if indexed_indirectly {
1790                                 self.indexed_indirectly.insert(seqvar.segments[0].ident.name, None);
1791                             }
1792                             if index_used_directly {
1793                                 self.indexed_directly.insert(
1794                                     seqvar.segments[0].ident.name,
1795                                     (None, self.cx.tables.node_type(seqexpr.hir_id)),
1796                                 );
1797                             }
1798                             return false;  // no need to walk further *on the variable*
1799                         }
1800                         _ => (),
1801                     }
1802                 }
1803             }
1804         }
1805         true
1806     }
1807 }
1808
1809 impl<'a, 'tcx> Visitor<'tcx> for VarVisitor<'a, 'tcx> {
1810     type Map = Map<'tcx>;
1811
1812     fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
1813         if_chain! {
1814             // a range index op
1815             if let ExprKind::MethodCall(ref meth, _, ref args) = expr.kind;
1816             if (meth.ident.name == sym!(index) && match_trait_method(self.cx, expr, &paths::INDEX))
1817                 || (meth.ident.name == sym!(index_mut) && match_trait_method(self.cx, expr, &paths::INDEX_MUT));
1818             if !self.check(&args[1], &args[0], expr);
1819             then { return }
1820         }
1821
1822         if_chain! {
1823             // an index op
1824             if let ExprKind::Index(ref seqexpr, ref idx) = expr.kind;
1825             if !self.check(idx, seqexpr, expr);
1826             then { return }
1827         }
1828
1829         if_chain! {
1830             // directly using a variable
1831             if let ExprKind::Path(ref qpath) = expr.kind;
1832             if let QPath::Resolved(None, ref path) = *qpath;
1833             if path.segments.len() == 1;
1834             then {
1835                 if let Res::Local(local_id) = qpath_res(self.cx, qpath, expr.hir_id) {
1836                     if local_id == self.var {
1837                         self.nonindex = true;
1838                     } else {
1839                         // not the correct variable, but still a variable
1840                         self.referenced.insert(path.segments[0].ident.name);
1841                     }
1842                 }
1843             }
1844         }
1845
1846         let old = self.prefer_mutable;
1847         match expr.kind {
1848             ExprKind::AssignOp(_, ref lhs, ref rhs) | ExprKind::Assign(ref lhs, ref rhs, _) => {
1849                 self.prefer_mutable = true;
1850                 self.visit_expr(lhs);
1851                 self.prefer_mutable = false;
1852                 self.visit_expr(rhs);
1853             },
1854             ExprKind::AddrOf(BorrowKind::Ref, mutbl, ref expr) => {
1855                 if mutbl == Mutability::Mut {
1856                     self.prefer_mutable = true;
1857                 }
1858                 self.visit_expr(expr);
1859             },
1860             ExprKind::Call(ref f, args) => {
1861                 self.visit_expr(f);
1862                 for expr in args {
1863                     let ty = self.cx.tables.expr_ty_adjusted(expr);
1864                     self.prefer_mutable = false;
1865                     if let ty::Ref(_, _, mutbl) = ty.kind {
1866                         if mutbl == Mutability::Mut {
1867                             self.prefer_mutable = true;
1868                         }
1869                     }
1870                     self.visit_expr(expr);
1871                 }
1872             },
1873             ExprKind::MethodCall(_, _, args) => {
1874                 let def_id = self.cx.tables.type_dependent_def_id(expr.hir_id).unwrap();
1875                 for (ty, expr) in self.cx.tcx.fn_sig(def_id).inputs().skip_binder().iter().zip(args) {
1876                     self.prefer_mutable = false;
1877                     if let ty::Ref(_, _, mutbl) = ty.kind {
1878                         if mutbl == Mutability::Mut {
1879                             self.prefer_mutable = true;
1880                         }
1881                     }
1882                     self.visit_expr(expr);
1883                 }
1884             },
1885             ExprKind::Closure(_, _, body_id, ..) => {
1886                 let body = self.cx.tcx.hir().body(body_id);
1887                 self.visit_expr(&body.value);
1888             },
1889             _ => walk_expr(self, expr),
1890         }
1891         self.prefer_mutable = old;
1892     }
1893     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
1894         NestedVisitorMap::None
1895     }
1896 }
1897
1898 fn is_used_inside<'a, 'tcx>(cx: &'a LateContext<'a, 'tcx>, expr: &'tcx Expr<'_>, container: &'tcx Expr<'_>) -> bool {
1899     let def_id = match var_def_id(cx, expr) {
1900         Some(id) => id,
1901         None => return false,
1902     };
1903     if let Some(used_mutably) = mutated_variables(container, cx) {
1904         if used_mutably.contains(&def_id) {
1905             return true;
1906         }
1907     }
1908     false
1909 }
1910
1911 fn is_iterator_used_after_while_let<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, iter_expr: &'tcx Expr<'_>) -> bool {
1912     let def_id = match var_def_id(cx, iter_expr) {
1913         Some(id) => id,
1914         None => return false,
1915     };
1916     let mut visitor = VarUsedAfterLoopVisitor {
1917         cx,
1918         def_id,
1919         iter_expr_id: iter_expr.hir_id,
1920         past_while_let: false,
1921         var_used_after_while_let: false,
1922     };
1923     if let Some(enclosing_block) = get_enclosing_block(cx, def_id) {
1924         walk_block(&mut visitor, enclosing_block);
1925     }
1926     visitor.var_used_after_while_let
1927 }
1928
1929 struct VarUsedAfterLoopVisitor<'a, 'tcx> {
1930     cx: &'a LateContext<'a, 'tcx>,
1931     def_id: HirId,
1932     iter_expr_id: HirId,
1933     past_while_let: bool,
1934     var_used_after_while_let: bool,
1935 }
1936
1937 impl<'a, 'tcx> Visitor<'tcx> for VarUsedAfterLoopVisitor<'a, 'tcx> {
1938     type Map = Map<'tcx>;
1939
1940     fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
1941         if self.past_while_let {
1942             if Some(self.def_id) == var_def_id(self.cx, expr) {
1943                 self.var_used_after_while_let = true;
1944             }
1945         } else if self.iter_expr_id == expr.hir_id {
1946             self.past_while_let = true;
1947         }
1948         walk_expr(self, expr);
1949     }
1950     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
1951         NestedVisitorMap::None
1952     }
1953 }
1954
1955 /// Returns `true` if the type of expr is one that provides `IntoIterator` impls
1956 /// for `&T` and `&mut T`, such as `Vec`.
1957 #[rustfmt::skip]
1958 fn is_ref_iterable_type(cx: &LateContext<'_, '_>, e: &Expr<'_>) -> bool {
1959     // no walk_ptrs_ty: calling iter() on a reference can make sense because it
1960     // will allow further borrows afterwards
1961     let ty = cx.tables.expr_ty(e);
1962     is_iterable_array(ty, cx) ||
1963     is_type_diagnostic_item(cx, ty, sym!(vec_type)) ||
1964     match_type(cx, ty, &paths::LINKED_LIST) ||
1965     is_type_diagnostic_item(cx, ty, sym!(hashmap_type)) ||
1966     is_type_diagnostic_item(cx, ty, sym!(hashset_type)) ||
1967     is_type_diagnostic_item(cx, ty, sym!(vecdeque_type)) ||
1968     match_type(cx, ty, &paths::BINARY_HEAP) ||
1969     match_type(cx, ty, &paths::BTREEMAP) ||
1970     match_type(cx, ty, &paths::BTREESET)
1971 }
1972
1973 fn is_iterable_array<'tcx>(ty: Ty<'tcx>, cx: &LateContext<'_, 'tcx>) -> bool {
1974     // IntoIterator is currently only implemented for array sizes <= 32 in rustc
1975     match ty.kind {
1976         ty::Array(_, n) => {
1977             if let Some(val) = n.try_eval_usize(cx.tcx, cx.param_env) {
1978                 (0..=32).contains(&val)
1979             } else {
1980                 false
1981             }
1982         },
1983         _ => false,
1984     }
1985 }
1986
1987 /// If a block begins with a statement (possibly a `let` binding) and has an
1988 /// expression, return it.
1989 fn extract_expr_from_first_stmt<'tcx>(block: &Block<'tcx>) -> Option<&'tcx Expr<'tcx>> {
1990     if block.stmts.is_empty() {
1991         return None;
1992     }
1993     if let StmtKind::Local(ref local) = block.stmts[0].kind {
1994         if let Some(expr) = local.init {
1995             Some(expr)
1996         } else {
1997             None
1998         }
1999     } else {
2000         None
2001     }
2002 }
2003
2004 /// If a block begins with an expression (with or without semicolon), return it.
2005 fn extract_first_expr<'tcx>(block: &Block<'tcx>) -> Option<&'tcx Expr<'tcx>> {
2006     match block.expr {
2007         Some(ref expr) if block.stmts.is_empty() => Some(expr),
2008         None if !block.stmts.is_empty() => match block.stmts[0].kind {
2009             StmtKind::Expr(ref expr) | StmtKind::Semi(ref expr) => Some(expr),
2010             StmtKind::Local(..) | StmtKind::Item(..) => None,
2011         },
2012         _ => None,
2013     }
2014 }
2015
2016 /// Returns `true` if expr contains a single break expr without destination label
2017 /// and
2018 /// passed expression. The expression may be within a block.
2019 fn is_simple_break_expr(expr: &Expr<'_>) -> bool {
2020     match expr.kind {
2021         ExprKind::Break(dest, ref passed_expr) if dest.label.is_none() && passed_expr.is_none() => true,
2022         ExprKind::Block(ref b, _) => extract_first_expr(b).map_or(false, |subexpr| is_simple_break_expr(subexpr)),
2023         _ => false,
2024     }
2025 }
2026
2027 // To trigger the EXPLICIT_COUNTER_LOOP lint, a variable must be
2028 // incremented exactly once in the loop body, and initialized to zero
2029 // at the start of the loop.
2030 #[derive(Debug, PartialEq)]
2031 enum VarState {
2032     Initial,  // Not examined yet
2033     IncrOnce, // Incremented exactly once, may be a loop counter
2034     Declared, // Declared but not (yet) initialized to zero
2035     Warn,
2036     DontWarn,
2037 }
2038
2039 /// Scan a for loop for variables that are incremented exactly once.
2040 struct IncrementVisitor<'a, 'tcx> {
2041     cx: &'a LateContext<'a, 'tcx>,      // context reference
2042     states: FxHashMap<HirId, VarState>, // incremented variables
2043     depth: u32,                         // depth of conditional expressions
2044     done: bool,
2045 }
2046
2047 impl<'a, 'tcx> Visitor<'tcx> for IncrementVisitor<'a, 'tcx> {
2048     type Map = Map<'tcx>;
2049
2050     fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
2051         if self.done {
2052             return;
2053         }
2054
2055         // If node is a variable
2056         if let Some(def_id) = var_def_id(self.cx, expr) {
2057             if let Some(parent) = get_parent_expr(self.cx, expr) {
2058                 let state = self.states.entry(def_id).or_insert(VarState::Initial);
2059
2060                 match parent.kind {
2061                     ExprKind::AssignOp(op, ref lhs, ref rhs) => {
2062                         if lhs.hir_id == expr.hir_id {
2063                             if op.node == BinOpKind::Add && is_integer_const(self.cx, rhs, 1) {
2064                                 *state = match *state {
2065                                     VarState::Initial if self.depth == 0 => VarState::IncrOnce,
2066                                     _ => VarState::DontWarn,
2067                                 };
2068                             } else {
2069                                 // Assigned some other value
2070                                 *state = VarState::DontWarn;
2071                             }
2072                         }
2073                     },
2074                     ExprKind::Assign(ref lhs, _, _) if lhs.hir_id == expr.hir_id => *state = VarState::DontWarn,
2075                     ExprKind::AddrOf(BorrowKind::Ref, mutability, _) if mutability == Mutability::Mut => {
2076                         *state = VarState::DontWarn
2077                     },
2078                     _ => (),
2079                 }
2080             }
2081         } else if is_loop(expr) || is_conditional(expr) {
2082             self.depth += 1;
2083             walk_expr(self, expr);
2084             self.depth -= 1;
2085             return;
2086         } else if let ExprKind::Continue(_) = expr.kind {
2087             self.done = true;
2088             return;
2089         }
2090         walk_expr(self, expr);
2091     }
2092     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
2093         NestedVisitorMap::None
2094     }
2095 }
2096
2097 /// Checks whether a variable is initialized to zero at the start of a loop.
2098 struct InitializeVisitor<'a, 'tcx> {
2099     cx: &'a LateContext<'a, 'tcx>, // context reference
2100     end_expr: &'tcx Expr<'tcx>,    // the for loop. Stop scanning here.
2101     var_id: HirId,
2102     state: VarState,
2103     name: Option<Name>,
2104     depth: u32, // depth of conditional expressions
2105     past_loop: bool,
2106 }
2107
2108 impl<'a, 'tcx> Visitor<'tcx> for InitializeVisitor<'a, 'tcx> {
2109     type Map = Map<'tcx>;
2110
2111     fn visit_stmt(&mut self, stmt: &'tcx Stmt<'_>) {
2112         // Look for declarations of the variable
2113         if let StmtKind::Local(ref local) = stmt.kind {
2114             if local.pat.hir_id == self.var_id {
2115                 if let PatKind::Binding(.., ident, _) = local.pat.kind {
2116                     self.name = Some(ident.name);
2117
2118                     self.state = if let Some(ref init) = local.init {
2119                         if is_integer_const(&self.cx, init, 0) {
2120                             VarState::Warn
2121                         } else {
2122                             VarState::Declared
2123                         }
2124                     } else {
2125                         VarState::Declared
2126                     }
2127                 }
2128             }
2129         }
2130         walk_stmt(self, stmt);
2131     }
2132
2133     fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
2134         if self.state == VarState::DontWarn {
2135             return;
2136         }
2137         if SpanlessEq::new(self.cx).eq_expr(&expr, self.end_expr) {
2138             self.past_loop = true;
2139             return;
2140         }
2141         // No need to visit expressions before the variable is
2142         // declared
2143         if self.state == VarState::IncrOnce {
2144             return;
2145         }
2146
2147         // If node is the desired variable, see how it's used
2148         if var_def_id(self.cx, expr) == Some(self.var_id) {
2149             if let Some(parent) = get_parent_expr(self.cx, expr) {
2150                 match parent.kind {
2151                     ExprKind::AssignOp(_, ref lhs, _) if lhs.hir_id == expr.hir_id => {
2152                         self.state = VarState::DontWarn;
2153                     },
2154                     ExprKind::Assign(ref lhs, ref rhs, _) if lhs.hir_id == expr.hir_id => {
2155                         self.state = if is_integer_const(&self.cx, rhs, 0) && self.depth == 0 {
2156                             VarState::Warn
2157                         } else {
2158                             VarState::DontWarn
2159                         }
2160                     },
2161                     ExprKind::AddrOf(BorrowKind::Ref, mutability, _) if mutability == Mutability::Mut => {
2162                         self.state = VarState::DontWarn
2163                     },
2164                     _ => (),
2165                 }
2166             }
2167
2168             if self.past_loop {
2169                 self.state = VarState::DontWarn;
2170                 return;
2171             }
2172         } else if !self.past_loop && is_loop(expr) {
2173             self.state = VarState::DontWarn;
2174             return;
2175         } else if is_conditional(expr) {
2176             self.depth += 1;
2177             walk_expr(self, expr);
2178             self.depth -= 1;
2179             return;
2180         }
2181         walk_expr(self, expr);
2182     }
2183
2184     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
2185         NestedVisitorMap::OnlyBodies(self.cx.tcx.hir())
2186     }
2187 }
2188
2189 fn var_def_id(cx: &LateContext<'_, '_>, expr: &Expr<'_>) -> Option<HirId> {
2190     if let ExprKind::Path(ref qpath) = expr.kind {
2191         let path_res = qpath_res(cx, qpath, expr.hir_id);
2192         if let Res::Local(hir_id) = path_res {
2193             return Some(hir_id);
2194         }
2195     }
2196     None
2197 }
2198
2199 fn is_loop(expr: &Expr<'_>) -> bool {
2200     match expr.kind {
2201         ExprKind::Loop(..) => true,
2202         _ => false,
2203     }
2204 }
2205
2206 fn is_conditional(expr: &Expr<'_>) -> bool {
2207     match expr.kind {
2208         ExprKind::Match(..) => true,
2209         _ => false,
2210     }
2211 }
2212
2213 fn is_nested(cx: &LateContext<'_, '_>, match_expr: &Expr<'_>, iter_expr: &Expr<'_>) -> bool {
2214     if_chain! {
2215         if let Some(loop_block) = get_enclosing_block(cx, match_expr.hir_id);
2216         let parent_node = cx.tcx.hir().get_parent_node(loop_block.hir_id);
2217         if let Some(Node::Expr(loop_expr)) = cx.tcx.hir().find(parent_node);
2218         then {
2219             return is_loop_nested(cx, loop_expr, iter_expr)
2220         }
2221     }
2222     false
2223 }
2224
2225 fn is_loop_nested(cx: &LateContext<'_, '_>, loop_expr: &Expr<'_>, iter_expr: &Expr<'_>) -> bool {
2226     let mut id = loop_expr.hir_id;
2227     let iter_name = if let Some(name) = path_name(iter_expr) {
2228         name
2229     } else {
2230         return true;
2231     };
2232     loop {
2233         let parent = cx.tcx.hir().get_parent_node(id);
2234         if parent == id {
2235             return false;
2236         }
2237         match cx.tcx.hir().find(parent) {
2238             Some(Node::Expr(expr)) => {
2239                 if let ExprKind::Loop(..) = expr.kind {
2240                     return true;
2241                 };
2242             },
2243             Some(Node::Block(block)) => {
2244                 let mut block_visitor = LoopNestVisitor {
2245                     hir_id: id,
2246                     iterator: iter_name,
2247                     nesting: Unknown,
2248                 };
2249                 walk_block(&mut block_visitor, block);
2250                 if block_visitor.nesting == RuledOut {
2251                     return false;
2252                 }
2253             },
2254             Some(Node::Stmt(_)) => (),
2255             _ => {
2256                 return false;
2257             },
2258         }
2259         id = parent;
2260     }
2261 }
2262
2263 #[derive(PartialEq, Eq)]
2264 enum Nesting {
2265     Unknown,     // no nesting detected yet
2266     RuledOut,    // the iterator is initialized or assigned within scope
2267     LookFurther, // no nesting detected, no further walk required
2268 }
2269
2270 use self::Nesting::{LookFurther, RuledOut, Unknown};
2271
2272 struct LoopNestVisitor {
2273     hir_id: HirId,
2274     iterator: Name,
2275     nesting: Nesting,
2276 }
2277
2278 impl<'tcx> Visitor<'tcx> for LoopNestVisitor {
2279     type Map = Map<'tcx>;
2280
2281     fn visit_stmt(&mut self, stmt: &'tcx Stmt<'_>) {
2282         if stmt.hir_id == self.hir_id {
2283             self.nesting = LookFurther;
2284         } else if self.nesting == Unknown {
2285             walk_stmt(self, stmt);
2286         }
2287     }
2288
2289     fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
2290         if self.nesting != Unknown {
2291             return;
2292         }
2293         if expr.hir_id == self.hir_id {
2294             self.nesting = LookFurther;
2295             return;
2296         }
2297         match expr.kind {
2298             ExprKind::Assign(ref path, _, _) | ExprKind::AssignOp(_, ref path, _) => {
2299                 if match_var(path, self.iterator) {
2300                     self.nesting = RuledOut;
2301                 }
2302             },
2303             _ => walk_expr(self, expr),
2304         }
2305     }
2306
2307     fn visit_pat(&mut self, pat: &'tcx Pat<'_>) {
2308         if self.nesting != Unknown {
2309             return;
2310         }
2311         if let PatKind::Binding(.., span_name, _) = pat.kind {
2312             if self.iterator == span_name.name {
2313                 self.nesting = RuledOut;
2314                 return;
2315             }
2316         }
2317         walk_pat(self, pat)
2318     }
2319
2320     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
2321         NestedVisitorMap::None
2322     }
2323 }
2324
2325 fn path_name(e: &Expr<'_>) -> Option<Name> {
2326     if let ExprKind::Path(QPath::Resolved(_, ref path)) = e.kind {
2327         let segments = &path.segments;
2328         if segments.len() == 1 {
2329             return Some(segments[0].ident.name);
2330         }
2331     };
2332     None
2333 }
2334
2335 fn check_infinite_loop<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, cond: &'tcx Expr<'_>, expr: &'tcx Expr<'_>) {
2336     if constant(cx, cx.tables, cond).is_some() {
2337         // A pure constant condition (e.g., `while false`) is not linted.
2338         return;
2339     }
2340
2341     let mut var_visitor = VarCollectorVisitor {
2342         cx,
2343         ids: FxHashSet::default(),
2344         def_ids: FxHashMap::default(),
2345         skip: false,
2346     };
2347     var_visitor.visit_expr(cond);
2348     if var_visitor.skip {
2349         return;
2350     }
2351     let used_in_condition = &var_visitor.ids;
2352     let no_cond_variable_mutated = if let Some(used_mutably) = mutated_variables(expr, cx) {
2353         used_in_condition.is_disjoint(&used_mutably)
2354     } else {
2355         return;
2356     };
2357     let mutable_static_in_cond = var_visitor.def_ids.iter().any(|(_, v)| *v);
2358
2359     let mut has_break_or_return_visitor = HasBreakOrReturnVisitor {
2360         has_break_or_return: false,
2361     };
2362     has_break_or_return_visitor.visit_expr(expr);
2363     let has_break_or_return = has_break_or_return_visitor.has_break_or_return;
2364
2365     if no_cond_variable_mutated && !mutable_static_in_cond {
2366         span_lint_and_then(
2367             cx,
2368             WHILE_IMMUTABLE_CONDITION,
2369             cond.span,
2370             "variables in the condition are not mutated in the loop body",
2371             |diag| {
2372                 diag.note("this may lead to an infinite or to a never running loop");
2373
2374                 if has_break_or_return {
2375                     diag.note("this loop contains `return`s or `break`s");
2376                     diag.help("rewrite it as `if cond { loop { } }`");
2377                 }
2378             },
2379         );
2380     }
2381 }
2382
2383 struct HasBreakOrReturnVisitor {
2384     has_break_or_return: bool,
2385 }
2386
2387 impl<'a, 'tcx> Visitor<'tcx> for HasBreakOrReturnVisitor {
2388     type Map = Map<'tcx>;
2389
2390     fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
2391         if self.has_break_or_return {
2392             return;
2393         }
2394
2395         match expr.kind {
2396             ExprKind::Ret(_) | ExprKind::Break(_, _) => {
2397                 self.has_break_or_return = true;
2398                 return;
2399             },
2400             _ => {},
2401         }
2402
2403         walk_expr(self, expr);
2404     }
2405
2406     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
2407         NestedVisitorMap::None
2408     }
2409 }
2410
2411 /// Collects the set of variables in an expression
2412 /// Stops analysis if a function call is found
2413 /// Note: In some cases such as `self`, there are no mutable annotation,
2414 /// All variables definition IDs are collected
2415 struct VarCollectorVisitor<'a, 'tcx> {
2416     cx: &'a LateContext<'a, 'tcx>,
2417     ids: FxHashSet<HirId>,
2418     def_ids: FxHashMap<def_id::DefId, bool>,
2419     skip: bool,
2420 }
2421
2422 impl<'a, 'tcx> VarCollectorVisitor<'a, 'tcx> {
2423     fn insert_def_id(&mut self, ex: &'tcx Expr<'_>) {
2424         if_chain! {
2425             if let ExprKind::Path(ref qpath) = ex.kind;
2426             if let QPath::Resolved(None, _) = *qpath;
2427             let res = qpath_res(self.cx, qpath, ex.hir_id);
2428             then {
2429                 match res {
2430                     Res::Local(hir_id) => {
2431                         self.ids.insert(hir_id);
2432                     },
2433                     Res::Def(DefKind::Static, def_id) => {
2434                         let mutable = self.cx.tcx.is_mutable_static(def_id);
2435                         self.def_ids.insert(def_id, mutable);
2436                     },
2437                     _ => {},
2438                 }
2439             }
2440         }
2441     }
2442 }
2443
2444 impl<'a, 'tcx> Visitor<'tcx> for VarCollectorVisitor<'a, 'tcx> {
2445     type Map = Map<'tcx>;
2446
2447     fn visit_expr(&mut self, ex: &'tcx Expr<'_>) {
2448         match ex.kind {
2449             ExprKind::Path(_) => self.insert_def_id(ex),
2450             // If there is any function/method call… we just stop analysis
2451             ExprKind::Call(..) | ExprKind::MethodCall(..) => self.skip = true,
2452
2453             _ => walk_expr(self, ex),
2454         }
2455     }
2456
2457     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
2458         NestedVisitorMap::None
2459     }
2460 }
2461
2462 const NEEDLESS_COLLECT_MSG: &str = "avoid using `collect()` when not needed";
2463
2464 fn check_needless_collect<'a, 'tcx>(expr: &'tcx Expr<'_>, cx: &LateContext<'a, 'tcx>) {
2465     if_chain! {
2466         if let ExprKind::MethodCall(ref method, _, ref args) = expr.kind;
2467         if let ExprKind::MethodCall(ref chain_method, _, _) = args[0].kind;
2468         if chain_method.ident.name == sym!(collect) && match_trait_method(cx, &args[0], &paths::ITERATOR);
2469         if let Some(ref generic_args) = chain_method.args;
2470         if let Some(GenericArg::Type(ref ty)) = generic_args.args.get(0);
2471         then {
2472             let ty = cx.tables.node_type(ty.hir_id);
2473             if is_type_diagnostic_item(cx, ty, sym!(vec_type)) ||
2474                 is_type_diagnostic_item(cx, ty, sym!(vecdeque_type)) ||
2475                 match_type(cx, ty, &paths::BTREEMAP) ||
2476                 is_type_diagnostic_item(cx, ty, sym!(hashmap_type)) {
2477                 if method.ident.name == sym!(len) {
2478                     let span = shorten_needless_collect_span(expr);
2479                     span_lint_and_sugg(
2480                         cx,
2481                         NEEDLESS_COLLECT,
2482                         span,
2483                         NEEDLESS_COLLECT_MSG,
2484                         "replace with",
2485                         ".count()".to_string(),
2486                         Applicability::MachineApplicable,
2487                     );
2488                 }
2489                 if method.ident.name == sym!(is_empty) {
2490                     let span = shorten_needless_collect_span(expr);
2491                     span_lint_and_sugg(
2492                         cx,
2493                         NEEDLESS_COLLECT,
2494                         span,
2495                         NEEDLESS_COLLECT_MSG,
2496                         "replace with",
2497                         ".next().is_none()".to_string(),
2498                         Applicability::MachineApplicable,
2499                     );
2500                 }
2501                 if method.ident.name == sym!(contains) {
2502                     let contains_arg = snippet(cx, args[1].span, "??");
2503                     let span = shorten_needless_collect_span(expr);
2504                     span_lint_and_then(
2505                         cx,
2506                         NEEDLESS_COLLECT,
2507                         span,
2508                         NEEDLESS_COLLECT_MSG,
2509                         |diag| {
2510                             let (arg, pred) = if contains_arg.starts_with('&') {
2511                                 ("x", &contains_arg[1..])
2512                             } else {
2513                                 ("&x", &*contains_arg)
2514                             };
2515                             diag.span_suggestion(
2516                                 span,
2517                                 "replace with",
2518                                 format!(
2519                                     ".any(|{}| x == {})",
2520                                     arg, pred
2521                                 ),
2522                                 Applicability::MachineApplicable,
2523                             );
2524                         }
2525                     );
2526                 }
2527             }
2528         }
2529     }
2530 }
2531
2532 fn shorten_needless_collect_span(expr: &Expr<'_>) -> Span {
2533     if_chain! {
2534         if let ExprKind::MethodCall(_, _, ref args) = expr.kind;
2535         if let ExprKind::MethodCall(_, ref span, _) = args[0].kind;
2536         then {
2537             return expr.span.with_lo(span.lo() - BytePos(1));
2538         }
2539     }
2540     unreachable!()
2541 }