]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/loops.rs
Rustup to *rustc 1.20.0-nightly (d84693b93 2017-07-09)*
[rust.git] / clippy_lints / src / loops.rs
1 use reexport::*;
2 use rustc::hir::*;
3 use rustc::hir::def::Def;
4 use rustc::hir::def_id::DefId;
5 use rustc::hir::intravisit::{Visitor, walk_expr, walk_block, walk_decl, NestedVisitorMap};
6 use rustc::hir::map::Node::NodeBlock;
7 use rustc::lint::*;
8 use rustc::middle::const_val::ConstVal;
9 use rustc::middle::region::CodeExtent;
10 use rustc::ty::{self, Ty};
11 use rustc::ty::subst::Subst;
12 use rustc_const_eval::ConstContext;
13 use std::collections::HashMap;
14 use syntax::ast;
15 use utils::sugg;
16
17 use utils::{snippet, span_lint, get_parent_expr, match_trait_method, match_type, multispan_sugg, in_external_macro,
18             is_refutable, span_help_and_lint, is_integer_literal, get_enclosing_block, span_lint_and_then, higher,
19             last_path_segment, span_lint_and_sugg};
20 use utils::paths;
21
22 /// **What it does:** Checks for looping over the range of `0..len` of some
23 /// collection just to get the values by index.
24 ///
25 /// **Why is this bad?** Just iterating the collection itself makes the intent
26 /// more clear and is probably faster.
27 ///
28 /// **Known problems:** None.
29 ///
30 /// **Example:**
31 /// ```rust
32 /// for i in 0..vec.len() {
33 ///     println!("{}", vec[i]);
34 /// }
35 /// ```
36 declare_lint! {
37     pub NEEDLESS_RANGE_LOOP,
38     Warn,
39     "for-looping over a range of indices where an iterator over items would do"
40 }
41
42 /// **What it does:** Checks for loops on `x.iter()` where `&x` will do, and
43 /// suggests the latter.
44 ///
45 /// **Why is this bad?** Readability.
46 ///
47 /// **Known problems:** False negatives. We currently only warn on some known
48 /// types.
49 ///
50 /// **Example:**
51 /// ```rust
52 /// // with `y` a `Vec` or slice:
53 /// for x in y.iter() { .. }
54 /// ```
55 declare_lint! {
56     pub EXPLICIT_ITER_LOOP,
57     Warn,
58     "for-looping over `_.iter()` or `_.iter_mut()` when `&_` or `&mut _` would do"
59 }
60
61 /// **What it does:** Checks for loops on `y.into_iter()` where `y` will do, and
62 /// suggests the latter.
63 ///
64 /// **Why is this bad?** Readability.
65 ///
66 /// **Known problems:** None
67 ///
68 /// **Example:**
69 /// ```rust
70 /// // with `y` a `Vec` or slice:
71 /// for x in y.into_iter() { .. }
72 /// ```
73 declare_lint! {
74     pub EXPLICIT_INTO_ITER_LOOP,
75     Warn,
76     "for-looping over `_.into_iter()` when `_` would do"
77 }
78
79 /// **What it does:** Checks for loops on `x.next()`.
80 ///
81 /// **Why is this bad?** `next()` returns either `Some(value)` if there was a
82 /// value, or `None` otherwise. The insidious thing is that `Option<_>`
83 /// implements `IntoIterator`, so that possibly one value will be iterated,
84 /// leading to some hard to find bugs. No one will want to write such code
85 /// [except to win an Underhanded Rust
86 /// Contest](https://www.reddit.com/r/rust/comments/3hb0wm/underhanded_rust_contest/cu5yuhr).
87 ///
88 /// **Known problems:** None.
89 ///
90 /// **Example:**
91 /// ```rust
92 /// for x in y.next() { .. }
93 /// ```
94 declare_lint! {
95     pub ITER_NEXT_LOOP,
96     Warn,
97     "for-looping over `_.next()` which is probably not intended"
98 }
99
100 /// **What it does:** Checks for `for` loops over `Option` values.
101 ///
102 /// **Why is this bad?** Readability. This is more clearly expressed as an `if let`.
103 ///
104 /// **Known problems:** None.
105 ///
106 /// **Example:**
107 /// ```rust
108 /// for x in option { .. }
109 /// ```
110 ///
111 /// This should be
112 /// ```rust
113 /// if let Some(x) = option { .. }
114 /// ```
115 declare_lint! {
116     pub FOR_LOOP_OVER_OPTION,
117     Warn,
118     "for-looping over an `Option`, which is more clearly expressed as an `if let`"
119 }
120
121 /// **What it does:** Checks for `for` loops over `Result` values.
122 ///
123 /// **Why is this bad?** Readability. This is more clearly expressed as an `if let`.
124 ///
125 /// **Known problems:** None.
126 ///
127 /// **Example:**
128 /// ```rust
129 /// for x in result { .. }
130 /// ```
131 ///
132 /// This should be
133 /// ```rust
134 /// if let Ok(x) = result { .. }
135 /// ```
136 declare_lint! {
137     pub FOR_LOOP_OVER_RESULT,
138     Warn,
139     "for-looping over a `Result`, which is more clearly expressed as an `if let`"
140 }
141
142 /// **What it does:** Detects `loop + match` combinations that are easier
143 /// written as a `while let` loop.
144 ///
145 /// **Why is this bad?** The `while let` loop is usually shorter and more readable.
146 ///
147 /// **Known problems:** Sometimes the wrong binding is displayed (#383).
148 ///
149 /// **Example:**
150 /// ```rust
151 /// loop {
152 ///     let x = match y {
153 ///         Some(x) => x,
154 ///         None => break,
155 ///     }
156 ///     // .. do something with x
157 /// }
158 /// // is easier written as
159 /// while let Some(x) = y {
160 ///     // .. do something with x
161 /// }
162 /// ```
163 declare_lint! {
164     pub WHILE_LET_LOOP,
165     Warn,
166     "`loop { if let { ... } else break }`, which can be written as a `while let` loop"
167 }
168
169 /// **What it does:** Checks for using `collect()` on an iterator without using
170 /// the result.
171 ///
172 /// **Why is this bad?** It is more idiomatic to use a `for` loop over the
173 /// iterator instead.
174 ///
175 /// **Known problems:** None.
176 ///
177 /// **Example:**
178 /// ```rust
179 /// vec.iter().map(|x| /* some operation returning () */).collect::<Vec<_>>();
180 /// ```
181 declare_lint! {
182     pub UNUSED_COLLECT,
183     Warn,
184     "`collect()`ing an iterator without using the result; this is usually better \
185      written as a for loop"
186 }
187
188 /// **What it does:** Checks for loops over ranges `x..y` where both `x` and `y`
189 /// are constant and `x` is greater or equal to `y`, unless the range is
190 /// reversed or has a negative `.step_by(_)`.
191 ///
192 /// **Why is it bad?** Such loops will either be skipped or loop until
193 /// wrap-around (in debug code, this may `panic!()`). Both options are probably
194 /// not intended.
195 ///
196 /// **Known problems:** The lint cannot catch loops over dynamically defined
197 /// ranges. Doing this would require simulating all possible inputs and code
198 /// paths through the program, which would be complex and error-prone.
199 ///
200 /// **Example:**
201 /// ```rust
202 /// for x in 5..10-5 { .. } // oops, stray `-`
203 /// ```
204 declare_lint! {
205     pub REVERSE_RANGE_LOOP,
206     Warn,
207     "iteration over an empty range, such as `10..0` or `5..5`"
208 }
209
210 /// **What it does:** Checks `for` loops over slices with an explicit counter
211 /// and suggests the use of `.enumerate()`.
212 ///
213 /// **Why is it bad?** Not only is the version using `.enumerate()` more
214 /// readable, the compiler is able to remove bounds checks which can lead to
215 /// faster code in some instances.
216 ///
217 /// **Known problems:** None.
218 ///
219 /// **Example:**
220 /// ```rust
221 /// for i in 0..v.len() { foo(v[i]);
222 /// for i in 0..v.len() { bar(i, v[i]); }
223 /// ```
224 declare_lint! {
225     pub EXPLICIT_COUNTER_LOOP,
226     Warn,
227     "for-looping with an explicit counter when `_.enumerate()` would do"
228 }
229
230 /// **What it does:** Checks for empty `loop` expressions.
231 ///
232 /// **Why is this bad?** Those busy loops burn CPU cycles without doing
233 /// anything. Think of the environment and either block on something or at least
234 /// make the thread sleep for some microseconds.
235 ///
236 /// **Known problems:** None.
237 ///
238 /// **Example:**
239 /// ```rust
240 /// loop {}
241 /// ```
242 declare_lint! {
243     pub EMPTY_LOOP,
244     Warn,
245     "empty `loop {}`, which should block or sleep"
246 }
247
248 /// **What it does:** Checks for `while let` expressions on iterators.
249 ///
250 /// **Why is this bad?** Readability. A simple `for` loop is shorter and conveys
251 /// the intent better.
252 ///
253 /// **Known problems:** None.
254 ///
255 /// **Example:**
256 /// ```rust
257 /// while let Some(val) = iter() { .. }
258 /// ```
259 declare_lint! {
260     pub WHILE_LET_ON_ITERATOR,
261     Warn,
262     "using a while-let loop instead of a for loop on an iterator"
263 }
264
265 /// **What it does:** Checks for iterating a map (`HashMap` or `BTreeMap`) and
266 /// ignoring either the keys or values.
267 ///
268 /// **Why is this bad?** Readability. There are `keys` and `values` methods that
269 /// can be used to express that don't need the values or keys.
270 ///
271 /// **Known problems:** None.
272 ///
273 /// **Example:**
274 /// ```rust
275 /// for (k, _) in &map { .. }
276 /// ```
277 ///
278 /// could be replaced by
279 ///
280 /// ```rust
281 /// for k in map.keys() { .. }
282 /// ```
283 declare_lint! {
284     pub FOR_KV_MAP,
285     Warn,
286     "looping on a map using `iter` when `keys` or `values` would do"
287 }
288
289 /// **What it does:** Checks for loops that will always `break`, `return` or
290 /// `continue` an outer loop.
291 ///
292 /// **Why is this bad?** This loop never loops, all it does is obfuscating the
293 /// code.
294 ///
295 /// **Known problems:** None
296 ///
297 /// **Example:**
298 /// ```rust
299 /// loop { ..; break; }
300 /// ```
301 declare_lint! {
302     pub NEVER_LOOP,
303     Warn,
304     "any loop that will always `break` or `return`"
305 }
306
307 #[derive(Copy, Clone, Default)]
308 pub struct Pass {
309     loop_count : usize,
310 }
311
312 impl LintPass for Pass {
313     fn get_lints(&self) -> LintArray {
314         lint_array!(NEEDLESS_RANGE_LOOP,
315                     EXPLICIT_ITER_LOOP,
316                     EXPLICIT_INTO_ITER_LOOP,
317                     ITER_NEXT_LOOP,
318                     FOR_LOOP_OVER_RESULT,
319                     FOR_LOOP_OVER_OPTION,
320                     WHILE_LET_LOOP,
321                     UNUSED_COLLECT,
322                     REVERSE_RANGE_LOOP,
323                     EXPLICIT_COUNTER_LOOP,
324                     EMPTY_LOOP,
325                     WHILE_LET_ON_ITERATOR,
326                     FOR_KV_MAP,
327                     NEVER_LOOP)
328     }
329 }
330
331 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
332     fn check_expr_post(&mut self, _: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
333         match expr.node {
334             ExprWhile(..) | ExprLoop(..) => { self.loop_count -= 1; }
335             _ => ()
336         }
337     }
338
339     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
340         if let Some((pat, arg, body)) = higher::for_loop(expr) {
341             check_for_loop(cx, pat, arg, body, expr);
342         }
343
344         // check for never_loop
345         match expr.node {
346             ExprWhile(_, ref block, _) |
347             ExprLoop(ref block, _, _) => {
348                 self.loop_count += 1;
349                 if never_loop(block, &expr.id) {
350                     span_lint(cx, NEVER_LOOP, expr.span, "this loop never actually loops");
351                 }
352             },
353             _ => (),
354         }
355
356         // check for `loop { if let {} else break }` that could be `while let`
357         // (also matches an explicit "match" instead of "if let")
358         // (even if the "match" or "if let" is used for declaration)
359         if let ExprLoop(ref block, _, LoopSource::Loop) = expr.node {
360             // also check for empty `loop {}` statements
361             if block.stmts.is_empty() && block.expr.is_none() {
362                 span_lint(cx,
363                           EMPTY_LOOP,
364                           expr.span,
365                           "empty `loop {}` detected. You may want to either use `panic!()` or add \
366                            `std::thread::sleep(..);` to the loop body.");
367             }
368
369             // extract the expression from the first statement (if any) in a block
370             let inner_stmt_expr = extract_expr_from_first_stmt(block);
371             // or extract the first expression (if any) from the block
372             if let Some(inner) = inner_stmt_expr.or_else(|| extract_first_expr(block)) {
373                 if let ExprMatch(ref matchexpr, ref arms, ref source) = inner.node {
374                     // ensure "if let" compatible match structure
375                     match *source {
376                         MatchSource::Normal |
377                         MatchSource::IfLetDesugar { .. } => {
378                             if arms.len() == 2 && arms[0].pats.len() == 1 && arms[0].guard.is_none() &&
379                                arms[1].pats.len() == 1 && arms[1].guard.is_none() &&
380                                is_break_expr(&arms[1].body) {
381                                 if in_external_macro(cx, expr.span) {
382                                     return;
383                                 }
384
385                                 // NOTE: we used to make build a body here instead of using
386                                 // ellipsis, this was removed because:
387                                 // 1) it was ugly with big bodies;
388                                 // 2) it was not indented properly;
389                                 // 3) it wasn’t very smart (see #675).
390                                 span_lint_and_sugg(cx,
391                                                    WHILE_LET_LOOP,
392                                                    expr.span,
393                                                    "this loop could be written as a `while let` loop",
394                                                    "try",
395                                                    format!("while let {} = {} {{ .. }}",
396                                                            snippet(cx, arms[0].pats[0].span, ".."),
397                                                            snippet(cx, matchexpr.span, "..")));
398                             }
399                         },
400                         _ => (),
401                     }
402                 }
403             }
404         }
405         if let ExprMatch(ref match_expr, ref arms, MatchSource::WhileLetDesugar) = expr.node {
406             let pat = &arms[0].pats[0].node;
407             if let (&PatKind::TupleStruct(ref qpath, ref pat_args, _),
408                     &ExprMethodCall(ref method_path, _, ref method_args)) = (pat, &match_expr.node) {
409                 let iter_expr = &method_args[0];
410                 let lhs_constructor = last_path_segment(qpath);
411                 if self.loop_count < 2 && method_path.name == "next" &&
412                    match_trait_method(cx, match_expr, &paths::ITERATOR) &&
413                    lhs_constructor.name == "Some" && !is_refutable(cx, &pat_args[0]) &&
414                    !is_iterator_used_after_while_let(cx, iter_expr) {
415                     let iterator = snippet(cx, method_args[0].span, "_");
416                     let loop_var = snippet(cx, pat_args[0].span, "_");
417                     span_lint_and_sugg(cx,
418                                        WHILE_LET_ON_ITERATOR,
419                                        expr.span,
420                                        "this loop could be written as a `for` loop",
421                                        "try",
422                                        format!("for {} in {} {{ .. }}", loop_var, iterator));
423                 }
424             }
425         }
426     }
427
428     fn check_stmt(&mut self, cx: &LateContext<'a, 'tcx>, stmt: &'tcx Stmt) {
429         if let StmtSemi(ref expr, _) = stmt.node {
430             if let ExprMethodCall(ref method, _, ref args) = expr.node {
431                 if args.len() == 1 && method.name == "collect" && match_trait_method(cx, expr, &paths::ITERATOR) {
432                     span_lint(cx,
433                               UNUSED_COLLECT,
434                               expr.span,
435                               "you are collect()ing an iterator and throwing away the result. \
436                                Consider using an explicit for loop to exhaust the iterator");
437                 }
438             }
439         }
440     }
441 }
442
443 fn never_loop(block: &Block, id: &NodeId) -> bool {
444     !contains_continue_block(block, id) && loop_exit_block(block)
445 }
446
447 fn contains_continue_block(block: &Block, dest: &NodeId) -> bool {
448     block.stmts.iter().any(|e| contains_continue_stmt(e, dest)) ||
449     block.expr.as_ref().map_or(false, |e| contains_continue_expr(e, dest))
450 }
451
452 fn contains_continue_stmt(stmt: &Stmt, dest: &NodeId) -> bool {
453     match stmt.node {
454         StmtSemi(ref e, _) |
455         StmtExpr(ref e, _) => contains_continue_expr(e, dest),
456         StmtDecl(ref d, _) => contains_continue_decl(d, dest),
457     }
458 }
459
460 fn contains_continue_decl(decl: &Decl, dest: &NodeId) -> bool {
461     match decl.node {
462         DeclLocal(ref local) => local.init.as_ref().map_or(false, |e| contains_continue_expr(e, dest)),
463         _ => false,
464     }
465 }
466
467 fn contains_continue_expr(expr: &Expr, dest: &NodeId) -> bool {
468     match expr.node {
469         ExprRet(Some(ref e)) |
470         ExprBox(ref e) |
471         ExprUnary(_, ref e) |
472         ExprCast(ref e, _) |
473         ExprType(ref e, _) |
474         ExprField(ref e, _) |
475         ExprTupField(ref e, _) |
476         ExprAddrOf(_, ref e) |
477         ExprRepeat(ref e, _) => contains_continue_expr(e, dest),
478         ExprArray(ref es) |
479         ExprMethodCall(_, _, ref es) |
480         ExprTup(ref es) => es.iter().any(|e| contains_continue_expr(e, dest)),
481         ExprCall(ref e, ref es) => {
482             contains_continue_expr(e, dest) || es.iter().any(|e| contains_continue_expr(e, dest))
483         },
484         ExprBinary(_, ref e1, ref e2) |
485         ExprAssign(ref e1, ref e2) |
486         ExprAssignOp(_, ref e1, ref e2) |
487         ExprIndex(ref e1, ref e2) => [e1, e2].iter().any(|e| contains_continue_expr(e, dest)),
488         ExprIf(ref e, ref e2, ref e3) => {
489             [e, e2].iter().chain(e3.as_ref().iter()).any(|e| contains_continue_expr(e, dest))
490         },
491         ExprWhile(ref e, ref b, _) => contains_continue_expr(e, dest) || contains_continue_block(b, dest),
492         ExprMatch(ref e, ref arms, _) => {
493             contains_continue_expr(e, dest) || arms.iter().any(|a| contains_continue_expr(&a.body, dest))
494         },
495         ExprBlock(ref block) => contains_continue_block(block, dest),
496         ExprStruct(_, _, ref base) => base.as_ref().map_or(false, |e| contains_continue_expr(e, dest)),
497         ExprAgain(d) => d.target_id.opt_id().map_or(false, |id| id == *dest),
498         _ => false,
499     }
500 }
501
502 fn loop_exit_block(block: &Block) -> bool {
503     block.stmts.iter().any(|e| loop_exit_stmt(e)) || block.expr.as_ref().map_or(false, |e| loop_exit_expr(e))
504 }
505
506 fn loop_exit_stmt(stmt: &Stmt) -> bool {
507     match stmt.node {
508         StmtSemi(ref e, _) |
509         StmtExpr(ref e, _) => loop_exit_expr(e),
510         StmtDecl(ref d, _) => loop_exit_decl(d),
511     }
512 }
513
514 fn loop_exit_decl(decl: &Decl) -> bool {
515     match decl.node {
516         DeclLocal(ref local) => local.init.as_ref().map_or(false, |e| loop_exit_expr(e)),
517         _ => false,
518     }
519 }
520
521 fn loop_exit_expr(expr: &Expr) -> bool {
522     match expr.node {
523         ExprBox(ref e) |
524         ExprUnary(_, ref e) |
525         ExprCast(ref e, _) |
526         ExprType(ref e, _) |
527         ExprField(ref e, _) |
528         ExprTupField(ref e, _) |
529         ExprAddrOf(_, ref e) |
530         ExprRepeat(ref e, _) => loop_exit_expr(e),
531         ExprArray(ref es) |
532         ExprMethodCall(_, _, ref es) |
533         ExprTup(ref es) => es.iter().any(|e| loop_exit_expr(e)),
534         ExprCall(ref e, ref es) => loop_exit_expr(e) || es.iter().any(|e| loop_exit_expr(e)),
535         ExprBinary(_, ref e1, ref e2) |
536         ExprAssign(ref e1, ref e2) |
537         ExprAssignOp(_, ref e1, ref e2) |
538         ExprIndex(ref e1, ref e2) => [e1, e2].iter().any(|e| loop_exit_expr(e)),
539         ExprIf(ref e, ref e2, ref e3) => {
540             loop_exit_expr(e) || e3.as_ref().map_or(false, |e| loop_exit_expr(e)) && loop_exit_expr(e2)
541         },
542         ExprWhile(ref e, ref b, _) => loop_exit_expr(e) || loop_exit_block(b),
543         ExprMatch(ref e, ref arms, _) => loop_exit_expr(e) || arms.iter().all(|a| loop_exit_expr(&a.body)),
544         ExprBlock(ref b) => loop_exit_block(b),
545         ExprBreak(_, _) | ExprAgain(_) | ExprRet(_) => true,
546         _ => false,
547     }
548 }
549
550 fn check_for_loop<'a, 'tcx>(
551     cx: &LateContext<'a, 'tcx>,
552     pat: &'tcx Pat,
553     arg: &'tcx Expr,
554     body: &'tcx Expr,
555     expr: &'tcx Expr
556 ) {
557     check_for_loop_range(cx, pat, arg, body, expr);
558     check_for_loop_reverse_range(cx, arg, expr);
559     check_for_loop_arg(cx, pat, arg, expr);
560     check_for_loop_explicit_counter(cx, arg, body, expr);
561     check_for_loop_over_map_kv(cx, pat, arg, body, expr);
562 }
563
564 /// Check for looping over a range and then indexing a sequence with it.
565 /// The iteratee must be a range literal.
566 fn check_for_loop_range<'a, 'tcx>(
567     cx: &LateContext<'a, 'tcx>,
568     pat: &'tcx Pat,
569     arg: &'tcx Expr,
570     body: &'tcx Expr,
571     expr: &'tcx Expr
572 ) {
573     if let Some(higher::Range { start: Some(start), ref end, limits }) = higher::range(arg) {
574         // the var must be a single name
575         if let PatKind::Binding(_, def_id, ref ident, _) = pat.node {
576             let mut visitor = VarVisitor {
577                 cx: cx,
578                 var: def_id,
579                 indexed: HashMap::new(),
580                 nonindex: false,
581             };
582             walk_expr(&mut visitor, body);
583
584             // linting condition: we only indexed one variable
585             if visitor.indexed.len() == 1 {
586                 let (indexed, indexed_extent) = visitor.indexed
587                     .into_iter()
588                     .next()
589                     .unwrap_or_else(|| unreachable!() /* len == 1 */);
590
591                 // ensure that the indexed variable was declared before the loop, see #601
592                 if let Some(indexed_extent) = indexed_extent {
593                     let parent_id = cx.tcx.hir.get_parent(expr.id);
594                     let parent_def_id = cx.tcx.hir.local_def_id(parent_id);
595                     let region_maps = cx.tcx.region_maps(parent_def_id);
596                     let pat_extent = region_maps.var_scope(pat.id);
597                     if region_maps.is_subscope_of(indexed_extent, pat_extent) {
598                         return;
599                     }
600                 }
601
602                 let starts_at_zero = is_integer_literal(start, 0);
603
604                 let skip = if starts_at_zero {
605                     "".to_owned()
606                 } else {
607                     format!(".skip({})", snippet(cx, start.span, ".."))
608                 };
609
610                 let take = if let Some(end) = *end {
611                     if is_len_call(end, &indexed) {
612                         "".to_owned()
613                     } else {
614                         match limits {
615                             ast::RangeLimits::Closed => {
616                                 let end = sugg::Sugg::hir(cx, end, "<count>");
617                                 format!(".take({})", end + sugg::ONE)
618                             },
619                             ast::RangeLimits::HalfOpen => format!(".take({})", snippet(cx, end.span, "..")),
620                         }
621                     }
622                 } else {
623                     "".to_owned()
624                 };
625
626                 if visitor.nonindex {
627                     span_lint_and_then(cx,
628                                        NEEDLESS_RANGE_LOOP,
629                                        expr.span,
630                                        &format!("the loop variable `{}` is used to index `{}`", ident.node, indexed),
631                                        |db| {
632                         multispan_sugg(db,
633                                        "consider using an iterator".to_string(),
634                                        vec![(pat.span, format!("({}, <item>)", ident.node)),
635                                             (arg.span, format!("{}.iter().enumerate(){}{}", indexed, take, skip))]);
636                     });
637                 } else {
638                     let repl = if starts_at_zero && take.is_empty() {
639                         format!("&{}", indexed)
640                     } else {
641                         format!("{}.iter(){}{}", indexed, take, skip)
642                     };
643
644                     span_lint_and_then(cx,
645                                        NEEDLESS_RANGE_LOOP,
646                                        expr.span,
647                                        &format!("the loop variable `{}` is only used to index `{}`.",
648                                                 ident.node,
649                                                 indexed),
650                                        |db| {
651                         multispan_sugg(db,
652                                        "consider using an iterator".to_string(),
653                                        vec![(pat.span, "<item>".to_string()), (arg.span, repl)]);
654                     });
655                 }
656             }
657         }
658     }
659 }
660
661 fn is_len_call(expr: &Expr, var: &Name) -> bool {
662     if_let_chain! {[
663         let ExprMethodCall(ref method, _, ref len_args) = expr.node,
664         len_args.len() == 1,
665         method.name == "len",
666         let ExprPath(QPath::Resolved(_, ref path)) = len_args[0].node,
667         path.segments.len() == 1,
668         path.segments[0].name == *var
669     ], {
670         return true;
671     }}
672
673     false
674 }
675
676 fn check_for_loop_reverse_range(cx: &LateContext, arg: &Expr, expr: &Expr) {
677     // if this for loop is iterating over a two-sided range...
678     if let Some(higher::Range { start: Some(start), end: Some(end), limits }) = higher::range(arg) {
679         // ...and both sides are compile-time constant integers...
680         let constcx = ConstContext::with_tables(cx.tcx, cx.tables);
681         if let Ok(start_idx) = constcx.eval(start) {
682             if let Ok(end_idx) = constcx.eval(end) {
683                 // ...and the start index is greater than the end index,
684                 // this loop will never run. This is often confusing for developers
685                 // who think that this will iterate from the larger value to the
686                 // smaller value.
687                 let (sup, eq) = match (start_idx, end_idx) {
688                     (ConstVal::Integral(start_idx), ConstVal::Integral(end_idx)) => {
689                         (start_idx > end_idx, start_idx == end_idx)
690                     },
691                     _ => (false, false),
692                 };
693
694                 if sup {
695                     let start_snippet = snippet(cx, start.span, "_");
696                     let end_snippet = snippet(cx, end.span, "_");
697                     let dots = if limits == ast::RangeLimits::Closed {
698                         "..."
699                     } else {
700                         ".."
701                     };
702
703                     span_lint_and_then(cx,
704                                        REVERSE_RANGE_LOOP,
705                                        expr.span,
706                                        "this range is empty so this for loop will never run",
707                                        |db| {
708                         db.span_suggestion(arg.span,
709                                            "consider using the following if you are attempting to iterate over this \
710                                             range in reverse",
711                                            format!("({end}{dots}{start}).rev()",
712                                                    end = end_snippet,
713                                                    dots = dots,
714                                                    start = start_snippet));
715                     });
716                 } else if eq && limits != ast::RangeLimits::Closed {
717                     // if they are equal, it's also problematic - this loop
718                     // will never run.
719                     span_lint(cx,
720                               REVERSE_RANGE_LOOP,
721                               expr.span,
722                               "this range is empty so this for loop will never run");
723                 }
724             }
725         }
726     }
727 }
728
729 fn lint_iter_method(cx: &LateContext, args: &[Expr], arg: &Expr, method_name: &str) {
730     let object = snippet(cx, args[0].span, "_");
731     let muta = if method_name == "iter_mut" {
732         "mut "
733     } else {
734         ""
735     };
736     span_lint_and_sugg(cx,
737                        EXPLICIT_ITER_LOOP,
738                        arg.span,
739                        "it is more idiomatic to loop over references to containers instead of using explicit \
740                         iteration methods",
741                        "to write this more concisely, try",
742                        format!("&{}{}", muta, object))
743 }
744
745 fn check_for_loop_arg(cx: &LateContext, pat: &Pat, arg: &Expr, expr: &Expr) {
746     let mut next_loop_linted = false; // whether or not ITER_NEXT_LOOP lint was used
747     if let ExprMethodCall(ref method, _, ref args) = arg.node {
748         // just the receiver, no arguments
749         if args.len() == 1 {
750             let method_name = &*method.name.as_str();
751             // check for looping over x.iter() or x.iter_mut(), could use &x or &mut x
752             if method_name == "iter" || method_name == "iter_mut" {
753                 if is_ref_iterable_type(cx, &args[0]) {
754                     lint_iter_method(cx, args, arg, method_name);
755                 }
756             } else if method_name == "into_iter" && match_trait_method(cx, arg, &paths::INTO_ITERATOR) {
757                 let def_id = cx.tables.type_dependent_defs[&arg.id].def_id();
758                 let substs = cx.tables.node_substs(arg.id);
759                 let method_type = cx.tcx.type_of(def_id).subst(cx.tcx, substs);
760
761                 let fn_arg_tys = method_type.fn_sig(cx.tcx).inputs();
762                 assert_eq!(fn_arg_tys.skip_binder().len(), 1);
763                 if fn_arg_tys.skip_binder()[0].is_region_ptr() {
764                     lint_iter_method(cx, args, arg, method_name);
765                 } else {
766                     let object = snippet(cx, args[0].span, "_");
767                     span_lint_and_sugg(cx,
768                                        EXPLICIT_INTO_ITER_LOOP,
769                                        arg.span,
770                                        "it is more idiomatic to loop over containers instead of using explicit \
771                                         iteration methods`",
772                                        "to write this more concisely, try",
773                                        object.to_string());
774                 }
775             } else if method_name == "next" && match_trait_method(cx, arg, &paths::ITERATOR) {
776                 span_lint(cx,
777                           ITER_NEXT_LOOP,
778                           expr.span,
779                           "you are iterating over `Iterator::next()` which is an Option; this will compile but is \
780                            probably not what you want");
781                 next_loop_linted = true;
782             }
783         }
784     }
785     if !next_loop_linted {
786         check_arg_type(cx, pat, arg);
787     }
788 }
789
790 /// Check for `for` loops over `Option`s and `Results`
791 fn check_arg_type(cx: &LateContext, pat: &Pat, arg: &Expr) {
792     let ty = cx.tables.expr_ty(arg);
793     if match_type(cx, ty, &paths::OPTION) {
794         span_help_and_lint(cx,
795                            FOR_LOOP_OVER_OPTION,
796                            arg.span,
797                            &format!("for loop over `{0}`, which is an `Option`. This is more readably written as an \
798                                      `if let` statement.",
799                                     snippet(cx, arg.span, "_")),
800                            &format!("consider replacing `for {0} in {1}` with `if let Some({0}) = {1}`",
801                                     snippet(cx, pat.span, "_"),
802                                     snippet(cx, arg.span, "_")));
803     } else if match_type(cx, ty, &paths::RESULT) {
804         span_help_and_lint(cx,
805                            FOR_LOOP_OVER_RESULT,
806                            arg.span,
807                            &format!("for loop over `{0}`, which is a `Result`. This is more readably written as an \
808                                      `if let` statement.",
809                                     snippet(cx, arg.span, "_")),
810                            &format!("consider replacing `for {0} in {1}` with `if let Ok({0}) = {1}`",
811                                     snippet(cx, pat.span, "_"),
812                                     snippet(cx, arg.span, "_")));
813     }
814 }
815
816 fn check_for_loop_explicit_counter<'a, 'tcx>(
817     cx: &LateContext<'a, 'tcx>,
818     arg: &'tcx Expr,
819     body: &'tcx Expr,
820     expr: &'tcx Expr
821 ) {
822     // Look for variables that are incremented once per loop iteration.
823     let mut visitor = IncrementVisitor {
824         cx: cx,
825         states: HashMap::new(),
826         depth: 0,
827         done: false,
828     };
829     walk_expr(&mut visitor, body);
830
831     // For each candidate, check the parent block to see if
832     // it's initialized to zero at the start of the loop.
833     let map = &cx.tcx.hir;
834     let parent_scope = map.get_enclosing_scope(expr.id).and_then(|id| map.get_enclosing_scope(id));
835     if let Some(parent_id) = parent_scope {
836         if let NodeBlock(block) = map.get(parent_id) {
837             for (id, _) in visitor.states.iter().filter(|&(_, v)| *v == VarState::IncrOnce) {
838                 let mut visitor2 = InitializeVisitor {
839                     cx: cx,
840                     end_expr: expr,
841                     var_id: *id,
842                     state: VarState::IncrOnce,
843                     name: None,
844                     depth: 0,
845                     past_loop: false,
846                 };
847                 walk_block(&mut visitor2, block);
848
849                 if visitor2.state == VarState::Warn {
850                     if let Some(name) = visitor2.name {
851                         span_lint(cx,
852                                   EXPLICIT_COUNTER_LOOP,
853                                   expr.span,
854                                   &format!("the variable `{0}` is used as a loop counter. Consider using `for ({0}, \
855                                             item) in {1}.enumerate()` or similar iterators",
856                                            name,
857                                            snippet(cx, arg.span, "_")));
858                     }
859                 }
860             }
861         }
862     }
863 }
864
865 /// Check for the `FOR_KV_MAP` lint.
866 fn check_for_loop_over_map_kv<'a, 'tcx>(
867     cx: &LateContext<'a, 'tcx>,
868     pat: &'tcx Pat,
869     arg: &'tcx Expr,
870     body: &'tcx Expr,
871     expr: &'tcx Expr
872 ) {
873     let pat_span = pat.span;
874
875     if let PatKind::Tuple(ref pat, _) = pat.node {
876         if pat.len() == 2 {
877             let arg_span = arg.span;
878             let (new_pat_span, kind, ty, mutbl) = match cx.tables.expr_ty(arg).sty {
879                 ty::TyRef(_, ref tam) => {
880                     match (&pat[0].node, &pat[1].node) {
881                         (key, _) if pat_is_wild(key, body) => (pat[1].span, "value", tam.ty, tam.mutbl),
882                         (_, value) if pat_is_wild(value, body) => (pat[0].span, "key", tam.ty, MutImmutable),
883                         _ => return,
884                     }
885                 },
886                 _ => return,
887             };
888             let mutbl = match mutbl {
889                 MutImmutable => "",
890                 MutMutable => "_mut",
891             };
892             let arg = match arg.node {
893                 ExprAddrOf(_, ref expr) => &**expr,
894                 _ => arg,
895             };
896
897             if match_type(cx, ty, &paths::HASHMAP) || match_type(cx, ty, &paths::BTREEMAP) {
898                 span_lint_and_then(cx,
899                                    FOR_KV_MAP,
900                                    expr.span,
901                                    &format!("you seem to want to iterate on a map's {}s", kind),
902                                    |db| {
903                     let map = sugg::Sugg::hir(cx, arg, "map");
904                     multispan_sugg(db,
905                                    "use the corresponding method".into(),
906                                    vec![(pat_span, snippet(cx, new_pat_span, kind).into_owned()),
907                                         (arg_span, format!("{}.{}s{}()", map.maybe_par(), kind, mutbl))]);
908                 });
909             }
910         }
911     }
912
913 }
914
915 /// Return true if the pattern is a `PatWild` or an ident prefixed with `'_'`.
916 fn pat_is_wild<'tcx>(pat: &'tcx PatKind, body: &'tcx Expr) -> bool {
917     match *pat {
918         PatKind::Wild => true,
919         PatKind::Binding(_, _, ident, None) if ident.node.as_str().starts_with('_') => {
920             let mut visitor = UsedVisitor {
921                 var: ident.node,
922                 used: false,
923             };
924             walk_expr(&mut visitor, body);
925             !visitor.used
926         },
927         _ => false,
928     }
929 }
930
931 struct UsedVisitor {
932     var: ast::Name, // var to look for
933     used: bool, // has the var been used otherwise?
934 }
935
936 impl<'tcx> Visitor<'tcx> for UsedVisitor {
937     fn visit_expr(&mut self, expr: &'tcx Expr) {
938         if let ExprPath(QPath::Resolved(None, ref path)) = expr.node {
939             if path.segments.len() == 1 && path.segments[0].name == self.var {
940                 self.used = true;
941                 return;
942             }
943         }
944
945         walk_expr(self, expr);
946     }
947     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
948         NestedVisitorMap::None
949     }
950 }
951
952 struct VarVisitor<'a, 'tcx: 'a> {
953     cx: &'a LateContext<'a, 'tcx>, // context reference
954     var: DefId, // var name to look for as index
955     indexed: HashMap<Name, Option<CodeExtent>>, // indexed variables, the extent is None for global
956     nonindex: bool, // has the var been used otherwise?
957 }
958
959 impl<'a, 'tcx> Visitor<'tcx> for VarVisitor<'a, 'tcx> {
960     fn visit_expr(&mut self, expr: &'tcx Expr) {
961         if let ExprPath(ref qpath) = expr.node {
962             if let QPath::Resolved(None, ref path) = *qpath {
963                 if path.segments.len() == 1 && self.cx.tables.qpath_def(qpath, expr.id).def_id() == self.var {
964                     // we are referencing our variable! now check if it's as an index
965                     if_let_chain! {[
966                         let Some(parexpr) = get_parent_expr(self.cx, expr),
967                         let ExprIndex(ref seqexpr, _) = parexpr.node,
968                         let ExprPath(ref seqpath) = seqexpr.node,
969                         let QPath::Resolved(None, ref seqvar) = *seqpath,
970                         seqvar.segments.len() == 1
971                     ], {
972                         let def = self.cx.tables.qpath_def(seqpath, seqexpr.id);
973                         match def {
974                             Def::Local(..) | Def::Upvar(..) => {
975                                 let def_id = def.def_id();
976                                 let node_id = self.cx.tcx.hir.as_local_node_id(def_id).expect("local/upvar are local nodes");
977
978                                 let parent_id = self.cx.tcx.hir.get_parent(expr.id);
979                                 let parent_def_id = self.cx.tcx.hir.local_def_id(parent_id);
980                                 let extent = self.cx.tcx.region_maps(parent_def_id).var_scope(node_id);
981                                 self.indexed.insert(seqvar.segments[0].name, Some(extent));
982                                 return;  // no need to walk further
983                             }
984                             Def::Static(..) | Def::Const(..) => {
985                                 self.indexed.insert(seqvar.segments[0].name, None);
986                                 return;  // no need to walk further
987                             }
988                             _ => (),
989                         }
990                     }}
991                     // we are not indexing anything, record that
992                     self.nonindex = true;
993                     return;
994                 }
995             }
996         }
997         walk_expr(self, expr);
998     }
999     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1000         NestedVisitorMap::None
1001     }
1002 }
1003
1004 fn is_iterator_used_after_while_let<'a, 'tcx: 'a>(cx: &LateContext<'a, 'tcx>, iter_expr: &'tcx Expr) -> bool {
1005     let def_id = match var_def_id(cx, iter_expr) {
1006         Some(id) => id,
1007         None => return false,
1008     };
1009     let mut visitor = VarUsedAfterLoopVisitor {
1010         cx: cx,
1011         def_id: def_id,
1012         iter_expr_id: iter_expr.id,
1013         past_while_let: false,
1014         var_used_after_while_let: false,
1015     };
1016     if let Some(enclosing_block) = get_enclosing_block(cx, def_id) {
1017         walk_block(&mut visitor, enclosing_block);
1018     }
1019     visitor.var_used_after_while_let
1020 }
1021
1022 struct VarUsedAfterLoopVisitor<'a, 'tcx: 'a> {
1023     cx: &'a LateContext<'a, 'tcx>,
1024     def_id: NodeId,
1025     iter_expr_id: NodeId,
1026     past_while_let: bool,
1027     var_used_after_while_let: bool,
1028 }
1029
1030 impl<'a, 'tcx> Visitor<'tcx> for VarUsedAfterLoopVisitor<'a, 'tcx> {
1031     fn visit_expr(&mut self, expr: &'tcx Expr) {
1032         if self.past_while_let {
1033             if Some(self.def_id) == var_def_id(self.cx, expr) {
1034                 self.var_used_after_while_let = true;
1035             }
1036         } else if self.iter_expr_id == expr.id {
1037             self.past_while_let = true;
1038         }
1039         walk_expr(self, expr);
1040     }
1041     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1042         NestedVisitorMap::None
1043     }
1044 }
1045
1046
1047 /// Return true if the type of expr is one that provides `IntoIterator` impls
1048 /// for `&T` and `&mut T`, such as `Vec`.
1049 #[cfg_attr(rustfmt, rustfmt_skip)]
1050 fn is_ref_iterable_type(cx: &LateContext, e: &Expr) -> bool {
1051     // no walk_ptrs_ty: calling iter() on a reference can make sense because it
1052     // will allow further borrows afterwards
1053     let ty = cx.tables.expr_ty(e);
1054     is_iterable_array(ty) ||
1055     match_type(cx, ty, &paths::VEC) ||
1056     match_type(cx, ty, &paths::LINKED_LIST) ||
1057     match_type(cx, ty, &paths::HASHMAP) ||
1058     match_type(cx, ty, &paths::HASHSET) ||
1059     match_type(cx, ty, &paths::VEC_DEQUE) ||
1060     match_type(cx, ty, &paths::BINARY_HEAP) ||
1061     match_type(cx, ty, &paths::BTREEMAP) ||
1062     match_type(cx, ty, &paths::BTREESET)
1063 }
1064
1065 fn is_iterable_array(ty: Ty) -> bool {
1066     // IntoIterator is currently only implemented for array sizes <= 32 in rustc
1067     match ty.sty {
1068         ty::TyArray(_, 0...32) => true,
1069         _ => false,
1070     }
1071 }
1072
1073 /// If a block begins with a statement (possibly a `let` binding) and has an expression, return it.
1074 fn extract_expr_from_first_stmt(block: &Block) -> Option<&Expr> {
1075     if block.stmts.is_empty() {
1076         return None;
1077     }
1078     if let StmtDecl(ref decl, _) = block.stmts[0].node {
1079         if let DeclLocal(ref local) = decl.node {
1080             if let Some(ref expr) = local.init {
1081                 Some(expr)
1082             } else {
1083                 None
1084             }
1085         } else {
1086             None
1087         }
1088     } else {
1089         None
1090     }
1091 }
1092
1093 /// If a block begins with an expression (with or without semicolon), return it.
1094 fn extract_first_expr(block: &Block) -> Option<&Expr> {
1095     match block.expr {
1096         Some(ref expr) if block.stmts.is_empty() => Some(expr),
1097         None if !block.stmts.is_empty() => {
1098             match block.stmts[0].node {
1099                 StmtExpr(ref expr, _) |
1100                 StmtSemi(ref expr, _) => Some(expr),
1101                 StmtDecl(..) => None,
1102             }
1103         },
1104         _ => None,
1105     }
1106 }
1107
1108 /// Return true if expr contains a single break expr (maybe within a block).
1109 fn is_break_expr(expr: &Expr) -> bool {
1110     match expr.node {
1111         ExprBreak(dest, _) if dest.ident.is_none() => true,
1112         ExprBlock(ref b) => {
1113             match extract_first_expr(b) {
1114                 Some(subexpr) => is_break_expr(subexpr),
1115                 None => false,
1116             }
1117         },
1118         _ => false,
1119     }
1120 }
1121
1122 // To trigger the EXPLICIT_COUNTER_LOOP lint, a variable must be
1123 // incremented exactly once in the loop body, and initialized to zero
1124 // at the start of the loop.
1125 #[derive(PartialEq)]
1126 enum VarState {
1127     Initial, // Not examined yet
1128     IncrOnce, // Incremented exactly once, may be a loop counter
1129     Declared, // Declared but not (yet) initialized to zero
1130     Warn,
1131     DontWarn,
1132 }
1133
1134 /// Scan a for loop for variables that are incremented exactly once.
1135 struct IncrementVisitor<'a, 'tcx: 'a> {
1136     cx: &'a LateContext<'a, 'tcx>, // context reference
1137     states: HashMap<NodeId, VarState>, // incremented variables
1138     depth: u32, // depth of conditional expressions
1139     done: bool,
1140 }
1141
1142 impl<'a, 'tcx> Visitor<'tcx> for IncrementVisitor<'a, 'tcx> {
1143     fn visit_expr(&mut self, expr: &'tcx Expr) {
1144         if self.done {
1145             return;
1146         }
1147
1148         // If node is a variable
1149         if let Some(def_id) = var_def_id(self.cx, expr) {
1150             if let Some(parent) = get_parent_expr(self.cx, expr) {
1151                 let state = self.states.entry(def_id).or_insert(VarState::Initial);
1152
1153                 match parent.node {
1154                     ExprAssignOp(op, ref lhs, ref rhs) => {
1155                         if lhs.id == expr.id {
1156                             if op.node == BiAdd && is_integer_literal(rhs, 1) {
1157                                 *state = match *state {
1158                                     VarState::Initial if self.depth == 0 => VarState::IncrOnce,
1159                                     _ => VarState::DontWarn,
1160                                 };
1161                             } else {
1162                                 // Assigned some other value
1163                                 *state = VarState::DontWarn;
1164                             }
1165                         }
1166                     },
1167                     ExprAssign(ref lhs, _) if lhs.id == expr.id => *state = VarState::DontWarn,
1168                     ExprAddrOf(mutability, _) if mutability == MutMutable => *state = VarState::DontWarn,
1169                     _ => (),
1170                 }
1171             }
1172         } else if is_loop(expr) {
1173             self.states.clear();
1174             self.done = true;
1175             return;
1176         } else if is_conditional(expr) {
1177             self.depth += 1;
1178             walk_expr(self, expr);
1179             self.depth -= 1;
1180             return;
1181         }
1182         walk_expr(self, expr);
1183     }
1184     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1185         NestedVisitorMap::None
1186     }
1187 }
1188
1189 /// Check whether a variable is initialized to zero at the start of a loop.
1190 struct InitializeVisitor<'a, 'tcx: 'a> {
1191     cx: &'a LateContext<'a, 'tcx>, // context reference
1192     end_expr: &'tcx Expr, // the for loop. Stop scanning here.
1193     var_id: NodeId,
1194     state: VarState,
1195     name: Option<Name>,
1196     depth: u32, // depth of conditional expressions
1197     past_loop: bool,
1198 }
1199
1200 impl<'a, 'tcx> Visitor<'tcx> for InitializeVisitor<'a, 'tcx> {
1201     fn visit_decl(&mut self, decl: &'tcx Decl) {
1202         // Look for declarations of the variable
1203         if let DeclLocal(ref local) = decl.node {
1204             if local.pat.id == self.var_id {
1205                 if let PatKind::Binding(_, _, ref ident, _) = local.pat.node {
1206                     self.name = Some(ident.node);
1207
1208                     self.state = if let Some(ref init) = local.init {
1209                         if is_integer_literal(init, 0) {
1210                             VarState::Warn
1211                         } else {
1212                             VarState::Declared
1213                         }
1214                     } else {
1215                         VarState::Declared
1216                     }
1217                 }
1218             }
1219         }
1220         walk_decl(self, decl);
1221     }
1222
1223     fn visit_expr(&mut self, expr: &'tcx Expr) {
1224         if self.state == VarState::DontWarn {
1225             return;
1226         }
1227         if expr == self.end_expr {
1228             self.past_loop = true;
1229             return;
1230         }
1231         // No need to visit expressions before the variable is
1232         // declared
1233         if self.state == VarState::IncrOnce {
1234             return;
1235         }
1236
1237         // If node is the desired variable, see how it's used
1238         if var_def_id(self.cx, expr) == Some(self.var_id) {
1239             if let Some(parent) = get_parent_expr(self.cx, expr) {
1240                 match parent.node {
1241                     ExprAssignOp(_, ref lhs, _) if lhs.id == expr.id => {
1242                         self.state = VarState::DontWarn;
1243                     },
1244                     ExprAssign(ref lhs, ref rhs) if lhs.id == expr.id => {
1245                         self.state = if is_integer_literal(rhs, 0) && self.depth == 0 {
1246                             VarState::Warn
1247                         } else {
1248                             VarState::DontWarn
1249                         }
1250                     },
1251                     ExprAddrOf(mutability, _) if mutability == MutMutable => self.state = VarState::DontWarn,
1252                     _ => (),
1253                 }
1254             }
1255
1256             if self.past_loop {
1257                 self.state = VarState::DontWarn;
1258                 return;
1259             }
1260         } else if !self.past_loop && is_loop(expr) {
1261             self.state = VarState::DontWarn;
1262             return;
1263         } else if is_conditional(expr) {
1264             self.depth += 1;
1265             walk_expr(self, expr);
1266             self.depth -= 1;
1267             return;
1268         }
1269         walk_expr(self, expr);
1270     }
1271     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1272         NestedVisitorMap::None
1273     }
1274 }
1275
1276 fn var_def_id(cx: &LateContext, expr: &Expr) -> Option<NodeId> {
1277     if let ExprPath(ref qpath) = expr.node {
1278         let path_res = cx.tables.qpath_def(qpath, expr.id);
1279         if let Def::Local(def_id) = path_res {
1280             let node_id = cx.tcx.hir.as_local_node_id(def_id).expect("That DefId should be valid");
1281             return Some(node_id);
1282         }
1283     }
1284     None
1285 }
1286
1287 fn is_loop(expr: &Expr) -> bool {
1288     match expr.node {
1289         ExprLoop(..) | ExprWhile(..) => true,
1290         _ => false,
1291     }
1292 }
1293
1294 fn is_conditional(expr: &Expr) -> bool {
1295     match expr.node {
1296         ExprIf(..) | ExprMatch(..) => true,
1297         _ => false,
1298     }
1299 }