]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/loops.rs
e3492fd00f75cfd7c4b451dfc05ceb229f257e24
[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;
11 use rustc_const_eval::EvalHint::ExprTypeChecked;
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};
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 #[derive(Copy, Clone)]
290 pub struct Pass;
291
292 impl LintPass for Pass {
293     fn get_lints(&self) -> LintArray {
294         lint_array!(NEEDLESS_RANGE_LOOP,
295                     EXPLICIT_ITER_LOOP,
296                     EXPLICIT_INTO_ITER_LOOP,
297                     ITER_NEXT_LOOP,
298                     FOR_LOOP_OVER_RESULT,
299                     FOR_LOOP_OVER_OPTION,
300                     WHILE_LET_LOOP,
301                     UNUSED_COLLECT,
302                     REVERSE_RANGE_LOOP,
303                     EXPLICIT_COUNTER_LOOP,
304                     EMPTY_LOOP,
305                     WHILE_LET_ON_ITERATOR,
306                     FOR_KV_MAP)
307     }
308 }
309
310 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
311     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
312         if let Some((pat, arg, body)) = higher::for_loop(expr) {
313             check_for_loop(cx, pat, arg, body, expr);
314         }
315         // check for `loop { if let {} else break }` that could be `while let`
316         // (also matches an explicit "match" instead of "if let")
317         // (even if the "match" or "if let" is used for declaration)
318         if let ExprLoop(ref block, _, LoopSource::Loop) = expr.node {
319             // also check for empty `loop {}` statements
320             if block.stmts.is_empty() && block.expr.is_none() {
321                 span_lint(cx,
322                           EMPTY_LOOP,
323                           expr.span,
324                           "empty `loop {}` detected. You may want to either use `panic!()` or add \
325                            `std::thread::sleep(..);` to the loop body.");
326             }
327
328             // extract the expression from the first statement (if any) in a block
329             let inner_stmt_expr = extract_expr_from_first_stmt(block);
330             // or extract the first expression (if any) from the block
331             if let Some(inner) = inner_stmt_expr.or_else(|| extract_first_expr(block)) {
332                 if let ExprMatch(ref matchexpr, ref arms, ref source) = inner.node {
333                     // ensure "if let" compatible match structure
334                     match *source {
335                         MatchSource::Normal |
336                         MatchSource::IfLetDesugar { .. } => {
337                             if arms.len() == 2 && arms[0].pats.len() == 1 && arms[0].guard.is_none() &&
338                                arms[1].pats.len() == 1 && arms[1].guard.is_none() &&
339                                is_break_expr(&arms[1].body) {
340                                 if in_external_macro(cx, expr.span) {
341                                     return;
342                                 }
343
344                                 // NOTE: we used to make build a body here instead of using
345                                 // ellipsis, this was removed because:
346                                 // 1) it was ugly with big bodies;
347                                 // 2) it was not indented properly;
348                                 // 3) it wasn’t very smart (see #675).
349                                 span_lint_and_then(cx,
350                                                    WHILE_LET_LOOP,
351                                                    expr.span,
352                                                    "this loop could be written as a `while let` loop",
353                                                    |db| {
354                                     let sug = format!("while let {} = {} {{ .. }}",
355                                                       snippet(cx, arms[0].pats[0].span, ".."),
356                                                       snippet(cx, matchexpr.span, ".."));
357                                     db.span_suggestion(expr.span, "try", sug);
358                                 });
359                             }
360                         },
361                         _ => (),
362                     }
363                 }
364             }
365         }
366         if let ExprMatch(ref match_expr, ref arms, MatchSource::WhileLetDesugar) = expr.node {
367             let pat = &arms[0].pats[0].node;
368             if let (&PatKind::TupleStruct(ref qpath, ref pat_args, _),
369                     &ExprMethodCall(method_name, _, ref method_args)) = (pat, &match_expr.node) {
370                 let iter_expr = &method_args[0];
371                 let lhs_constructor = last_path_segment(qpath);
372                 if &*method_name.node.as_str() == "next" && match_trait_method(cx, match_expr, &paths::ITERATOR) &&
373                    &*lhs_constructor.name.as_str() == "Some" && !is_refutable(cx, &pat_args[0]) &&
374                    !is_iterator_used_after_while_let(cx, iter_expr) {
375                     let iterator = snippet(cx, method_args[0].span, "_");
376                     let loop_var = snippet(cx, pat_args[0].span, "_");
377                     span_lint_and_then(cx,
378                                        WHILE_LET_ON_ITERATOR,
379                                        expr.span,
380                                        "this loop could be written as a `for` loop",
381                                        |db| {
382                         db.span_suggestion(expr.span, "try", format!("for {} in {} {{ .. }}", loop_var, iterator));
383                     });
384                 }
385             }
386         }
387     }
388
389     fn check_stmt(&mut self, cx: &LateContext<'a, 'tcx>, stmt: &'tcx Stmt) {
390         if let StmtSemi(ref expr, _) = stmt.node {
391             if let ExprMethodCall(ref method, _, ref args) = expr.node {
392                 if args.len() == 1 && &*method.node.as_str() == "collect" &&
393                    match_trait_method(cx, expr, &paths::ITERATOR) {
394                     span_lint(cx,
395                               UNUSED_COLLECT,
396                               expr.span,
397                               "you are collect()ing an iterator and throwing away the result. \
398                                Consider using an explicit for loop to exhaust the iterator");
399                 }
400             }
401         }
402     }
403 }
404
405 fn check_for_loop<'a, 'tcx>(
406     cx: &LateContext<'a, 'tcx>,
407     pat: &'tcx Pat,
408     arg: &'tcx Expr,
409     body: &'tcx Expr,
410     expr: &'tcx Expr
411 ) {
412     check_for_loop_range(cx, pat, arg, body, expr);
413     check_for_loop_reverse_range(cx, arg, expr);
414     check_for_loop_arg(cx, pat, arg, expr);
415     check_for_loop_explicit_counter(cx, arg, body, expr);
416     check_for_loop_over_map_kv(cx, pat, arg, body, expr);
417 }
418
419 /// Check for looping over a range and then indexing a sequence with it.
420 /// The iteratee must be a range literal.
421 fn check_for_loop_range<'a, 'tcx>(
422     cx: &LateContext<'a, 'tcx>,
423     pat: &'tcx Pat,
424     arg: &'tcx Expr,
425     body: &'tcx Expr,
426     expr: &'tcx Expr
427 ) {
428     if let Some(higher::Range { start: Some(start), ref end, limits }) = higher::range(arg) {
429         // the var must be a single name
430         if let PatKind::Binding(_, def_id, ref ident, _) = pat.node {
431             let mut visitor = VarVisitor {
432                 cx: cx,
433                 var: def_id,
434                 indexed: HashMap::new(),
435                 nonindex: false,
436             };
437             walk_expr(&mut visitor, body);
438
439             // linting condition: we only indexed one variable
440             if visitor.indexed.len() == 1 {
441                 let (indexed, indexed_extent) = visitor.indexed
442                     .into_iter()
443                     .next()
444                     .unwrap_or_else(|| unreachable!() /* len == 1 */);
445
446                 // ensure that the indexed variable was declared before the loop, see #601
447                 if let Some(indexed_extent) = indexed_extent {
448                     let pat_extent = cx.tcx.region_maps.var_scope(pat.id);
449                     if cx.tcx.region_maps.is_subscope_of(indexed_extent, pat_extent) {
450                         return;
451                     }
452                 }
453
454                 let starts_at_zero = is_integer_literal(start, 0);
455
456                 let skip = if starts_at_zero {
457                     "".to_owned()
458                 } else {
459                     format!(".skip({})", snippet(cx, start.span, ".."))
460                 };
461
462                 let take = if let Some(end) = *end {
463                     if is_len_call(end, &indexed) {
464                         "".to_owned()
465                     } else {
466                         match limits {
467                             ast::RangeLimits::Closed => {
468                                 let end = sugg::Sugg::hir(cx, end, "<count>");
469                                 format!(".take({})", end + sugg::ONE)
470                             },
471                             ast::RangeLimits::HalfOpen => format!(".take({})", snippet(cx, end.span, "..")),
472                         }
473                     }
474                 } else {
475                     "".to_owned()
476                 };
477
478                 if visitor.nonindex {
479                     span_lint_and_then(cx,
480                                        NEEDLESS_RANGE_LOOP,
481                                        expr.span,
482                                        &format!("the loop variable `{}` is used to index `{}`", ident.node, indexed),
483                                        |db| {
484                         multispan_sugg(db,
485                                        "consider using an iterator".to_string(),
486                                        &[(pat.span, &format!("({}, <item>)", ident.node)),
487                                          (arg.span, &format!("{}.iter().enumerate(){}{}", indexed, take, skip))]);
488                     });
489                 } else {
490                     let repl = if starts_at_zero && take.is_empty() {
491                         format!("&{}", indexed)
492                     } else {
493                         format!("{}.iter(){}{}", indexed, take, skip)
494                     };
495
496                     span_lint_and_then(cx,
497                                        NEEDLESS_RANGE_LOOP,
498                                        expr.span,
499                                        &format!("the loop variable `{}` is only used to index `{}`.",
500                                                 ident.node,
501                                                 indexed),
502                                        |db| {
503                         multispan_sugg(db,
504                                        "consider using an iterator".to_string(),
505                                        &[(pat.span, "<item>"), (arg.span, &repl)]);
506                     });
507                 }
508             }
509         }
510     }
511 }
512
513 fn is_len_call(expr: &Expr, var: &Name) -> bool {
514     if_let_chain! {[
515         let ExprMethodCall(method, _, ref len_args) = expr.node,
516         len_args.len() == 1,
517         &*method.node.as_str() == "len",
518         let ExprPath(QPath::Resolved(_, ref path)) = len_args[0].node,
519         path.segments.len() == 1,
520         &path.segments[0].name == var
521     ], {
522         return true;
523     }}
524
525     false
526 }
527
528 fn check_for_loop_reverse_range(cx: &LateContext, arg: &Expr, expr: &Expr) {
529     // if this for loop is iterating over a two-sided range...
530     if let Some(higher::Range { start: Some(start), end: Some(end), limits }) = higher::range(arg) {
531         // ...and both sides are compile-time constant integers...
532         let constcx = ConstContext::with_tables(cx.tcx, cx.tables);
533         if let Ok(start_idx) = constcx.eval(start, ExprTypeChecked) {
534             if let Ok(end_idx) = constcx.eval(end, ExprTypeChecked) {
535                 // ...and the start index is greater than the end index,
536                 // this loop will never run. This is often confusing for developers
537                 // who think that this will iterate from the larger value to the
538                 // smaller value.
539                 let (sup, eq) = match (start_idx, end_idx) {
540                     (ConstVal::Integral(start_idx), ConstVal::Integral(end_idx)) => {
541                         (start_idx > end_idx, start_idx == end_idx)
542                     },
543                     _ => (false, false),
544                 };
545
546                 if sup {
547                     let start_snippet = snippet(cx, start.span, "_");
548                     let end_snippet = snippet(cx, end.span, "_");
549                     let dots = if limits == ast::RangeLimits::Closed {
550                         "..."
551                     } else {
552                         ".."
553                     };
554
555                     span_lint_and_then(cx,
556                                        REVERSE_RANGE_LOOP,
557                                        expr.span,
558                                        "this range is empty so this for loop will never run",
559                                        |db| {
560                         db.span_suggestion(arg.span,
561                                            "consider using the following if you are attempting to iterate over this \
562                                             range in reverse",
563                                            format!("({end}{dots}{start}).rev()",
564                                                    end = end_snippet,
565                                                    dots = dots,
566                                                    start = start_snippet));
567                     });
568                 } else if eq && limits != ast::RangeLimits::Closed {
569                     // if they are equal, it's also problematic - this loop
570                     // will never run.
571                     span_lint(cx,
572                               REVERSE_RANGE_LOOP,
573                               expr.span,
574                               "this range is empty so this for loop will never run");
575                 }
576             }
577         }
578     }
579 }
580
581 fn check_for_loop_arg(cx: &LateContext, pat: &Pat, arg: &Expr, expr: &Expr) {
582     let mut next_loop_linted = false; // whether or not ITER_NEXT_LOOP lint was used
583     if let ExprMethodCall(ref method, _, ref args) = arg.node {
584         // just the receiver, no arguments
585         if args.len() == 1 {
586             let method_name = method.node;
587             // check for looping over x.iter() or x.iter_mut(), could use &x or &mut x
588             if &*method_name.as_str() == "iter" || &*method_name.as_str() == "iter_mut" {
589                 if is_ref_iterable_type(cx, &args[0]) {
590                     let object = snippet(cx, args[0].span, "_");
591                     let suggestion = format!("&{}{}",
592                                              if &*method_name.as_str() == "iter_mut" {
593                                                  "mut "
594                                              } else {
595                                                  ""
596                                              },
597                                              object);
598                     span_lint_and_then(cx,
599                                        EXPLICIT_ITER_LOOP,
600                                        arg.span,
601                                        &format!("it is more idiomatic to loop over `{}` instead of `{}.{}()`",
602                                                 suggestion,
603                                                 object,
604                                                 method_name),
605                                        |db| {
606                         db.span_suggestion(arg.span, "to write this more concisely, try looping over", suggestion);
607                     });
608                 }
609             } else if &*method_name.as_str() == "into_iter" && match_trait_method(cx, arg, &paths::INTO_ITERATOR) {
610                 let object = snippet(cx, args[0].span, "_");
611                 span_lint_and_then(cx,
612                                    EXPLICIT_INTO_ITER_LOOP,
613                                    arg.span,
614                                    &format!("it is more idiomatic to loop over `{}` instead of `{}.{}()`",
615                                             object,
616                                             object,
617                                             method_name),
618                                    |db| {
619                     db.span_suggestion(arg.span,
620                                        "to write this more concisely, try looping over",
621                                        object.to_string());
622                 });
623
624             } else if &*method_name.as_str() == "next" && match_trait_method(cx, arg, &paths::ITERATOR) {
625                 span_lint(cx,
626                           ITER_NEXT_LOOP,
627                           expr.span,
628                           "you are iterating over `Iterator::next()` which is an Option; this will compile but is \
629                            probably not what you want");
630                 next_loop_linted = true;
631             }
632         }
633     }
634     if !next_loop_linted {
635         check_arg_type(cx, pat, arg);
636     }
637 }
638
639 /// Check for `for` loops over `Option`s and `Results`
640 fn check_arg_type(cx: &LateContext, pat: &Pat, arg: &Expr) {
641     let ty = cx.tables.expr_ty(arg);
642     if match_type(cx, ty, &paths::OPTION) {
643         span_help_and_lint(cx,
644                            FOR_LOOP_OVER_OPTION,
645                            arg.span,
646                            &format!("for loop over `{0}`, which is an `Option`. This is more readably written as an \
647                                      `if let` statement.",
648                                     snippet(cx, arg.span, "_")),
649                            &format!("consider replacing `for {0} in {1}` with `if let Some({0}) = {1}`",
650                                     snippet(cx, pat.span, "_"),
651                                     snippet(cx, arg.span, "_")));
652     } else if match_type(cx, ty, &paths::RESULT) {
653         span_help_and_lint(cx,
654                            FOR_LOOP_OVER_RESULT,
655                            arg.span,
656                            &format!("for loop over `{0}`, which is a `Result`. This is more readably written as an \
657                                      `if let` statement.",
658                                     snippet(cx, arg.span, "_")),
659                            &format!("consider replacing `for {0} in {1}` with `if let Ok({0}) = {1}`",
660                                     snippet(cx, pat.span, "_"),
661                                     snippet(cx, arg.span, "_")));
662     }
663 }
664
665 fn check_for_loop_explicit_counter<'a, 'tcx>(
666     cx: &LateContext<'a, 'tcx>,
667     arg: &'tcx Expr,
668     body: &'tcx Expr,
669     expr: &'tcx Expr
670 ) {
671     // Look for variables that are incremented once per loop iteration.
672     let mut visitor = IncrementVisitor {
673         cx: cx,
674         states: HashMap::new(),
675         depth: 0,
676         done: false,
677     };
678     walk_expr(&mut visitor, body);
679
680     // For each candidate, check the parent block to see if
681     // it's initialized to zero at the start of the loop.
682     let map = &cx.tcx.map;
683     let parent_scope = map.get_enclosing_scope(expr.id).and_then(|id| map.get_enclosing_scope(id));
684     if let Some(parent_id) = parent_scope {
685         if let NodeBlock(block) = map.get(parent_id) {
686             for (id, _) in visitor.states.iter().filter(|&(_, v)| *v == VarState::IncrOnce) {
687                 let mut visitor2 = InitializeVisitor {
688                     cx: cx,
689                     end_expr: expr,
690                     var_id: *id,
691                     state: VarState::IncrOnce,
692                     name: None,
693                     depth: 0,
694                     past_loop: false,
695                 };
696                 walk_block(&mut visitor2, block);
697
698                 if visitor2.state == VarState::Warn {
699                     if let Some(name) = visitor2.name {
700                         span_lint(cx,
701                                   EXPLICIT_COUNTER_LOOP,
702                                   expr.span,
703                                   &format!("the variable `{0}` is used as a loop counter. Consider using `for ({0}, \
704                                             item) in {1}.enumerate()` or similar iterators",
705                                            name,
706                                            snippet(cx, arg.span, "_")));
707                     }
708                 }
709             }
710         }
711     }
712 }
713
714 /// Check for the `FOR_KV_MAP` lint.
715 fn check_for_loop_over_map_kv<'a, 'tcx>(
716     cx: &LateContext<'a, 'tcx>,
717     pat: &'tcx Pat,
718     arg: &'tcx Expr,
719     body: &'tcx Expr,
720     expr: &'tcx Expr
721 ) {
722     let pat_span = pat.span;
723
724     if let PatKind::Tuple(ref pat, _) = pat.node {
725         if pat.len() == 2 {
726             let arg_span = arg.span;
727             let (new_pat_span, kind, ty, mutbl) = match cx.tables.expr_ty(arg).sty {
728                 ty::TyRef(_, ref tam) => {
729                     match (&pat[0].node, &pat[1].node) {
730                         (key, _) if pat_is_wild(cx, key, body) => (pat[1].span, "value", tam.ty, tam.mutbl),
731                         (_, value) if pat_is_wild(cx, value, body) => (pat[0].span, "key", tam.ty, MutImmutable),
732                         _ => return,
733                     }
734                 },
735                 _ => return,
736             };
737             let mutbl = match mutbl {
738                 MutImmutable => "",
739                 MutMutable => "_mut",
740             };
741             let arg = match arg.node {
742                 ExprAddrOf(_, ref expr) => &**expr,
743                 _ => arg,
744             };
745
746             if match_type(cx, ty, &paths::HASHMAP) || match_type(cx, ty, &paths::BTREEMAP) {
747                 span_lint_and_then(cx,
748                                    FOR_KV_MAP,
749                                    expr.span,
750                                    &format!("you seem to want to iterate on a map's {}s", kind),
751                                    |db| {
752                     let map = sugg::Sugg::hir(cx, arg, "map");
753                     multispan_sugg(db,
754                                    "use the corresponding method".into(),
755                                    &[(pat_span, &snippet(cx, new_pat_span, kind)),
756                                      (arg_span, &format!("{}.{}s{}()", map.maybe_par(), kind, mutbl))]);
757                 });
758             }
759         }
760     }
761
762 }
763
764 /// Return true if the pattern is a `PatWild` or an ident prefixed with `'_'`.
765 fn pat_is_wild<'a, 'tcx: 'a>(cx: &LateContext<'a, 'tcx>, pat: &'tcx PatKind, body: &'tcx Expr) -> bool {
766     match *pat {
767         PatKind::Wild => true,
768         PatKind::Binding(_, _, ident, None) if ident.node.as_str().starts_with('_') => {
769             let mut visitor = UsedVisitor {
770                 var: ident.node,
771                 used: false,
772                 cx: cx,
773             };
774             walk_expr(&mut visitor, body);
775             !visitor.used
776         },
777         _ => false,
778     }
779 }
780
781 struct UsedVisitor<'a, 'tcx: 'a> {
782     var: ast::Name, // var to look for
783     used: bool, // has the var been used otherwise?
784     cx: &'a LateContext<'a, 'tcx>,
785 }
786
787 impl<'a, 'tcx: 'a> Visitor<'tcx> for UsedVisitor<'a, 'tcx> {
788     fn visit_expr(&mut self, expr: &'tcx Expr) {
789         if let ExprPath(QPath::Resolved(None, ref path)) = expr.node {
790             if path.segments.len() == 1 && path.segments[0].name == self.var {
791                 self.used = true;
792                 return;
793             }
794         }
795
796         walk_expr(self, expr);
797     }
798     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
799         NestedVisitorMap::All(&self.cx.tcx.map)
800     }
801 }
802
803 struct VarVisitor<'a, 'tcx: 'a> {
804     cx: &'a LateContext<'a, 'tcx>, // context reference
805     var: DefId, // var name to look for as index
806     indexed: HashMap<Name, Option<CodeExtent>>, // indexed variables, the extent is None for global
807     nonindex: bool, // has the var been used otherwise?
808 }
809
810 impl<'a, 'tcx> Visitor<'tcx> for VarVisitor<'a, 'tcx> {
811     fn visit_expr(&mut self, expr: &'tcx Expr) {
812         if let ExprPath(ref qpath) = expr.node {
813             if let QPath::Resolved(None, ref path) = *qpath {
814                 if path.segments.len() == 1 && self.cx.tables.qpath_def(qpath, expr.id).def_id() == self.var {
815                     // we are referencing our variable! now check if it's as an index
816                     if_let_chain! {[
817                         let Some(parexpr) = get_parent_expr(self.cx, expr),
818                         let ExprIndex(ref seqexpr, _) = parexpr.node,
819                         let ExprPath(ref seqpath) = seqexpr.node,
820                         let QPath::Resolved(None, ref seqvar) = *seqpath,
821                         seqvar.segments.len() == 1
822                     ], {
823                         let def = self.cx.tables.qpath_def(seqpath, seqexpr.id);
824                         match def {
825                             Def::Local(..) | Def::Upvar(..) => {
826                                 let def_id = def.def_id();
827                                 let node_id = self.cx.tcx.map.as_local_node_id(def_id).unwrap();
828
829                                 let extent = self.cx.tcx.region_maps.var_scope(node_id);
830                                 self.indexed.insert(seqvar.segments[0].name, Some(extent));
831                                 return;  // no need to walk further
832                             }
833                             Def::Static(..) | Def::Const(..) => {
834                                 self.indexed.insert(seqvar.segments[0].name, None);
835                                 return;  // no need to walk further
836                             }
837                             _ => (),
838                         }
839                     }}
840                     // we are not indexing anything, record that
841                     self.nonindex = true;
842                     return;
843                 }
844             }
845         }
846         walk_expr(self, expr);
847     }
848     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
849         NestedVisitorMap::All(&self.cx.tcx.map)
850     }
851 }
852
853 fn is_iterator_used_after_while_let<'a, 'tcx: 'a>(cx: &LateContext<'a, 'tcx>, iter_expr: &'tcx Expr) -> bool {
854     let def_id = match var_def_id(cx, iter_expr) {
855         Some(id) => id,
856         None => return false,
857     };
858     let mut visitor = VarUsedAfterLoopVisitor {
859         cx: cx,
860         def_id: def_id,
861         iter_expr_id: iter_expr.id,
862         past_while_let: false,
863         var_used_after_while_let: false,
864     };
865     if let Some(enclosing_block) = get_enclosing_block(cx, def_id) {
866         walk_block(&mut visitor, enclosing_block);
867     }
868     visitor.var_used_after_while_let
869 }
870
871 struct VarUsedAfterLoopVisitor<'a, 'tcx: 'a> {
872     cx: &'a LateContext<'a, 'tcx>,
873     def_id: NodeId,
874     iter_expr_id: NodeId,
875     past_while_let: bool,
876     var_used_after_while_let: bool,
877 }
878
879 impl<'a, 'tcx> Visitor<'tcx> for VarUsedAfterLoopVisitor<'a, 'tcx> {
880     fn visit_expr(&mut self, expr: &'tcx Expr) {
881         if self.past_while_let {
882             if Some(self.def_id) == var_def_id(self.cx, expr) {
883                 self.var_used_after_while_let = true;
884             }
885         } else if self.iter_expr_id == expr.id {
886             self.past_while_let = true;
887         }
888         walk_expr(self, expr);
889     }
890     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
891         NestedVisitorMap::All(&self.cx.tcx.map)
892     }
893 }
894
895
896 /// Return true if the type of expr is one that provides `IntoIterator` impls
897 /// for `&T` and `&mut T`, such as `Vec`.
898 #[cfg_attr(rustfmt, rustfmt_skip)]
899 fn is_ref_iterable_type(cx: &LateContext, e: &Expr) -> bool {
900     // no walk_ptrs_ty: calling iter() on a reference can make sense because it
901     // will allow further borrows afterwards
902     let ty = cx.tables.expr_ty(e);
903     is_iterable_array(ty) ||
904     match_type(cx, ty, &paths::VEC) ||
905     match_type(cx, ty, &paths::LINKED_LIST) ||
906     match_type(cx, ty, &paths::HASHMAP) ||
907     match_type(cx, ty, &paths::HASHSET) ||
908     match_type(cx, ty, &paths::VEC_DEQUE) ||
909     match_type(cx, ty, &paths::BINARY_HEAP) ||
910     match_type(cx, ty, &paths::BTREEMAP) ||
911     match_type(cx, ty, &paths::BTREESET)
912 }
913
914 fn is_iterable_array(ty: ty::Ty) -> bool {
915     // IntoIterator is currently only implemented for array sizes <= 32 in rustc
916     match ty.sty {
917         ty::TyArray(_, 0...32) => true,
918         _ => false,
919     }
920 }
921
922 /// If a block begins with a statement (possibly a `let` binding) and has an expression, return it.
923 fn extract_expr_from_first_stmt(block: &Block) -> Option<&Expr> {
924     if block.stmts.is_empty() {
925         return None;
926     }
927     if let StmtDecl(ref decl, _) = block.stmts[0].node {
928         if let DeclLocal(ref local) = decl.node {
929             if let Some(ref expr) = local.init {
930                 Some(expr)
931             } else {
932                 None
933             }
934         } else {
935             None
936         }
937     } else {
938         None
939     }
940 }
941
942 /// If a block begins with an expression (with or without semicolon), return it.
943 fn extract_first_expr(block: &Block) -> Option<&Expr> {
944     match block.expr {
945         Some(ref expr) if block.stmts.is_empty() => Some(expr),
946         None if !block.stmts.is_empty() => {
947             match block.stmts[0].node {
948                 StmtExpr(ref expr, _) |
949                 StmtSemi(ref expr, _) => Some(expr),
950                 StmtDecl(..) => None,
951             }
952         },
953         _ => None,
954     }
955 }
956
957 /// Return true if expr contains a single break expr (maybe within a block).
958 fn is_break_expr(expr: &Expr) -> bool {
959     match expr.node {
960         ExprBreak(None, _) => true,
961         ExprBlock(ref b) => {
962             match extract_first_expr(b) {
963                 Some(subexpr) => is_break_expr(subexpr),
964                 None => false,
965             }
966         },
967         _ => false,
968     }
969 }
970
971 // To trigger the EXPLICIT_COUNTER_LOOP lint, a variable must be
972 // incremented exactly once in the loop body, and initialized to zero
973 // at the start of the loop.
974 #[derive(PartialEq)]
975 enum VarState {
976     Initial, // Not examined yet
977     IncrOnce, // Incremented exactly once, may be a loop counter
978     Declared, // Declared but not (yet) initialized to zero
979     Warn,
980     DontWarn,
981 }
982
983 /// Scan a for loop for variables that are incremented exactly once.
984 struct IncrementVisitor<'a, 'tcx: 'a> {
985     cx: &'a LateContext<'a, 'tcx>, // context reference
986     states: HashMap<NodeId, VarState>, // incremented variables
987     depth: u32, // depth of conditional expressions
988     done: bool,
989 }
990
991 impl<'a, 'tcx> Visitor<'tcx> for IncrementVisitor<'a, 'tcx> {
992     fn visit_expr(&mut self, expr: &'tcx Expr) {
993         if self.done {
994             return;
995         }
996
997         // If node is a variable
998         if let Some(def_id) = var_def_id(self.cx, expr) {
999             if let Some(parent) = get_parent_expr(self.cx, expr) {
1000                 let state = self.states.entry(def_id).or_insert(VarState::Initial);
1001
1002                 match parent.node {
1003                     ExprAssignOp(op, ref lhs, ref rhs) => {
1004                         if lhs.id == expr.id {
1005                             if op.node == BiAdd && is_integer_literal(rhs, 1) {
1006                                 *state = match *state {
1007                                     VarState::Initial if self.depth == 0 => VarState::IncrOnce,
1008                                     _ => VarState::DontWarn,
1009                                 };
1010                             } else {
1011                                 // Assigned some other value
1012                                 *state = VarState::DontWarn;
1013                             }
1014                         }
1015                     },
1016                     ExprAssign(ref lhs, _) if lhs.id == expr.id => *state = VarState::DontWarn,
1017                     ExprAddrOf(mutability, _) if mutability == MutMutable => *state = VarState::DontWarn,
1018                     _ => (),
1019                 }
1020             }
1021         } else if is_loop(expr) {
1022             self.states.clear();
1023             self.done = true;
1024             return;
1025         } else if is_conditional(expr) {
1026             self.depth += 1;
1027             walk_expr(self, expr);
1028             self.depth -= 1;
1029             return;
1030         }
1031         walk_expr(self, expr);
1032     }
1033     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1034         NestedVisitorMap::All(&self.cx.tcx.map)
1035     }
1036 }
1037
1038 /// Check whether a variable is initialized to zero at the start of a loop.
1039 struct InitializeVisitor<'a, 'tcx: 'a> {
1040     cx: &'a LateContext<'a, 'tcx>, // context reference
1041     end_expr: &'tcx Expr, // the for loop. Stop scanning here.
1042     var_id: NodeId,
1043     state: VarState,
1044     name: Option<Name>,
1045     depth: u32, // depth of conditional expressions
1046     past_loop: bool,
1047 }
1048
1049 impl<'a, 'tcx> Visitor<'tcx> for InitializeVisitor<'a, 'tcx> {
1050     fn visit_decl(&mut self, decl: &'tcx Decl) {
1051         // Look for declarations of the variable
1052         if let DeclLocal(ref local) = decl.node {
1053             if local.pat.id == self.var_id {
1054                 if let PatKind::Binding(_, _, ref ident, _) = local.pat.node {
1055                     self.name = Some(ident.node);
1056
1057                     self.state = if let Some(ref init) = local.init {
1058                         if is_integer_literal(init, 0) {
1059                             VarState::Warn
1060                         } else {
1061                             VarState::Declared
1062                         }
1063                     } else {
1064                         VarState::Declared
1065                     }
1066                 }
1067             }
1068         }
1069         walk_decl(self, decl);
1070     }
1071
1072     fn visit_expr(&mut self, expr: &'tcx Expr) {
1073         if self.state == VarState::DontWarn {
1074             return;
1075         }
1076         if expr == self.end_expr {
1077             self.past_loop = true;
1078             return;
1079         }
1080         // No need to visit expressions before the variable is
1081         // declared
1082         if self.state == VarState::IncrOnce {
1083             return;
1084         }
1085
1086         // If node is the desired variable, see how it's used
1087         if var_def_id(self.cx, expr) == Some(self.var_id) {
1088             if let Some(parent) = get_parent_expr(self.cx, expr) {
1089                 match parent.node {
1090                     ExprAssignOp(_, ref lhs, _) if lhs.id == expr.id => {
1091                         self.state = VarState::DontWarn;
1092                     },
1093                     ExprAssign(ref lhs, ref rhs) if lhs.id == expr.id => {
1094                         self.state = if is_integer_literal(rhs, 0) && self.depth == 0 {
1095                             VarState::Warn
1096                         } else {
1097                             VarState::DontWarn
1098                         }
1099                     },
1100                     ExprAddrOf(mutability, _) if mutability == MutMutable => self.state = VarState::DontWarn,
1101                     _ => (),
1102                 }
1103             }
1104
1105             if self.past_loop {
1106                 self.state = VarState::DontWarn;
1107                 return;
1108             }
1109         } else if !self.past_loop && is_loop(expr) {
1110             self.state = VarState::DontWarn;
1111             return;
1112         } else if is_conditional(expr) {
1113             self.depth += 1;
1114             walk_expr(self, expr);
1115             self.depth -= 1;
1116             return;
1117         }
1118         walk_expr(self, expr);
1119     }
1120     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1121         NestedVisitorMap::All(&self.cx.tcx.map)
1122     }
1123 }
1124
1125 fn var_def_id(cx: &LateContext, expr: &Expr) -> Option<NodeId> {
1126     if let ExprPath(ref qpath) = expr.node {
1127         let path_res = cx.tables.qpath_def(qpath, expr.id);
1128         if let Def::Local(def_id) = path_res {
1129             let node_id = cx.tcx.map.as_local_node_id(def_id).expect("That DefId should be valid");
1130             return Some(node_id);
1131         }
1132     }
1133     None
1134 }
1135
1136 fn is_loop(expr: &Expr) -> bool {
1137     match expr.node {
1138         ExprLoop(..) | ExprWhile(..) => true,
1139         _ => false,
1140     }
1141 }
1142
1143 fn is_conditional(expr: &Expr) -> bool {
1144     match expr.node {
1145         ExprIf(..) | ExprMatch(..) => true,
1146         _ => false,
1147     }
1148 }