]> git.lizzy.rs Git - rust.git/blob - src/loops.rs
3c4e023b98e80444e9d7ec876fffb83c46830983
[rust.git] / src / loops.rs
1 use rustc::lint::*;
2 use rustc_front::hir::*;
3 use reexport::*;
4 use rustc_front::intravisit::{Visitor, walk_expr, walk_block, walk_decl};
5 use rustc::middle::ty;
6 use rustc::middle::def::DefLocal;
7 use consts::{constant_simple, Constant};
8 use rustc::front::map::Node::{NodeBlock};
9 use std::borrow::Cow;
10 use std::collections::{HashSet,HashMap};
11 use syntax::ast::Lit_::*;
12
13 use utils::{snippet, span_lint, get_parent_expr, match_trait_method, match_type,
14             in_external_macro, expr_block, span_help_and_lint, is_integer_literal,
15             get_enclosing_block};
16 use utils::{VEC_PATH, LL_PATH};
17
18 /// **What it does:** This lint checks for looping over the range of `0..len` of some collection just to get the values by index. It is `Warn` by default.
19 ///
20 /// **Why is this bad?** Just iterating the collection itself makes the intent more clear and is probably faster.
21 ///
22 /// **Known problems:** None
23 ///
24 /// **Example:**
25 /// ```
26 /// for i in 0..vec.len() {
27 ///     println!("{}", vec[i]);
28 /// }
29 /// ```
30 declare_lint!{ pub NEEDLESS_RANGE_LOOP, Warn,
31                "for-looping over a range of indices where an iterator over items would do" }
32
33 /// **What it does:** This lint checks for loops on `x.iter()` where `&x` will do, and suggest the latter. It is `Warn` by default.
34 ///
35 /// **Why is this bad?** Readability.
36 ///
37 /// **Known problems:** False negatives. We currently only warn on some known types.
38 ///
39 /// **Example:** `for x in y.iter() { .. }` (where y is a `Vec` or slice)
40 declare_lint!{ pub EXPLICIT_ITER_LOOP, Warn,
41                "for-looping over `_.iter()` or `_.iter_mut()` when `&_` or `&mut _` would do" }
42
43 /// **What it does:** This lint checks for loops on `x.next()`. It is `Warn` by default.
44 ///
45 /// **Why is this bad?** `next()` returns either `Some(value)` if there was a value, or `None` otherwise. The insidious thing is that `Option<_>` implements `IntoIterator`, so that possibly one value will be iterated, leading to some hard to find bugs. No one will want to write such code [except to win an Underhanded Rust Contest](https://www.reddit.com/r/rust/comments/3hb0wm/underhanded_rust_contest/cu5yuhr).
46 ///
47 /// **Known problems:** None
48 ///
49 /// **Example:** `for x in y.next() { .. }`
50 declare_lint!{ pub ITER_NEXT_LOOP, Warn,
51                "for-looping over `_.next()` which is probably not intended" }
52
53 /// **What it does:** This lint detects `loop + match` combinations that are easier written as a `while let` loop.
54 ///
55 /// **Why is this bad?** The `while let` loop is usually shorter and more readable
56 ///
57 /// **Known problems:** Sometimes the wrong binding is displayed (#383)
58 ///
59 /// **Example:**
60 ///
61 /// ```
62 /// loop {
63 ///     let x = match y {
64 ///         Some(x) => x,
65 ///         None => break,
66 ///     }
67 ///     // .. do something with x
68 /// }
69 /// // is easier written as
70 /// while let Some(x) = y {
71 ///     // .. do something with x
72 /// }
73 /// ```
74 declare_lint!{ pub WHILE_LET_LOOP, Warn,
75                "`loop { if let { ... } else break }` can be written as a `while let` loop" }
76
77 /// **What it does:** This lint checks for using `collect()` on an iterator without using the result. It is `Warn` by default.
78 ///
79 /// **Why is this bad?** It is more idiomatic to use a `for` loop over the iterator instead.
80 ///
81 /// **Known problems:** None
82 ///
83 /// **Example:** `vec.iter().map(|x| /* some operation returning () */).collect::<Vec<_>>();`
84 declare_lint!{ pub UNUSED_COLLECT, Warn,
85                "`collect()`ing an iterator without using the result; this is usually better \
86                 written as a for loop" }
87
88 /// **What it does:** This lint checks for loops over ranges `x..y` where both `x` and `y` are constant and `x` is greater or equal to `y`, unless the range is reversed or has a negative `.step_by(_)`.
89 ///
90 /// **Why is it bad?** Such loops will either be skipped or loop until wrap-around (in debug code, this may `panic!()`). Both options are probably not intended.
91 ///
92 /// **Known problems:** The lint cannot catch loops over dynamically defined ranges. Doing this would require simulating all possible inputs and code paths through the program, which would be complex and error-prone.
93 ///
94 /// **Examples**: `for x in 5..10-5 { .. }` (oops, stray `-`)
95 declare_lint!{ pub REVERSE_RANGE_LOOP, Warn,
96                "Iterating over an empty range, such as `10..0` or `5..5`" }
97
98 /// **What it does:** This lint checks `for` loops over slices with an explicit counter and suggests the use of `.enumerate()`. It is `Warn` by default.
99 ///
100 /// **Why is it bad?** Not only is the version using `.enumerate()` more readable, the compiler is able to remove bounds checks which can lead to faster code in some instances.
101 ///
102 /// **Known problems:** None.
103 ///
104 /// **Example:** `for i in 0..v.len() { foo(v[i]); }` or `for i in 0..v.len() { bar(i, v[i]); }`
105 declare_lint!{ pub EXPLICIT_COUNTER_LOOP, Warn,
106                "for-looping with an explicit counter when `_.enumerate()` would do" }
107
108 /// **What it does:** This lint checks for empty `loop` expressions. It is `Warn` by default.
109 ///
110 /// **Why is this bad?** Those busy loops burn CPU cycles without doing anything. Think of the environment and either block on something or at least make the thread sleep for some microseconds.
111 ///
112 /// **Known problems:** None
113 ///
114 /// **Example:** `loop {}`
115 declare_lint!{ pub EMPTY_LOOP, Warn, "empty `loop {}` detected" }
116
117 declare_lint!{ pub WHILE_LET_ON_ITERATOR, Warn, "using a while-let loop instead of a for loop on an iterator" }
118
119 #[derive(Copy, Clone)]
120 pub struct LoopsPass;
121
122 impl LintPass for LoopsPass {
123     fn get_lints(&self) -> LintArray {
124         lint_array!(NEEDLESS_RANGE_LOOP, EXPLICIT_ITER_LOOP, ITER_NEXT_LOOP,
125                     WHILE_LET_LOOP, UNUSED_COLLECT, REVERSE_RANGE_LOOP,
126                     EXPLICIT_COUNTER_LOOP, EMPTY_LOOP,
127                     WHILE_LET_ON_ITERATOR)
128     }
129 }
130
131 impl LateLintPass for LoopsPass {
132     fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
133         if let Some((pat, arg, body)) = recover_for_loop(expr) {
134             check_for_loop(cx, pat, arg, body, expr);
135         }
136         // check for `loop { if let {} else break }` that could be `while let`
137         // (also matches an explicit "match" instead of "if let")
138         // (even if the "match" or "if let" is used for declaration)
139         if let ExprLoop(ref block, _) = expr.node {
140             // also check for empty `loop {}` statements
141             if block.stmts.is_empty() && block.expr.is_none() {
142                 span_lint(cx, EMPTY_LOOP, expr.span,
143                           "empty `loop {}` detected. You may want to either \
144                            use `panic!()` or add `std::thread::sleep(..);` to \
145                            the loop body.");
146             }
147
148             // extract the expression from the first statement (if any) in a block
149             let inner_stmt_expr = extract_expr_from_first_stmt(block);
150             // extract the first expression (if any) from the block
151             let inner_expr = extract_first_expr(block);
152             let (extracted, collect_expr) = match inner_stmt_expr {
153                 Some(_) => (inner_stmt_expr, true),     // check if an expression exists in the first statement
154                 None => (inner_expr, false),    // if not, let's go for the first expression in the block
155             };
156
157             if let Some(inner) = extracted {
158                 if let ExprMatch(ref matchexpr, ref arms, ref source) = inner.node {
159                     // collect the remaining statements below the match
160                     let mut other_stuff = block.stmts
161                                   .iter()
162                                   .skip(1)
163                                   .map(|stmt| {
164                                       format!("{}", snippet(cx, stmt.span, ".."))
165                                   }).collect::<Vec<String>>();
166                     if collect_expr {           // if we have a statement which has a match,
167                         match block.expr {      // then collect the expression (without semicolon) below it
168                             Some(ref expr) => other_stuff.push(format!("{}", snippet(cx, expr.span, ".."))),
169                             None => (),
170                         }
171                     }
172
173                     // ensure "if let" compatible match structure
174                     match *source {
175                         MatchSource::Normal | MatchSource::IfLetDesugar{..} => if
176                             arms.len() == 2 &&
177                             arms[0].pats.len() == 1 && arms[0].guard.is_none() &&
178                             arms[1].pats.len() == 1 && arms[1].guard.is_none() &&
179                             // finally, check for "break" in the second clause
180                             is_break_expr(&arms[1].body)
181                         {
182                             if in_external_macro(cx, expr.span) { return; }
183                             let loop_body = match inner_stmt_expr {
184                                 // FIXME: should probably be an ellipsis
185                                 // tabbing and newline is probably a bad idea, especially for large blocks
186                                 Some(_) => Cow::Owned(format!("{{\n    {}\n}}", other_stuff.join("\n    "))),
187                                 None => expr_block(cx, &arms[0].body,
188                                                    Some(other_stuff.join("\n    ")), ".."),
189                             };
190                             span_help_and_lint(cx, WHILE_LET_LOOP, expr.span,
191                                                "this loop could be written as a `while let` loop",
192                                                &format!("try\nwhile let {} = {} {}",
193                                                         snippet(cx, arms[0].pats[0].span, ".."),
194                                                         snippet(cx, matchexpr.span, ".."),
195                                                         loop_body));
196                         },
197                         _ => ()
198                     }
199                 }
200             }
201         }
202         if let ExprMatch(ref match_expr, ref arms, MatchSource::WhileLetDesugar) = expr.node {
203             let pat = &arms[0].pats[0].node;
204             if let (&PatEnum(ref path, Some(ref pat_args)),
205                     &ExprMethodCall(method_name, _, ref method_args)) =
206                         (pat, &match_expr.node) {
207                 let iter_expr = &method_args[0];
208                 if let Some(lhs_constructor) = path.segments.last() {
209                     if method_name.node.as_str() == "next" &&
210                             match_trait_method(cx, match_expr, &["core", "iter", "Iterator"]) &&
211                             lhs_constructor.identifier.name.as_str() == "Some" &&
212                             !is_iterator_used_after_while_let(cx, iter_expr) {
213                         let iterator = snippet(cx, method_args[0].span, "_");
214                         let loop_var = snippet(cx, pat_args[0].span, "_");
215                         span_help_and_lint(cx, WHILE_LET_ON_ITERATOR, expr.span,
216                                            "this loop could be written as a `for` loop",
217                                            &format!("try\nfor {} in {} {{...}}",
218                                                     loop_var,
219                                                     iterator));
220                     }
221                 }
222             }
223         }
224     }
225
226     fn check_stmt(&mut self, cx: &LateContext, stmt: &Stmt) {
227         if let StmtSemi(ref expr, _) = stmt.node {
228             if let ExprMethodCall(ref method, _, ref args) = expr.node {
229                 if args.len() == 1 && method.node.as_str() == "collect" &&
230                         match_trait_method(cx, expr, &["core", "iter", "Iterator"]) {
231                     span_lint(cx, UNUSED_COLLECT, expr.span, &format!(
232                         "you are collect()ing an iterator and throwing away the result. \
233                          Consider using an explicit for loop to exhaust the iterator"));
234                 }
235             }
236         }
237     }
238 }
239
240 fn check_for_loop(cx: &LateContext, pat: &Pat, arg: &Expr, body: &Expr, expr: &Expr) {
241     // check for looping over a range and then indexing a sequence with it
242     // -> the iteratee must be a range literal
243     if let ExprRange(Some(ref l), _) = arg.node {
244         // Range should start with `0`
245         if let ExprLit(ref lit) = l.node {
246             if let LitInt(0, _) = lit.node {
247
248                 // the var must be a single name
249                 if let PatIdent(_, ref ident, _) = pat.node {
250                     let mut visitor = VarVisitor { cx: cx, var: ident.node.name,
251                                                    indexed: HashSet::new(), nonindex: false };
252                     walk_expr(&mut visitor, body);
253                     // linting condition: we only indexed one variable
254                     if visitor.indexed.len() == 1 {
255                         let indexed = visitor.indexed.into_iter().next().expect(
256                             "Len was nonzero, but no contents found");
257                         if visitor.nonindex {
258                             span_lint(cx, NEEDLESS_RANGE_LOOP, expr.span, &format!(
259                                 "the loop variable `{}` is used to index `{}`. Consider using \
260                                  `for ({}, item) in {}.iter().enumerate()` or similar iterators",
261                                 ident.node.name, indexed, ident.node.name, indexed));
262                         } else {
263                             span_lint(cx, NEEDLESS_RANGE_LOOP, expr.span, &format!(
264                                 "the loop variable `{}` is only used to index `{}`. \
265                                  Consider using `for item in &{}` or similar iterators",
266                                 ident.node.name, indexed, indexed));
267                         }
268                     }
269                 }
270             }
271         }
272     }
273
274     // if this for loop is iterating over a two-sided range...
275     if let ExprRange(Some(ref start_expr), Some(ref stop_expr)) = arg.node {
276         // ...and both sides are compile-time constant integers...
277         if let Some(start_idx @ Constant::ConstantInt(..)) = constant_simple(start_expr) {
278             if let Some(stop_idx @ Constant::ConstantInt(..)) = constant_simple(stop_expr) {
279                 // ...and the start index is greater than the stop index,
280                 // this loop will never run. This is often confusing for developers
281                 // who think that this will iterate from the larger value to the
282                 // smaller value.
283                 if start_idx > stop_idx {
284                     span_help_and_lint(cx, REVERSE_RANGE_LOOP, expr.span,
285                         "this range is empty so this for loop will never run",
286                         &format!("Consider using `({}..{}).rev()` if you are attempting to \
287                         iterate over this range in reverse", stop_idx, start_idx));
288                 } else if start_idx == stop_idx {
289                     // if they are equal, it's also problematic - this loop
290                     // will never run.
291                     span_lint(cx, REVERSE_RANGE_LOOP, expr.span,
292                         "this range is empty so this for loop will never run");
293                 }
294             }
295         }
296     }
297
298     if let ExprMethodCall(ref method, _, ref args) = arg.node {
299         // just the receiver, no arguments
300         if args.len() == 1 {
301             let method_name = method.node;
302             // check for looping over x.iter() or x.iter_mut(), could use &x or &mut x
303             if method_name.as_str() == "iter" || method_name.as_str() == "iter_mut" {
304                 if is_ref_iterable_type(cx, &args[0]) {
305                     let object = snippet(cx, args[0].span, "_");
306                     span_lint(cx, EXPLICIT_ITER_LOOP, expr.span, &format!(
307                         "it is more idiomatic to loop over `&{}{}` instead of `{}.{}()`",
308                         if method_name.as_str() == "iter_mut" { "mut " } else { "" },
309                         object, object, method_name));
310                 }
311             }
312             // check for looping over Iterator::next() which is not what you want
313             else if method_name.as_str() == "next" &&
314                     match_trait_method(cx, arg, &["core", "iter", "Iterator"]) {
315                 span_lint(cx, ITER_NEXT_LOOP, expr.span,
316                           "you are iterating over `Iterator::next()` which is an Option; \
317                            this will compile but is probably not what you want");
318             }
319         }
320     }
321
322     // Look for variables that are incremented once per loop iteration.
323     let mut visitor = IncrementVisitor { cx: cx, states: HashMap::new(), depth: 0, done: false };
324     walk_expr(&mut visitor, body);
325
326     // For each candidate, check the parent block to see if
327     // it's initialized to zero at the start of the loop.
328     let map = &cx.tcx.map;
329     let parent_scope = map.get_enclosing_scope(expr.id).and_then(|id| map.get_enclosing_scope(id) );
330     if let Some(parent_id) = parent_scope {
331         if let NodeBlock(block) = map.get(parent_id) {
332             for (id, _) in visitor.states.iter().filter( |&(_,v)| *v == VarState::IncrOnce) {
333                 let mut visitor2 = InitializeVisitor { cx: cx, end_expr: expr, var_id: id.clone(),
334                                                        state: VarState::IncrOnce, name: None,
335                                                        depth: 0,
336                                                        past_loop: false };
337                 walk_block(&mut visitor2, block);
338
339                 if visitor2.state == VarState::Warn {
340                     if let Some(name) = visitor2.name {
341                         span_lint(cx, EXPLICIT_COUNTER_LOOP, expr.span,
342                                   &format!("the variable `{0}` is used as a loop counter. Consider \
343                                             using `for ({0}, item) in {1}.enumerate()` \
344                                             or similar iterators",
345                                            name, snippet(cx, arg.span, "_")));
346                     }
347                 }
348             }
349         }
350     }
351 }
352
353 /// Recover the essential nodes of a desugared for loop:
354 /// `for pat in arg { body }` becomes `(pat, arg, body)`.
355 fn recover_for_loop(expr: &Expr) -> Option<(&Pat, &Expr, &Expr)> {
356     if_let_chain! {
357         [
358             let ExprMatch(ref iterexpr, ref arms, _) = expr.node,
359             let ExprCall(_, ref iterargs) = iterexpr.node,
360             iterargs.len() == 1 && arms.len() == 1 && arms[0].guard.is_none(),
361             let ExprLoop(ref block, _) = arms[0].body.node,
362             block.stmts.is_empty(),
363             let Some(ref loopexpr) = block.expr,
364             let ExprMatch(_, ref innerarms, MatchSource::ForLoopDesugar) = loopexpr.node,
365             innerarms.len() == 2 && innerarms[0].pats.len() == 1,
366             let PatEnum(_, Some(ref somepats)) = innerarms[0].pats[0].node,
367             somepats.len() == 1
368         ], {
369             return Some((&somepats[0],
370                          &iterargs[0],
371                          &innerarms[0].body));
372         }
373     }
374     None
375 }
376
377 struct VarVisitor<'v, 't: 'v> {
378     cx: &'v LateContext<'v, 't>, // context reference
379     var: Name,               // var name to look for as index
380     indexed: HashSet<Name>,  // indexed variables
381     nonindex: bool,          // has the var been used otherwise?
382 }
383
384 impl<'v, 't> Visitor<'v> for VarVisitor<'v, 't> {
385     fn visit_expr(&mut self, expr: &'v Expr) {
386         if let ExprPath(None, ref path) = expr.node {
387             if path.segments.len() == 1 && path.segments[0].identifier.name == self.var {
388                 // we are referencing our variable! now check if it's as an index
389                 if_let_chain! {
390                     [
391                         let Some(parexpr) = get_parent_expr(self.cx, expr),
392                         let ExprIndex(ref seqexpr, _) = parexpr.node,
393                         let ExprPath(None, ref seqvar) = seqexpr.node,
394                         seqvar.segments.len() == 1
395                     ], {
396                         self.indexed.insert(seqvar.segments[0].identifier.name);
397                         return;  // no need to walk further
398                     }
399                 }
400                 // we are not indexing anything, record that
401                 self.nonindex = true;
402                 return;
403             }
404         }
405         walk_expr(self, expr);
406     }
407 }
408
409 fn is_iterator_used_after_while_let(cx: &LateContext, iter_expr: &Expr) -> bool {
410     let def_id = match var_def_id(cx, iter_expr) {
411         Some(id) => id,
412         None => return false
413     };
414     let mut visitor = VarUsedAfterLoopVisitor {
415         cx: cx,
416         def_id: def_id,
417         iter_expr_id: iter_expr.id,
418         past_while_let: false,
419         var_used_after_while_let: false
420     };
421     if let Some(enclosing_block) = get_enclosing_block(cx, def_id) {
422         walk_block(&mut visitor, enclosing_block);
423     }
424     visitor.var_used_after_while_let
425 }
426
427 struct VarUsedAfterLoopVisitor<'v, 't: 'v> {
428     cx: &'v LateContext<'v, 't>,
429     def_id: NodeId,
430     iter_expr_id: NodeId,
431     past_while_let: bool,
432     var_used_after_while_let: bool
433 }
434
435 impl <'v, 't> Visitor<'v> for VarUsedAfterLoopVisitor<'v, 't> {
436     fn visit_expr(&mut self, expr: &'v Expr) {
437         if self.past_while_let {
438             if Some(self.def_id) == var_def_id(self.cx, expr) {
439                 self.var_used_after_while_let = true;
440             }
441         } else if self.iter_expr_id == expr.id {
442             self.past_while_let = true;
443         }
444         walk_expr(self, expr);
445     }
446 }
447
448
449 /// Return true if the type of expr is one that provides IntoIterator impls
450 /// for &T and &mut T, such as Vec.
451 fn is_ref_iterable_type(cx: &LateContext, e: &Expr) -> bool {
452     // no walk_ptrs_ty: calling iter() on a reference can make sense because it
453     // will allow further borrows afterwards
454     let ty = cx.tcx.expr_ty(e);
455     is_iterable_array(ty) ||
456         match_type(cx, ty, &VEC_PATH) ||
457         match_type(cx, ty, &LL_PATH) ||
458         match_type(cx, ty, &["std", "collections", "hash", "map", "HashMap"]) ||
459         match_type(cx, ty, &["std", "collections", "hash", "set", "HashSet"]) ||
460         match_type(cx, ty, &["collections", "vec_deque", "VecDeque"]) ||
461         match_type(cx, ty, &["collections", "binary_heap", "BinaryHeap"]) ||
462         match_type(cx, ty, &["collections", "btree", "map", "BTreeMap"]) ||
463         match_type(cx, ty, &["collections", "btree", "set", "BTreeSet"])
464 }
465
466 fn is_iterable_array(ty: ty::Ty) -> bool {
467     // IntoIterator is currently only implemented for array sizes <= 32 in rustc
468     match ty.sty {
469         ty::TyArray(_, 0...32) => true,
470         _ => false
471     }
472 }
473
474 /// If a block begins with a statement (possibly a `let` binding) and has an expression, return it.
475 fn extract_expr_from_first_stmt(block: &Block) -> Option<&Expr> {
476     if block.stmts.is_empty() { return None; }
477     if let StmtDecl(ref decl, _) = block.stmts[0].node {
478         if let DeclLocal(ref local) = decl.node {
479             if let Some(ref expr) = local.init { Some(expr) } else { None }
480         } else { None }
481     } else { None }
482 }
483
484 /// If a block begins with an expression (with or without semicolon), return it.
485 fn extract_first_expr(block: &Block) -> Option<&Expr> {
486     match block.expr {
487         Some(ref expr) => Some(expr),
488         None if !block.stmts.is_empty() => match block.stmts[0].node {
489             StmtExpr(ref expr, _) | StmtSemi(ref expr, _) => Some(expr),
490             _ => None,
491         },
492         _ => None,
493     }
494 }
495
496 /// Return true if expr contains a single break expr (maybe within a block).
497 fn is_break_expr(expr: &Expr) -> bool {
498     match expr.node {
499         ExprBreak(None) => true,
500         // there won't be a `let <pat> = break` and so we can safely ignore the StmtDecl case
501         ExprBlock(ref b) => match extract_first_expr(b) {
502             Some(ref subexpr) => is_break_expr(subexpr),
503             None => false,
504         },
505         _ => false,
506     }
507 }
508
509 // To trigger the EXPLICIT_COUNTER_LOOP lint, a variable must be
510 // incremented exactly once in the loop body, and initialized to zero
511 // at the start of the loop.
512 #[derive(PartialEq)]
513 enum VarState {
514     Initial,      // Not examined yet
515     IncrOnce,     // Incremented exactly once, may be a loop counter
516     Declared,     // Declared but not (yet) initialized to zero
517     Warn,
518     DontWarn
519 }
520
521 // Scan a for loop for variables that are incremented exactly once.
522 struct IncrementVisitor<'v, 't: 'v> {
523     cx: &'v LateContext<'v, 't>,      // context reference
524     states: HashMap<NodeId, VarState>,  // incremented variables
525     depth: u32,                         // depth of conditional expressions
526     done: bool
527 }
528
529 impl<'v, 't> Visitor<'v> for IncrementVisitor<'v, 't> {
530     fn visit_expr(&mut self, expr: &'v Expr) {
531         if self.done {
532             return;
533         }
534
535         // If node is a variable
536         if let Some(def_id) = var_def_id(self.cx, expr) {
537             if let Some(parent) = get_parent_expr(self.cx, expr) {
538                 let state = self.states.entry(def_id).or_insert(VarState::Initial);
539
540                 match parent.node {
541                     ExprAssignOp(op, ref lhs, ref rhs) =>
542                         if lhs.id == expr.id {
543                             if op.node == BiAdd && is_integer_literal(rhs, 1) {
544                                 *state = match *state {
545                                     VarState::Initial if self.depth == 0 => VarState::IncrOnce,
546                                     _ => VarState::DontWarn
547                                 };
548                             }
549                             else {
550                                 // Assigned some other value
551                                 *state = VarState::DontWarn;
552                             }
553                         },
554                     ExprAssign(ref lhs, _) if lhs.id == expr.id => *state = VarState::DontWarn,
555                     ExprAddrOf(mutability,_) if mutability == MutMutable => *state = VarState::DontWarn,
556                     _ => ()
557                 }
558             }
559         }
560         // Give up if there are nested loops
561         else if is_loop(expr) {
562             self.states.clear();
563             self.done = true;
564             return;
565         }
566         // Keep track of whether we're inside a conditional expression
567         else if is_conditional(expr) {
568             self.depth += 1;
569             walk_expr(self, expr);
570             self.depth -= 1;
571             return;
572         }
573         walk_expr(self, expr);
574     }
575 }
576
577 // Check whether a variable is initialized to zero at the start of a loop.
578 struct InitializeVisitor<'v, 't: 'v> {
579     cx: &'v LateContext<'v, 't>, // context reference
580     end_expr: &'v Expr,      // the for loop. Stop scanning here.
581     var_id: NodeId,
582     state: VarState,
583     name: Option<Name>,
584     depth: u32,              // depth of conditional expressions
585     past_loop: bool
586 }
587
588 impl<'v, 't> Visitor<'v> for InitializeVisitor<'v, 't> {
589     fn visit_decl(&mut self, decl: &'v Decl) {
590         // Look for declarations of the variable
591         if let DeclLocal(ref local) = decl.node {
592             if local.pat.id == self.var_id {
593                 if let PatIdent(_, ref ident, _) = local.pat.node {
594                     self.name = Some(ident.node.name);
595
596                     self.state = if let Some(ref init) = local.init {
597                         if is_integer_literal(init, 0) {
598                             VarState::Warn
599                         } else {
600                             VarState::Declared
601                         }
602                     }
603                     else {
604                         VarState::Declared
605                     }
606                 }
607             }
608         }
609         walk_decl(self, decl);
610     }
611
612     fn visit_expr(&mut self, expr: &'v Expr) {
613         if self.state == VarState::DontWarn {
614             return;
615         }
616         if expr == self.end_expr {
617             self.past_loop = true;
618             return;
619         }
620         // No need to visit expressions before the variable is
621         // declared
622         if self.state == VarState::IncrOnce {
623             return;
624         }
625
626         // If node is the desired variable, see how it's used
627         if var_def_id(self.cx, expr) == Some(self.var_id) {
628             if let Some(parent) = get_parent_expr(self.cx, expr) {
629                 match parent.node {
630                     ExprAssignOp(_, ref lhs, _) if lhs.id == expr.id => {
631                         self.state = VarState::DontWarn;
632                     }
633                     ExprAssign(ref lhs, ref rhs) if lhs.id == expr.id => {
634                         self.state = if is_integer_literal(rhs, 0) && self.depth == 0 {
635                             VarState::Warn
636                         } else {
637                             VarState::DontWarn
638                         }}
639                     ExprAddrOf(mutability,_) if mutability == MutMutable => self.state = VarState::DontWarn,
640                     _ => ()
641                 }
642             }
643
644             if self.past_loop {
645                 self.state = VarState::DontWarn;
646                 return;
647             }
648         }
649         // If there are other loops between the declaration and the target loop, give up
650         else if !self.past_loop && is_loop(expr) {
651             self.state = VarState::DontWarn;
652             return;
653         }
654         // Keep track of whether we're inside a conditional expression
655         else if is_conditional(expr) {
656             self.depth += 1;
657             walk_expr(self, expr);
658             self.depth -= 1;
659             return;
660         }
661         walk_expr(self, expr);
662     }
663 }
664
665 fn var_def_id(cx: &LateContext, expr: &Expr) -> Option<NodeId> {
666     if let Some(path_res) = cx.tcx.def_map.borrow().get(&expr.id) {
667         if let DefLocal(_, node_id) = path_res.base_def {
668             return Some(node_id)
669         }
670     }
671     None
672 }
673
674 fn is_loop(expr: &Expr) -> bool {
675     match expr.node {
676         ExprLoop(..) | ExprWhile(..)  => true,
677         _ => false
678     }
679 }
680
681 fn is_conditional(expr: &Expr) -> bool {
682     match expr.node {
683         ExprIf(..) | ExprMatch(..) => true,
684         _ => false
685     }
686 }