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