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