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