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