]> git.lizzy.rs Git - rust.git/blob - src/loops.rs
Merge pull request #681 from oli-obk/split
[rust.git] / src / loops.rs
1 use reexport::*;
2 use rustc::hir::*;
3 use rustc::hir::def::Def;
4 use rustc::hir::intravisit::{Visitor, walk_expr, walk_block, walk_decl};
5 use rustc::hir::map::Node::NodeBlock;
6 use rustc::lint::*;
7 use rustc::middle::const_val::ConstVal;
8 use rustc::middle::region::CodeExtent;
9 use rustc::ty;
10 use rustc_const_eval::EvalHint::ExprTypeChecked;
11 use rustc_const_eval::eval_const_expr_partial;
12 use std::borrow::Cow;
13 use std::collections::HashMap;
14 use syntax::ast;
15
16 use utils::{snippet, span_lint, get_parent_expr, match_trait_method, match_type, in_external_macro,
17             span_help_and_lint, is_integer_literal, get_enclosing_block, span_lint_and_then, unsugar_range,
18             walk_ptrs_ty, recover_for_loop};
19 use utils::paths;
20 use utils::UnsugaredRange;
21
22 /// **What it does:** This lint checks for looping over the range of `0..len` of some collection just to get the values by index.
23 ///
24 /// **Why is this bad?** Just iterating the collection itself makes the intent more clear and is probably faster.
25 ///
26 /// **Known problems:** None
27 ///
28 /// **Example:**
29 /// ```
30 /// for i in 0..vec.len() {
31 ///     println!("{}", vec[i]);
32 /// }
33 /// ```
34 declare_lint! {
35     pub NEEDLESS_RANGE_LOOP,
36     Warn,
37     "for-looping over a range of indices where an iterator over items would do"
38 }
39
40 /// **What it does:** This lint checks for loops on `x.iter()` where `&x` will do, and suggest the latter.
41 ///
42 /// **Why is this bad?** Readability.
43 ///
44 /// **Known problems:** False negatives. We currently only warn on some known types.
45 ///
46 /// **Example:** `for x in y.iter() { .. }` (where y is a `Vec` or slice)
47 declare_lint! {
48     pub EXPLICIT_ITER_LOOP,
49     Warn,
50     "for-looping over `_.iter()` or `_.iter_mut()` when `&_` or `&mut _` would do"
51 }
52
53 /// **What it does:** This lint checks for loops on `x.next()`.
54 ///
55 /// **Why is this bad?** `next()` returns either `Some(value)` if there was a value, or `None` otherwise. The insidious thing is that `Option<_>` implements `IntoIterator`, so that possibly one value will be iterated, leading to some hard to find bugs. No one will want to write such code [except to win an Underhanded Rust Contest](https://www.reddit.com/r/rust/comments/3hb0wm/underhanded_rust_contest/cu5yuhr).
56 ///
57 /// **Known problems:** None
58 ///
59 /// **Example:** `for x in y.next() { .. }`
60 declare_lint! {
61     pub ITER_NEXT_LOOP,
62     Warn,
63     "for-looping over `_.next()` which is probably not intended"
64 }
65
66 /// **What it does:** This lint checks for `for` loops over `Option` values.
67 ///
68 /// **Why is this bad?** Readability. This is more clearly expressed as an `if let`.
69 ///
70 /// **Known problems:** None
71 ///
72 /// **Example:** `for x in option { .. }`. This should be `if let Some(x) = option { .. }`.
73 declare_lint! {
74     pub FOR_LOOP_OVER_OPTION,
75     Warn,
76     "for-looping over an `Option`, which is more clearly expressed as an `if let`"
77 }
78
79 /// **What it does:** This lint checks for `for` loops over `Result` values.
80 ///
81 /// **Why is this bad?** Readability. This is more clearly expressed as an `if let`.
82 ///
83 /// **Known problems:** None
84 ///
85 /// **Example:** `for x in result { .. }`. This should be `if let Ok(x) = result { .. }`.
86 declare_lint! {
87     pub FOR_LOOP_OVER_RESULT,
88     Warn,
89     "for-looping over a `Result`, which is more clearly expressed as an `if let`"
90 }
91
92 /// **What it does:** This lint detects `loop + match` combinations that are easier written as a `while let` loop.
93 ///
94 /// **Why is this bad?** The `while let` loop is usually shorter and more readable
95 ///
96 /// **Known problems:** Sometimes the wrong binding is displayed (#383)
97 ///
98 /// **Example:**
99 ///
100 /// ```
101 /// loop {
102 ///     let x = match y {
103 ///         Some(x) => x,
104 ///         None => break,
105 ///     }
106 ///     // .. do something with x
107 /// }
108 /// // is easier written as
109 /// while let Some(x) = y {
110 ///     // .. do something with x
111 /// }
112 /// ```
113 declare_lint! {
114     pub WHILE_LET_LOOP,
115     Warn,
116     "`loop { if let { ... } else break }` can be written as a `while let` loop"
117 }
118
119 /// **What it does:** This lint checks for using `collect()` on an iterator without using the result.
120 ///
121 /// **Why is this bad?** It is more idiomatic to use a `for` loop over the iterator instead.
122 ///
123 /// **Known problems:** None
124 ///
125 /// **Example:** `vec.iter().map(|x| /* some operation returning () */).collect::<Vec<_>>();`
126 declare_lint! {
127     pub UNUSED_COLLECT,
128     Warn,
129     "`collect()`ing an iterator without using the result; this is usually better \
130      written as a for loop"
131 }
132
133 /// **What it does:** This lint checks for loops over ranges `x..y` where both `x` and `y` are constant and `x` is greater or equal to `y`, unless the range is reversed or has a negative `.step_by(_)`.
134 ///
135 /// **Why is it bad?** Such loops will either be skipped or loop until wrap-around (in debug code, this may `panic!()`). Both options are probably not intended.
136 ///
137 /// **Known problems:** The lint cannot catch loops over dynamically defined ranges. Doing this would require simulating all possible inputs and code paths through the program, which would be complex and error-prone.
138 ///
139 /// **Examples**: `for x in 5..10-5 { .. }` (oops, stray `-`)
140 declare_lint! {
141     pub REVERSE_RANGE_LOOP,
142     Warn,
143     "Iterating over an empty range, such as `10..0` or `5..5`"
144 }
145
146 /// **What it does:** This lint checks `for` loops over slices with an explicit counter and suggests the use of `.enumerate()`.
147 ///
148 /// **Why is it bad?** Not only is the version using `.enumerate()` more readable, the compiler is able to remove bounds checks which can lead to faster code in some instances.
149 ///
150 /// **Known problems:** None.
151 ///
152 /// **Example:** `for i in 0..v.len() { foo(v[i]); }` or `for i in 0..v.len() { bar(i, v[i]); }`
153 declare_lint! {
154     pub EXPLICIT_COUNTER_LOOP,
155     Warn,
156     "for-looping with an explicit counter when `_.enumerate()` would do"
157 }
158
159 /// **What it does:** This lint checks for empty `loop` expressions.
160 ///
161 /// **Why is this bad?** Those busy loops burn CPU cycles without doing anything. Think of the environment and either block on something or at least make the thread sleep for some microseconds.
162 ///
163 /// **Known problems:** None
164 ///
165 /// **Example:** `loop {}`
166 declare_lint! {
167     pub EMPTY_LOOP,
168     Warn,
169     "empty `loop {}` detected"
170 }
171
172 /// **What it does:** This lint checks for `while let` expressions on iterators.
173 ///
174 /// **Why is this bad?** Readability. A simple `for` loop is shorter and conveys the intent better.
175 ///
176 /// **Known problems:** None
177 ///
178 /// **Example:** `while let Some(val) = iter() { .. }`
179 declare_lint! {
180     pub WHILE_LET_ON_ITERATOR,
181     Warn,
182     "using a while-let loop instead of a for loop on an iterator"
183 }
184
185 /// **What it does:** This warns when you iterate on a map (`HashMap` or `BTreeMap`) and ignore
186 /// either the keys or values.
187 ///
188 /// **Why is this bad?** Readability. There are `keys` and `values` methods that can be used to
189 /// express that don't need the values or keys.
190 ///
191 /// **Known problems:** None
192 ///
193 /// **Example:**
194 /// ```rust
195 /// for (k, _) in &map { .. }
196 /// ```
197 /// could be replaced by
198 /// ```rust
199 /// for k in map.keys() { .. }
200 /// ```
201 declare_lint! {
202     pub FOR_KV_MAP,
203     Warn,
204     "looping on a map using `iter` when `keys` or `values` would do"
205 }
206
207 #[derive(Copy, Clone)]
208 pub struct LoopsPass;
209
210 impl LintPass for LoopsPass {
211     fn get_lints(&self) -> LintArray {
212         lint_array!(NEEDLESS_RANGE_LOOP,
213                     EXPLICIT_ITER_LOOP,
214                     ITER_NEXT_LOOP,
215                     WHILE_LET_LOOP,
216                     UNUSED_COLLECT,
217                     REVERSE_RANGE_LOOP,
218                     EXPLICIT_COUNTER_LOOP,
219                     EMPTY_LOOP,
220                     WHILE_LET_ON_ITERATOR,
221                     FOR_KV_MAP)
222     }
223 }
224
225 impl LateLintPass for LoopsPass {
226     fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
227         if let Some((pat, arg, body)) = recover_for_loop(expr) {
228             check_for_loop(cx, pat, arg, body, expr);
229         }
230         // check for `loop { if let {} else break }` that could be `while let`
231         // (also matches an explicit "match" instead of "if let")
232         // (even if the "match" or "if let" is used for declaration)
233         if let ExprLoop(ref block, _) = expr.node {
234             // also check for empty `loop {}` statements
235             if block.stmts.is_empty() && block.expr.is_none() {
236                 span_lint(cx,
237                           EMPTY_LOOP,
238                           expr.span,
239                           "empty `loop {}` detected. You may want to either use `panic!()` or add \
240                            `std::thread::sleep(..);` to the loop body.");
241             }
242
243             // extract the expression from the first statement (if any) in a block
244             let inner_stmt_expr = extract_expr_from_first_stmt(block);
245             // or extract the first expression (if any) from the block
246             if let Some(inner) = inner_stmt_expr.or_else(|| extract_first_expr(block)) {
247                 if let ExprMatch(ref matchexpr, ref arms, ref source) = inner.node {
248                     // ensure "if let" compatible match structure
249                     match *source {
250                         MatchSource::Normal |
251                         MatchSource::IfLetDesugar { .. } => {
252                             if arms.len() == 2 && arms[0].pats.len() == 1 && arms[0].guard.is_none() &&
253                                arms[1].pats.len() == 1 && arms[1].guard.is_none() &&
254                                is_break_expr(&arms[1].body) {
255                                 if in_external_macro(cx, expr.span) {
256                                     return;
257                                 }
258
259                                 // NOTE: we used to make build a body here instead of using
260                                 // ellipsis, this was removed because:
261                                 // 1) it was ugly with big bodies;
262                                 // 2) it was not indented properly;
263                                 // 3) it wasn’t very smart (see #675).
264                                 span_lint_and_then(cx,
265                                                    WHILE_LET_LOOP,
266                                                    expr.span,
267                                                    "this loop could be written as a `while let` loop",
268                                                    |db| {
269                                                        let sug = format!("while let {} = {} {{ .. }}",
270                                                                          snippet(cx, arms[0].pats[0].span, ".."),
271                                                                          snippet(cx, matchexpr.span, ".."));
272                                                        db.span_suggestion(expr.span, "try", sug);
273                                                    });
274                             }
275                         }
276                         _ => (),
277                     }
278                 }
279             }
280         }
281         if let ExprMatch(ref match_expr, ref arms, MatchSource::WhileLetDesugar) = expr.node {
282             let pat = &arms[0].pats[0].node;
283             if let (&PatKind::TupleStruct(ref path, Some(ref pat_args)),
284                     &ExprMethodCall(method_name, _, ref method_args)) = (pat, &match_expr.node) {
285                 let iter_expr = &method_args[0];
286                 if let Some(lhs_constructor) = path.segments.last() {
287                     if method_name.node.as_str() == "next" &&
288                        match_trait_method(cx, match_expr, &paths::ITERATOR) &&
289                        lhs_constructor.identifier.name.as_str() == "Some" &&
290                        !is_iterator_used_after_while_let(cx, iter_expr) {
291                         let iterator = snippet(cx, method_args[0].span, "_");
292                         let loop_var = snippet(cx, pat_args[0].span, "_");
293                         span_help_and_lint(cx,
294                                            WHILE_LET_ON_ITERATOR,
295                                            expr.span,
296                                            "this loop could be written as a `for` loop",
297                                            &format!("try\nfor {} in {} {{...}}", loop_var, iterator));
298                     }
299                 }
300             }
301         }
302     }
303
304     fn check_stmt(&mut self, cx: &LateContext, stmt: &Stmt) {
305         if let StmtSemi(ref expr, _) = stmt.node {
306             if let ExprMethodCall(ref method, _, ref args) = expr.node {
307                 if args.len() == 1 && method.node.as_str() == "collect" &&
308                    match_trait_method(cx, expr, &paths::ITERATOR) {
309                     span_lint(cx,
310                               UNUSED_COLLECT,
311                               expr.span,
312                               "you are collect()ing an iterator and throwing away the result. \
313                                Consider using an explicit for loop to exhaust the iterator");
314                 }
315             }
316         }
317     }
318 }
319
320 fn check_for_loop(cx: &LateContext, pat: &Pat, arg: &Expr, body: &Expr, expr: &Expr) {
321     check_for_loop_range(cx, pat, arg, body, expr);
322     check_for_loop_reverse_range(cx, arg, expr);
323     check_for_loop_arg(cx, pat, arg, expr);
324     check_for_loop_explicit_counter(cx, arg, body, expr);
325     check_for_loop_over_map_kv(cx, pat, arg, body, expr);
326 }
327
328 /// Check for looping over a range and then indexing a sequence with it.
329 /// The iteratee must be a range literal.
330 fn check_for_loop_range(cx: &LateContext, pat: &Pat, arg: &Expr, body: &Expr, expr: &Expr) {
331     if let Some(UnsugaredRange { start: Some(ref start), ref end, .. }) = unsugar_range(arg) {
332         // the var must be a single name
333         if let PatKind::Ident(_, ref ident, _) = pat.node {
334             let mut visitor = VarVisitor {
335                 cx: cx,
336                 var: ident.node.name,
337                 indexed: HashMap::new(),
338                 nonindex: false,
339             };
340             walk_expr(&mut visitor, body);
341
342             // linting condition: we only indexed one variable
343             if visitor.indexed.len() == 1 {
344                 let (indexed, indexed_extent) = visitor.indexed
345                                                        .into_iter()
346                                                        .next()
347                                                        .unwrap_or_else(|| unreachable!() /* len == 1 */);
348
349                 // ensure that the indexed variable was declared before the loop, see #601
350                 if let Some(indexed_extent) = indexed_extent {
351                     let pat_extent = cx.tcx.region_maps.var_scope(pat.id);
352                     if cx.tcx.region_maps.is_subscope_of(indexed_extent, pat_extent) {
353                         return;
354                     }
355                 }
356
357                 let starts_at_zero = is_integer_literal(start, 0);
358
359                 let skip: Cow<_> = if starts_at_zero {
360                     "".into()
361                 } else {
362                     format!(".skip({})", snippet(cx, start.span, "..")).into()
363                 };
364
365                 let take: Cow<_> = if let Some(ref end) = *end {
366                     if is_len_call(end, &indexed) {
367                         "".into()
368                     } else {
369                         format!(".take({})", snippet(cx, end.span, "..")).into()
370                     }
371                 } else {
372                     "".into()
373                 };
374
375                 if visitor.nonindex {
376                     span_lint(cx,
377                               NEEDLESS_RANGE_LOOP,
378                               expr.span,
379                               &format!("the loop variable `{}` is used to index `{}`. Consider using `for ({}, \
380                                         item) in {}.iter().enumerate(){}{}` or similar iterators",
381                                        ident.node.name,
382                                        indexed,
383                                        ident.node.name,
384                                        indexed,
385                                        take,
386                                        skip));
387                 } else {
388                     let repl = if starts_at_zero && take.is_empty() {
389                         format!("&{}", indexed)
390                     } else {
391                         format!("{}.iter(){}{}", indexed, take, skip)
392                     };
393
394                     span_lint(cx,
395                               NEEDLESS_RANGE_LOOP,
396                               expr.span,
397                               &format!("the loop variable `{}` is only used to index `{}`. \
398                                         Consider using `for item in {}` or similar iterators",
399                                        ident.node.name,
400                                        indexed,
401                                        repl));
402                 }
403             }
404         }
405     }
406 }
407
408 fn is_len_call(expr: &Expr, var: &Name) -> bool {
409     if_let_chain! {[
410         let ExprMethodCall(method, _, ref len_args) = expr.node,
411         len_args.len() == 1,
412         method.node.as_str() == "len",
413         let ExprPath(_, ref path) = len_args[0].node,
414         path.segments.len() == 1,
415         &path.segments[0].identifier.name == var
416     ], {
417         return true;
418     }}
419
420     false
421 }
422
423 fn check_for_loop_reverse_range(cx: &LateContext, arg: &Expr, expr: &Expr) {
424     // if this for loop is iterating over a two-sided range...
425     if let Some(UnsugaredRange { start: Some(ref start), end: Some(ref end), limits }) = unsugar_range(arg) {
426         // ...and both sides are compile-time constant integers...
427         if let Ok(start_idx) = eval_const_expr_partial(cx.tcx, start, ExprTypeChecked, None) {
428             if let Ok(end_idx) = eval_const_expr_partial(cx.tcx, end, ExprTypeChecked, None) {
429                 // ...and the start index is greater than the end index,
430                 // this loop will never run. This is often confusing for developers
431                 // who think that this will iterate from the larger value to the
432                 // smaller value.
433                 let (sup, eq) = match (start_idx, end_idx) {
434                     (ConstVal::Integral(start_idx), ConstVal::Integral(end_idx)) => {
435                         (start_idx > end_idx, start_idx == end_idx)
436                     }
437                     _ => (false, false),
438                 };
439
440                 if sup {
441                     let start_snippet = snippet(cx, start.span, "_");
442                     let end_snippet = snippet(cx, end.span, "_");
443
444                     span_lint_and_then(cx,
445                                        REVERSE_RANGE_LOOP,
446                                        expr.span,
447                                        "this range is empty so this for loop will never run",
448                                        |db| {
449                                            db.span_suggestion(expr.span,
450                                                               "consider using the following if \
451                                                                you are attempting to iterate \
452                                                                over this range in reverse",
453                                                               format!("({}..{}).rev()` ", end_snippet, start_snippet));
454                                        });
455                 } else if eq && limits != ast::RangeLimits::Closed {
456                     // if they are equal, it's also problematic - this loop
457                     // will never run.
458                     span_lint(cx,
459                               REVERSE_RANGE_LOOP,
460                               expr.span,
461                               "this range is empty so this for loop will never run");
462                 }
463             }
464         }
465     }
466 }
467
468 fn check_for_loop_arg(cx: &LateContext, pat: &Pat, arg: &Expr, expr: &Expr) {
469     let mut next_loop_linted = false; // whether or not ITER_NEXT_LOOP lint was used
470     if let ExprMethodCall(ref method, _, ref args) = arg.node {
471         // just the receiver, no arguments
472         if args.len() == 1 {
473             let method_name = method.node;
474             // check for looping over x.iter() or x.iter_mut(), could use &x or &mut x
475             if method_name.as_str() == "iter" || method_name.as_str() == "iter_mut" {
476                 if is_ref_iterable_type(cx, &args[0]) {
477                     let object = snippet(cx, args[0].span, "_");
478                     span_lint(cx,
479                               EXPLICIT_ITER_LOOP,
480                               expr.span,
481                               &format!("it is more idiomatic to loop over `&{}{}` instead of `{}.{}()`",
482                                        if method_name.as_str() == "iter_mut" {
483                                            "mut "
484                                        } else {
485                                            ""
486                                        },
487                                        object,
488                                        object,
489                                        method_name));
490                 }
491             } else if method_name.as_str() == "next" && match_trait_method(cx, arg, &paths::ITERATOR) {
492                 span_lint(cx,
493                           ITER_NEXT_LOOP,
494                           expr.span,
495                           "you are iterating over `Iterator::next()` which is an Option; this will compile but is \
496                            probably not what you want");
497                 next_loop_linted = true;
498             }
499         }
500     }
501     if !next_loop_linted {
502         check_arg_type(cx, pat, arg);
503     }
504 }
505
506 /// Check for `for` loops over `Option`s and `Results`
507 fn check_arg_type(cx: &LateContext, pat: &Pat, arg: &Expr) {
508     let ty = cx.tcx.expr_ty(arg);
509     if match_type(cx, ty, &paths::OPTION) {
510         span_help_and_lint(cx,
511                            FOR_LOOP_OVER_OPTION,
512                            arg.span,
513                            &format!("for loop over `{0}`, which is an `Option`. This is more readably written as an \
514                                      `if let` statement.",
515                                     snippet(cx, arg.span, "_")),
516                            &format!("consider replacing `for {0} in {1}` with `if let Some({0}) = {1}`",
517                                     snippet(cx, pat.span, "_"),
518                                     snippet(cx, arg.span, "_")));
519     } else if match_type(cx, ty, &paths::RESULT) {
520         span_help_and_lint(cx,
521                            FOR_LOOP_OVER_RESULT,
522                            arg.span,
523                            &format!("for loop over `{0}`, which is a `Result`. This is more readably written as an \
524                                      `if let` statement.",
525                                     snippet(cx, arg.span, "_")),
526                            &format!("consider replacing `for {0} in {1}` with `if let Ok({0}) = {1}`",
527                                     snippet(cx, pat.span, "_"),
528                                     snippet(cx, arg.span, "_")));
529     }
530 }
531
532 fn check_for_loop_explicit_counter(cx: &LateContext, arg: &Expr, body: &Expr, expr: &Expr) {
533     // Look for variables that are incremented once per loop iteration.
534     let mut visitor = IncrementVisitor {
535         cx: cx,
536         states: HashMap::new(),
537         depth: 0,
538         done: false,
539     };
540     walk_expr(&mut visitor, body);
541
542     // For each candidate, check the parent block to see if
543     // it's initialized to zero at the start of the loop.
544     let map = &cx.tcx.map;
545     let parent_scope = map.get_enclosing_scope(expr.id).and_then(|id| map.get_enclosing_scope(id));
546     if let Some(parent_id) = parent_scope {
547         if let NodeBlock(block) = map.get(parent_id) {
548             for (id, _) in visitor.states.iter().filter(|&(_, v)| *v == VarState::IncrOnce) {
549                 let mut visitor2 = InitializeVisitor {
550                     cx: cx,
551                     end_expr: expr,
552                     var_id: *id,
553                     state: VarState::IncrOnce,
554                     name: None,
555                     depth: 0,
556                     past_loop: false,
557                 };
558                 walk_block(&mut visitor2, block);
559
560                 if visitor2.state == VarState::Warn {
561                     if let Some(name) = visitor2.name {
562                         span_lint(cx,
563                                   EXPLICIT_COUNTER_LOOP,
564                                   expr.span,
565                                   &format!("the variable `{0}` is used as a loop counter. Consider using `for ({0}, \
566                                             item) in {1}.enumerate()` or similar iterators",
567                                            name,
568                                            snippet(cx, arg.span, "_")));
569                     }
570                 }
571             }
572         }
573     }
574 }
575
576 /// Check for the `FOR_KV_MAP` lint.
577 fn check_for_loop_over_map_kv(cx: &LateContext, pat: &Pat, arg: &Expr, body: &Expr, expr: &Expr) {
578     if let PatKind::Tup(ref pat) = pat.node {
579         if pat.len() == 2 {
580             let (pat_span, kind) = match (&pat[0].node, &pat[1].node) {
581                 (key, _) if pat_is_wild(key, body) => (&pat[1].span, "values"),
582                 (_, value) if pat_is_wild(value, body) => (&pat[0].span, "keys"),
583                 _ => return,
584             };
585
586             let arg_span = match arg.node {
587                 ExprAddrOf(MutImmutable, ref expr) => expr.span,
588                 ExprAddrOf(MutMutable, _) => return, // for _ in &mut _, there is no {values,keys}_mut method
589                 _ => arg.span,
590             };
591
592             let ty = walk_ptrs_ty(cx.tcx.expr_ty(arg));
593             if match_type(cx, ty, &paths::HASHMAP) || match_type(cx, ty, &paths::BTREEMAP) {
594                 span_lint_and_then(cx,
595                                    FOR_KV_MAP,
596                                    expr.span,
597                                    &format!("you seem to want to iterate on a map's {}", kind),
598                                    |db| {
599                                        db.span_suggestion(expr.span,
600                                                           "use the corresponding method",
601                                                           format!("for {} in {}.{}() {{...}}",
602                                                                   snippet(cx, *pat_span, ".."),
603                                                                   snippet(cx, arg_span, ".."),
604                                                                   kind));
605                                    });
606             }
607         }
608     }
609
610 }
611
612 /// Return true if the pattern is a `PatWild` or an ident prefixed with `'_'`.
613 fn pat_is_wild(pat: &PatKind, body: &Expr) -> bool {
614     match *pat {
615         PatKind::Wild => true,
616         PatKind::Ident(_, ident, None) if ident.node.name.as_str().starts_with('_') => {
617             let mut visitor = UsedVisitor {
618                 var: ident.node,
619                 used: false,
620             };
621             walk_expr(&mut visitor, body);
622             !visitor.used
623         }
624         _ => false,
625     }
626 }
627
628 struct UsedVisitor {
629     var: Ident, // var to look for
630     used: bool, // has the var been used otherwise?
631 }
632
633 impl<'a> Visitor<'a> for UsedVisitor {
634     fn visit_expr(&mut self, expr: &Expr) {
635         if let ExprPath(None, ref path) = expr.node {
636             if path.segments.len() == 1 && path.segments[0].identifier == self.var {
637                 self.used = true;
638                 return;
639             }
640         }
641
642         walk_expr(self, expr);
643     }
644 }
645
646 struct VarVisitor<'v, 't: 'v> {
647     cx: &'v LateContext<'v, 't>, // context reference
648     var: Name, // var name to look for as index
649     indexed: HashMap<Name, Option<CodeExtent>>, // indexed variables, the extent is None for global
650     nonindex: bool, // has the var been used otherwise?
651 }
652
653 impl<'v, 't> Visitor<'v> for VarVisitor<'v, 't> {
654     fn visit_expr(&mut self, expr: &'v Expr) {
655         if let ExprPath(None, ref path) = expr.node {
656             if path.segments.len() == 1 && path.segments[0].identifier.name == self.var {
657                 // we are referencing our variable! now check if it's as an index
658                 if_let_chain! {
659                     [
660                         let Some(parexpr) = get_parent_expr(self.cx, expr),
661                         let ExprIndex(ref seqexpr, _) = parexpr.node,
662                         let ExprPath(None, ref seqvar) = seqexpr.node,
663                         seqvar.segments.len() == 1
664                     ], {
665                         let def_map = self.cx.tcx.def_map.borrow();
666                         if let Some(def) = def_map.get(&seqexpr.id) {
667                             match def.base_def {
668                                 Def::Local(..) | Def::Upvar(..) => {
669                                     let extent = self.cx.tcx.region_maps.var_scope(def.base_def.var_id());
670                                     self.indexed.insert(seqvar.segments[0].identifier.name, Some(extent));
671                                     return;  // no need to walk further
672                                 }
673                                 Def::Static(..) | Def::Const(..) => {
674                                     self.indexed.insert(seqvar.segments[0].identifier.name, None);
675                                     return;  // no need to walk further
676                                 }
677                                 _ => (),
678                             }
679                         }
680                     }
681                 }
682                 // we are not indexing anything, record that
683                 self.nonindex = true;
684                 return;
685             }
686         }
687         walk_expr(self, expr);
688     }
689 }
690
691 fn is_iterator_used_after_while_let(cx: &LateContext, iter_expr: &Expr) -> bool {
692     let def_id = match var_def_id(cx, iter_expr) {
693         Some(id) => id,
694         None => return false,
695     };
696     let mut visitor = VarUsedAfterLoopVisitor {
697         cx: cx,
698         def_id: def_id,
699         iter_expr_id: iter_expr.id,
700         past_while_let: false,
701         var_used_after_while_let: false,
702     };
703     if let Some(enclosing_block) = get_enclosing_block(cx, def_id) {
704         walk_block(&mut visitor, enclosing_block);
705     }
706     visitor.var_used_after_while_let
707 }
708
709 struct VarUsedAfterLoopVisitor<'v, 't: 'v> {
710     cx: &'v LateContext<'v, 't>,
711     def_id: NodeId,
712     iter_expr_id: NodeId,
713     past_while_let: bool,
714     var_used_after_while_let: bool,
715 }
716
717 impl<'v, 't> Visitor<'v> for VarUsedAfterLoopVisitor<'v, 't> {
718     fn visit_expr(&mut self, expr: &'v Expr) {
719         if self.past_while_let {
720             if Some(self.def_id) == var_def_id(self.cx, expr) {
721                 self.var_used_after_while_let = true;
722             }
723         } else if self.iter_expr_id == expr.id {
724             self.past_while_let = true;
725         }
726         walk_expr(self, expr);
727     }
728 }
729
730
731 /// Return true if the type of expr is one that provides `IntoIterator` impls
732 /// for `&T` and `&mut T`, such as `Vec`.
733 #[cfg_attr(rustfmt, rustfmt_skip)]
734 fn is_ref_iterable_type(cx: &LateContext, e: &Expr) -> bool {
735     // no walk_ptrs_ty: calling iter() on a reference can make sense because it
736     // will allow further borrows afterwards
737     let ty = cx.tcx.expr_ty(e);
738     is_iterable_array(ty) ||
739     match_type(cx, ty, &paths::VEC) ||
740     match_type(cx, ty, &paths::LINKED_LIST) ||
741     match_type(cx, ty, &paths::HASHMAP) ||
742     match_type(cx, ty, &paths::HASHSET) ||
743     match_type(cx, ty, &paths::VEC_DEQUE) ||
744     match_type(cx, ty, &paths::BINARY_HEAP) ||
745     match_type(cx, ty, &paths::BTREEMAP) ||
746     match_type(cx, ty, &paths::BTREESET)
747 }
748
749 fn is_iterable_array(ty: ty::Ty) -> bool {
750     // IntoIterator is currently only implemented for array sizes <= 32 in rustc
751     match ty.sty {
752         ty::TyArray(_, 0...32) => true,
753         _ => false,
754     }
755 }
756
757 /// If a block begins with a statement (possibly a `let` binding) and has an expression, return it.
758 fn extract_expr_from_first_stmt(block: &Block) -> Option<&Expr> {
759     if block.stmts.is_empty() {
760         return None;
761     }
762     if let StmtDecl(ref decl, _) = block.stmts[0].node {
763         if let DeclLocal(ref local) = decl.node {
764             if let Some(ref expr) = local.init {
765                 Some(expr)
766             } else {
767                 None
768             }
769         } else {
770             None
771         }
772     } else {
773         None
774     }
775 }
776
777 /// If a block begins with an expression (with or without semicolon), return it.
778 fn extract_first_expr(block: &Block) -> Option<&Expr> {
779     match block.expr {
780         Some(ref expr) => Some(expr),
781         None if !block.stmts.is_empty() => {
782             match block.stmts[0].node {
783                 StmtExpr(ref expr, _) |
784                 StmtSemi(ref expr, _) => Some(expr),
785                 _ => None,
786             }
787         }
788         _ => None,
789     }
790 }
791
792 /// Return true if expr contains a single break expr (maybe within a block).
793 fn is_break_expr(expr: &Expr) -> bool {
794     match expr.node {
795         ExprBreak(None) => true,
796         // there won't be a `let <pat> = break` and so we can safely ignore the StmtDecl case
797         ExprBlock(ref b) => {
798             match extract_first_expr(b) {
799                 Some(ref subexpr) => is_break_expr(subexpr),
800                 None => false,
801             }
802         }
803         _ => false,
804     }
805 }
806
807 // To trigger the EXPLICIT_COUNTER_LOOP lint, a variable must be
808 // incremented exactly once in the loop body, and initialized to zero
809 // at the start of the loop.
810 #[derive(PartialEq)]
811 enum VarState {
812     Initial, // Not examined yet
813     IncrOnce, // Incremented exactly once, may be a loop counter
814     Declared, // Declared but not (yet) initialized to zero
815     Warn,
816     DontWarn,
817 }
818
819 /// Scan a for loop for variables that are incremented exactly once.
820 struct IncrementVisitor<'v, 't: 'v> {
821     cx: &'v LateContext<'v, 't>, // context reference
822     states: HashMap<NodeId, VarState>, // incremented variables
823     depth: u32, // depth of conditional expressions
824     done: bool,
825 }
826
827 impl<'v, 't> Visitor<'v> for IncrementVisitor<'v, 't> {
828     fn visit_expr(&mut self, expr: &'v Expr) {
829         if self.done {
830             return;
831         }
832
833         // If node is a variable
834         if let Some(def_id) = var_def_id(self.cx, expr) {
835             if let Some(parent) = get_parent_expr(self.cx, expr) {
836                 let state = self.states.entry(def_id).or_insert(VarState::Initial);
837
838                 match parent.node {
839                     ExprAssignOp(op, ref lhs, ref rhs) => {
840                         if lhs.id == expr.id {
841                             if op.node == BiAdd && is_integer_literal(rhs, 1) {
842                                 *state = match *state {
843                                     VarState::Initial if self.depth == 0 => VarState::IncrOnce,
844                                     _ => VarState::DontWarn,
845                                 };
846                             } else {
847                                 // Assigned some other value
848                                 *state = VarState::DontWarn;
849                             }
850                         }
851                     }
852                     ExprAssign(ref lhs, _) if lhs.id == expr.id => *state = VarState::DontWarn,
853                     ExprAddrOf(mutability, _) if mutability == MutMutable => *state = VarState::DontWarn,
854                     _ => (),
855                 }
856             }
857         } else if is_loop(expr) {
858             self.states.clear();
859             self.done = true;
860             return;
861         } else if is_conditional(expr) {
862             self.depth += 1;
863             walk_expr(self, expr);
864             self.depth -= 1;
865             return;
866         }
867         walk_expr(self, expr);
868     }
869 }
870
871 /// Check whether a variable is initialized to zero at the start of a loop.
872 struct InitializeVisitor<'v, 't: 'v> {
873     cx: &'v LateContext<'v, 't>, // context reference
874     end_expr: &'v Expr, // the for loop. Stop scanning here.
875     var_id: NodeId,
876     state: VarState,
877     name: Option<Name>,
878     depth: u32, // depth of conditional expressions
879     past_loop: bool,
880 }
881
882 impl<'v, 't> Visitor<'v> for InitializeVisitor<'v, 't> {
883     fn visit_decl(&mut self, decl: &'v Decl) {
884         // Look for declarations of the variable
885         if let DeclLocal(ref local) = decl.node {
886             if local.pat.id == self.var_id {
887                 if let PatKind::Ident(_, ref ident, _) = local.pat.node {
888                     self.name = Some(ident.node.name);
889
890                     self.state = if let Some(ref init) = local.init {
891                         if is_integer_literal(init, 0) {
892                             VarState::Warn
893                         } else {
894                             VarState::Declared
895                         }
896                     } else {
897                         VarState::Declared
898                     }
899                 }
900             }
901         }
902         walk_decl(self, decl);
903     }
904
905     fn visit_expr(&mut self, expr: &'v Expr) {
906         if self.state == VarState::DontWarn {
907             return;
908         }
909         if expr == self.end_expr {
910             self.past_loop = true;
911             return;
912         }
913         // No need to visit expressions before the variable is
914         // declared
915         if self.state == VarState::IncrOnce {
916             return;
917         }
918
919         // If node is the desired variable, see how it's used
920         if var_def_id(self.cx, expr) == Some(self.var_id) {
921             if let Some(parent) = get_parent_expr(self.cx, expr) {
922                 match parent.node {
923                     ExprAssignOp(_, ref lhs, _) if lhs.id == expr.id => {
924                         self.state = VarState::DontWarn;
925                     }
926                     ExprAssign(ref lhs, ref rhs) if lhs.id == expr.id => {
927                         self.state = if is_integer_literal(rhs, 0) && self.depth == 0 {
928                             VarState::Warn
929                         } else {
930                             VarState::DontWarn
931                         }
932                     }
933                     ExprAddrOf(mutability, _) if mutability == MutMutable => self.state = VarState::DontWarn,
934                     _ => (),
935                 }
936             }
937
938             if self.past_loop {
939                 self.state = VarState::DontWarn;
940                 return;
941             }
942         } else if !self.past_loop && is_loop(expr) {
943             self.state = VarState::DontWarn;
944             return;
945         } else if is_conditional(expr) {
946             self.depth += 1;
947             walk_expr(self, expr);
948             self.depth -= 1;
949             return;
950         }
951         walk_expr(self, expr);
952     }
953 }
954
955 fn var_def_id(cx: &LateContext, expr: &Expr) -> Option<NodeId> {
956     if let Some(path_res) = cx.tcx.def_map.borrow().get(&expr.id) {
957         if let Def::Local(_, node_id) = path_res.base_def {
958             return Some(node_id);
959         }
960     }
961     None
962 }
963
964 fn is_loop(expr: &Expr) -> bool {
965     match expr.node {
966         ExprLoop(..) | ExprWhile(..) => true,
967         _ => false,
968     }
969 }
970
971 fn is_conditional(expr: &Expr) -> bool {
972     match expr.node {
973         ExprIf(..) | ExprMatch(..) => true,
974         _ => false,
975     }
976 }