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