]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/loops.rs
add lint declaration and example that should trigger the lint
[rust.git] / clippy_lints / src / loops.rs
1 use itertools::Itertools;
2 use reexport::*;
3 use rustc::hir::*;
4 use rustc::hir::def::Def;
5 use rustc::hir::intravisit::{walk_block, walk_decl, walk_expr, walk_pat, walk_stmt, NestedVisitorMap, Visitor};
6 use rustc::hir::map::Node::{NodeBlock, NodeExpr, NodeStmt};
7 use rustc::lint::*;
8 use rustc::middle::const_val::ConstVal;
9 use rustc::middle::region;
10 use rustc::ty::{self, Ty};
11 use rustc::ty::subst::{Subst, Substs};
12 use rustc_const_eval::ConstContext;
13 use std::collections::{HashMap, HashSet};
14 use syntax::ast;
15 use utils::sugg;
16 use utils::const_to_u64;
17
18 use utils::{get_enclosing_block, get_parent_expr, higher, in_external_macro, is_integer_literal, is_refutable,
19             last_path_segment, match_trait_method, match_type, match_var, multispan_sugg, snippet, snippet_opt,
20             span_help_and_lint, span_lint, span_lint_and_sugg, span_lint_and_then};
21 use utils::paths;
22
23 /// **What it does:** Checks for for-loops that manually copy items between
24 /// slices that could be optimized by having a memcpy.
25 ///
26 /// **Why is this bad?** It is not as fast as a memcpy.
27 ///
28 /// **Known problems:** None.
29 ///
30 /// **Example:**
31 /// ```rust
32 /// for i in 0..src.len() {
33 ///     dst[i + 64] = src[i];
34 /// }
35 /// ```
36 declare_lint! {
37     pub MANUAL_MEMCPY,
38     Warn,
39     "manually copying items between slices"
40 }
41
42 /// **What it does:** Checks for looping over the range of `0..len` of some
43 /// collection just to get the values by index.
44 ///
45 /// **Why is this bad?** Just iterating the collection itself makes the intent
46 /// more clear and is probably faster.
47 ///
48 /// **Known problems:** None.
49 ///
50 /// **Example:**
51 /// ```rust
52 /// for i in 0..vec.len() {
53 ///     println!("{}", vec[i]);
54 /// }
55 /// ```
56 declare_lint! {
57     pub NEEDLESS_RANGE_LOOP,
58     Warn,
59     "for-looping over a range of indices where an iterator over items would do"
60 }
61
62 /// **What it does:** Checks for loops on `x.iter()` where `&x` will do, and
63 /// suggests the latter.
64 ///
65 /// **Why is this bad?** Readability.
66 ///
67 /// **Known problems:** False negatives. We currently only warn on some known
68 /// types.
69 ///
70 /// **Example:**
71 /// ```rust
72 /// // with `y` a `Vec` or slice:
73 /// for x in y.iter() { .. }
74 /// ```
75 declare_lint! {
76     pub EXPLICIT_ITER_LOOP,
77     Warn,
78     "for-looping over `_.iter()` or `_.iter_mut()` when `&_` or `&mut _` would do"
79 }
80
81 /// **What it does:** Checks for loops on `y.into_iter()` where `y` will do, and
82 /// suggests the latter.
83 ///
84 /// **Why is this bad?** Readability.
85 ///
86 /// **Known problems:** None
87 ///
88 /// **Example:**
89 /// ```rust
90 /// // with `y` a `Vec` or slice:
91 /// for x in y.into_iter() { .. }
92 /// ```
93 declare_lint! {
94     pub EXPLICIT_INTO_ITER_LOOP,
95     Warn,
96     "for-looping over `_.into_iter()` when `_` would do"
97 }
98
99 /// **What it does:** Checks for loops on `x.next()`.
100 ///
101 /// **Why is this bad?** `next()` returns either `Some(value)` if there was a
102 /// value, or `None` otherwise. The insidious thing is that `Option<_>`
103 /// implements `IntoIterator`, so that possibly one value will be iterated,
104 /// leading to some hard to find bugs. No one will want to write such code
105 /// [except to win an Underhanded Rust
106 /// Contest](https://www.reddit.
107 /// com/r/rust/comments/3hb0wm/underhanded_rust_contest/cu5yuhr).
108 ///
109 /// **Known problems:** None.
110 ///
111 /// **Example:**
112 /// ```rust
113 /// for x in y.next() { .. }
114 /// ```
115 declare_lint! {
116     pub ITER_NEXT_LOOP,
117     Warn,
118     "for-looping over `_.next()` which is probably not intended"
119 }
120
121 /// **What it does:** Checks for `for` loops over `Option` values.
122 ///
123 /// **Why is this bad?** Readability. This is more clearly expressed as an `if
124 /// let`.
125 ///
126 /// **Known problems:** None.
127 ///
128 /// **Example:**
129 /// ```rust
130 /// for x in option { .. }
131 /// ```
132 ///
133 /// This should be
134 /// ```rust
135 /// if let Some(x) = option { .. }
136 /// ```
137 declare_lint! {
138     pub FOR_LOOP_OVER_OPTION,
139     Warn,
140     "for-looping over an `Option`, which is more clearly expressed as an `if let`"
141 }
142
143 /// **What it does:** Checks for `for` loops over `Result` values.
144 ///
145 /// **Why is this bad?** Readability. This is more clearly expressed as an `if
146 /// let`.
147 ///
148 /// **Known problems:** None.
149 ///
150 /// **Example:**
151 /// ```rust
152 /// for x in result { .. }
153 /// ```
154 ///
155 /// This should be
156 /// ```rust
157 /// if let Ok(x) = result { .. }
158 /// ```
159 declare_lint! {
160     pub FOR_LOOP_OVER_RESULT,
161     Warn,
162     "for-looping over a `Result`, which is more clearly expressed as an `if let`"
163 }
164
165 /// **What it does:** Detects `loop + match` combinations that are easier
166 /// written as a `while let` loop.
167 ///
168 /// **Why is this bad?** The `while let` loop is usually shorter and more
169 /// readable.
170 ///
171 /// **Known problems:** Sometimes the wrong binding is displayed (#383).
172 ///
173 /// **Example:**
174 /// ```rust
175 /// loop {
176 ///     let x = match y {
177 ///         Some(x) => x,
178 ///         None => break,
179 ///     }
180 ///     // .. do something with x
181 /// }
182 /// // is easier written as
183 /// while let Some(x) = y {
184 ///     // .. do something with x
185 /// }
186 /// ```
187 declare_lint! {
188     pub WHILE_LET_LOOP,
189     Warn,
190     "`loop { if let { ... } else break }`, which can be written as a `while let` loop"
191 }
192
193 /// **What it does:** Checks for using `collect()` on an iterator without using
194 /// the result.
195 ///
196 /// **Why is this bad?** It is more idiomatic to use a `for` loop over the
197 /// iterator instead.
198 ///
199 /// **Known problems:** None.
200 ///
201 /// **Example:**
202 /// ```rust
203 /// vec.iter().map(|x| /* some operation returning () */).collect::<Vec<_>>();
204 /// ```
205 declare_lint! {
206     pub UNUSED_COLLECT,
207     Warn,
208     "`collect()`ing an iterator without using the result; this is usually better \
209      written as a for loop"
210 }
211
212 /// **What it does:** Checks for loops over ranges `x..y` where both `x` and `y`
213 /// are constant and `x` is greater or equal to `y`, unless the range is
214 /// reversed or has a negative `.step_by(_)`.
215 ///
216 /// **Why is it bad?** Such loops will either be skipped or loop until
217 /// wrap-around (in debug code, this may `panic!()`). Both options are probably
218 /// not intended.
219 ///
220 /// **Known problems:** The lint cannot catch loops over dynamically defined
221 /// ranges. Doing this would require simulating all possible inputs and code
222 /// paths through the program, which would be complex and error-prone.
223 ///
224 /// **Example:**
225 /// ```rust
226 /// for x in 5..10-5 { .. } // oops, stray `-`
227 /// ```
228 declare_lint! {
229     pub REVERSE_RANGE_LOOP,
230     Warn,
231     "iteration over an empty range, such as `10..0` or `5..5`"
232 }
233
234 /// **What it does:** Checks `for` loops over slices with an explicit counter
235 /// and suggests the use of `.enumerate()`.
236 ///
237 /// **Why is it bad?** Not only is the version using `.enumerate()` more
238 /// readable, the compiler is able to remove bounds checks which can lead to
239 /// faster code in some instances.
240 ///
241 /// **Known problems:** None.
242 ///
243 /// **Example:**
244 /// ```rust
245 /// for i in 0..v.len() { foo(v[i]);
246 /// for i in 0..v.len() { bar(i, v[i]); }
247 /// ```
248 declare_lint! {
249     pub EXPLICIT_COUNTER_LOOP,
250     Warn,
251     "for-looping with an explicit counter when `_.enumerate()` would do"
252 }
253
254 /// **What it does:** Checks for empty `loop` expressions.
255 ///
256 /// **Why is this bad?** Those busy loops burn CPU cycles without doing
257 /// anything. Think of the environment and either block on something or at least
258 /// make the thread sleep for some microseconds.
259 ///
260 /// **Known problems:** None.
261 ///
262 /// **Example:**
263 /// ```rust
264 /// loop {}
265 /// ```
266 declare_lint! {
267     pub EMPTY_LOOP,
268     Warn,
269     "empty `loop {}`, which should block or sleep"
270 }
271
272 /// **What it does:** Checks for `while let` expressions on iterators.
273 ///
274 /// **Why is this bad?** Readability. A simple `for` loop is shorter and conveys
275 /// the intent better.
276 ///
277 /// **Known problems:** None.
278 ///
279 /// **Example:**
280 /// ```rust
281 /// while let Some(val) = iter() { .. }
282 /// ```
283 declare_lint! {
284     pub WHILE_LET_ON_ITERATOR,
285     Warn,
286     "using a while-let loop instead of a for loop on an iterator"
287 }
288
289 /// **What it does:** Checks for iterating a map (`HashMap` or `BTreeMap`) and
290 /// ignoring either the keys or values.
291 ///
292 /// **Why is this bad?** Readability. There are `keys` and `values` methods that
293 /// can be used to express that don't need the values or keys.
294 ///
295 /// **Known problems:** None.
296 ///
297 /// **Example:**
298 /// ```rust
299 /// for (k, _) in &map { .. }
300 /// ```
301 ///
302 /// could be replaced by
303 ///
304 /// ```rust
305 /// for k in map.keys() { .. }
306 /// ```
307 declare_lint! {
308     pub FOR_KV_MAP,
309     Warn,
310     "looping on a map using `iter` when `keys` or `values` would do"
311 }
312
313 /// **What it does:** Checks for loops that will always `break`, `return` or
314 /// `continue` an outer loop.
315 ///
316 /// **Why is this bad?** This loop never loops, all it does is obfuscating the
317 /// code.
318 ///
319 /// **Known problems:** None
320 ///
321 /// **Example:**
322 /// ```rust
323 /// loop { ..; break; }
324 /// ```
325 declare_lint! {
326     pub NEVER_LOOP,
327     Warn,
328     "any loop that will always `break` or `return`"
329 }
330
331 /// TODO: add documentation
332
333 declare_lint! {
334     pub MUT_RANGE_BOUND,
335     Warn,
336     "for loop over a range where one of the bounds is a mutable variable"
337 }
338
339 #[derive(Copy, Clone)]
340 pub struct Pass;
341
342 impl LintPass for Pass {
343     fn get_lints(&self) -> LintArray {
344         lint_array!(
345             MANUAL_MEMCPY,
346             NEEDLESS_RANGE_LOOP,
347             EXPLICIT_ITER_LOOP,
348             EXPLICIT_INTO_ITER_LOOP,
349             ITER_NEXT_LOOP,
350             FOR_LOOP_OVER_RESULT,
351             FOR_LOOP_OVER_OPTION,
352             WHILE_LET_LOOP,
353             UNUSED_COLLECT,
354             REVERSE_RANGE_LOOP,
355             EXPLICIT_COUNTER_LOOP,
356             EMPTY_LOOP,
357             WHILE_LET_ON_ITERATOR,
358             FOR_KV_MAP,
359             NEVER_LOOP, 
360             MUT_RANGE_BOUND
361         )
362     }
363 }
364
365 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
366     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
367         if let Some((pat, arg, body)) = higher::for_loop(expr) {
368             check_for_loop(cx, pat, arg, body, expr);
369         }
370
371         // check for never_loop
372         match expr.node {
373             ExprWhile(_, ref block, _) |
374             ExprLoop(ref block, _, _) => {
375                 if never_loop(block, &expr.id) {
376                     span_lint(cx, NEVER_LOOP, expr.span, "this loop never actually loops");
377                 }
378             },
379             _ => (),
380         }
381
382         // check for `loop { if let {} else break }` that could be `while let`
383         // (also matches an explicit "match" instead of "if let")
384         // (even if the "match" or "if let" is used for declaration)
385         if let ExprLoop(ref block, _, LoopSource::Loop) = expr.node {
386             // also check for empty `loop {}` statements
387             if block.stmts.is_empty() && block.expr.is_none() {
388                 span_lint(
389                     cx,
390                     EMPTY_LOOP,
391                     expr.span,
392                     "empty `loop {}` detected. You may want to either use `panic!()` or add \
393                      `std::thread::sleep(..);` to the loop body.",
394                 );
395             }
396
397             // extract the expression from the first statement (if any) in a block
398             let inner_stmt_expr = extract_expr_from_first_stmt(block);
399             // or extract the first expression (if any) from the block
400             if let Some(inner) = inner_stmt_expr.or_else(|| extract_first_expr(block)) {
401                 if let ExprMatch(ref matchexpr, ref arms, ref source) = inner.node {
402                     // ensure "if let" compatible match structure
403                     match *source {
404                         MatchSource::Normal |
405                         MatchSource::IfLetDesugar { .. } => {
406                             if arms.len() == 2 && arms[0].pats.len() == 1 && arms[0].guard.is_none() &&
407                                 arms[1].pats.len() == 1 && arms[1].guard.is_none() &&
408                                 is_simple_break_expr(&arms[1].body)
409                             {
410                                 if in_external_macro(cx, expr.span) {
411                                     return;
412                                 }
413
414                                 // NOTE: we used to make build a body here instead of using
415                                 // ellipsis, this was removed because:
416                                 // 1) it was ugly with big bodies;
417                                 // 2) it was not indented properly;
418                                 // 3) it wasn’t very smart (see #675).
419                                 span_lint_and_sugg(
420                                     cx,
421                                     WHILE_LET_LOOP,
422                                     expr.span,
423                                     "this loop could be written as a `while let` loop",
424                                     "try",
425                                     format!(
426                                         "while let {} = {} {{ .. }}",
427                                         snippet(cx, arms[0].pats[0].span, ".."),
428                                         snippet(cx, matchexpr.span, "..")
429                                     ),
430                                 );
431                             }
432                         },
433                         _ => (),
434                     }
435                 }
436             }
437         }
438         if let ExprMatch(ref match_expr, ref arms, MatchSource::WhileLetDesugar) = expr.node {
439             let pat = &arms[0].pats[0].node;
440             if let (&PatKind::TupleStruct(ref qpath, ref pat_args, _),
441                     &ExprMethodCall(ref method_path, _, ref method_args)) = (pat, &match_expr.node)
442             {
443                 let iter_expr = &method_args[0];
444                 let lhs_constructor = last_path_segment(qpath);
445                 if method_path.name == "next" && match_trait_method(cx, match_expr, &paths::ITERATOR) &&
446                     lhs_constructor.name == "Some" && !is_refutable(cx, &pat_args[0]) &&
447                     !is_iterator_used_after_while_let(cx, iter_expr) &&
448                     !is_nested(cx, expr, &method_args[0])
449                 {
450                     let iterator = snippet(cx, method_args[0].span, "_");
451                     let loop_var = snippet(cx, pat_args[0].span, "_");
452                     span_lint_and_sugg(
453                         cx,
454                         WHILE_LET_ON_ITERATOR,
455                         expr.span,
456                         "this loop could be written as a `for` loop",
457                         "try",
458                         format!("for {} in {} {{ .. }}", loop_var, iterator),
459                     );
460                 }
461             }
462         }
463     }
464
465     fn check_stmt(&mut self, cx: &LateContext<'a, 'tcx>, stmt: &'tcx Stmt) {
466         if let StmtSemi(ref expr, _) = stmt.node {
467             if let ExprMethodCall(ref method, _, ref args) = expr.node {
468                 if args.len() == 1 && method.name == "collect" && match_trait_method(cx, expr, &paths::ITERATOR) {
469                     span_lint(
470                         cx,
471                         UNUSED_COLLECT,
472                         expr.span,
473                         "you are collect()ing an iterator and throwing away the result. \
474                          Consider using an explicit for loop to exhaust the iterator",
475                     );
476                 }
477             }
478         }
479     }
480 }
481
482 fn never_loop(block: &Block, id: &NodeId) -> bool {
483     !contains_continue_block(block, id) && loop_exit_block(block)
484 }
485
486 fn contains_continue_block(block: &Block, dest: &NodeId) -> bool {
487     block.stmts.iter().any(|e| contains_continue_stmt(e, dest)) ||
488         block.expr.as_ref().map_or(
489             false,
490             |e| contains_continue_expr(e, dest),
491         )
492 }
493
494 fn contains_continue_stmt(stmt: &Stmt, dest: &NodeId) -> bool {
495     match stmt.node {
496         StmtSemi(ref e, _) |
497         StmtExpr(ref e, _) => contains_continue_expr(e, dest),
498         StmtDecl(ref d, _) => contains_continue_decl(d, dest),
499     }
500 }
501
502 fn contains_continue_decl(decl: &Decl, dest: &NodeId) -> bool {
503     match decl.node {
504         DeclLocal(ref local) => {
505             local.init.as_ref().map_or(
506                 false,
507                 |e| contains_continue_expr(e, dest),
508             )
509         },
510         _ => false,
511     }
512 }
513
514 fn contains_continue_expr(expr: &Expr, dest: &NodeId) -> bool {
515     match expr.node {
516         ExprRet(Some(ref e)) |
517         ExprBox(ref e) |
518         ExprUnary(_, ref e) |
519         ExprCast(ref e, _) |
520         ExprType(ref e, _) |
521         ExprField(ref e, _) |
522         ExprTupField(ref e, _) |
523         ExprAddrOf(_, ref e) |
524         ExprRepeat(ref e, _) => contains_continue_expr(e, dest),
525         ExprArray(ref es) |
526         ExprMethodCall(_, _, ref es) |
527         ExprTup(ref es) => es.iter().any(|e| contains_continue_expr(e, dest)),
528         ExprCall(ref e, ref es) => {
529             contains_continue_expr(e, dest) || es.iter().any(|e| contains_continue_expr(e, dest))
530         },
531         ExprBinary(_, ref e1, ref e2) |
532         ExprAssign(ref e1, ref e2) |
533         ExprAssignOp(_, ref e1, ref e2) |
534         ExprIndex(ref e1, ref e2) => [e1, e2].iter().any(|e| contains_continue_expr(e, dest)),
535         ExprIf(ref e, ref e2, ref e3) => {
536             [e, e2].iter().chain(e3.as_ref().iter()).any(|e| {
537                 contains_continue_expr(e, dest)
538             })
539         },
540         ExprWhile(ref e, ref b, _) => contains_continue_expr(e, dest) || contains_continue_block(b, dest),
541         ExprMatch(ref e, ref arms, _) => {
542             contains_continue_expr(e, dest) || arms.iter().any(|a| contains_continue_expr(&a.body, dest))
543         },
544         ExprBlock(ref block) |
545         ExprLoop(ref block, ..) => contains_continue_block(block, dest),
546         ExprStruct(_, _, ref base) => {
547             base.as_ref().map_or(
548                 false,
549                 |e| contains_continue_expr(e, dest),
550             )
551         },
552         ExprAgain(d) => d.target_id.opt_id().map_or(false, |id| id == *dest),
553         _ => false,
554     }
555 }
556
557 fn loop_exit_block(block: &Block) -> bool {
558     block.stmts.iter().any(|e| loop_exit_stmt(e)) || block.expr.as_ref().map_or(false, |e| loop_exit_expr(e))
559 }
560
561 fn loop_exit_stmt(stmt: &Stmt) -> bool {
562     match stmt.node {
563         StmtSemi(ref e, _) |
564         StmtExpr(ref e, _) => loop_exit_expr(e),
565         StmtDecl(ref d, _) => loop_exit_decl(d),
566     }
567 }
568
569 fn loop_exit_decl(decl: &Decl) -> bool {
570     match decl.node {
571         DeclLocal(ref local) => local.init.as_ref().map_or(false, |e| loop_exit_expr(e)),
572         _ => false,
573     }
574 }
575
576 fn loop_exit_expr(expr: &Expr) -> bool {
577     match expr.node {
578         ExprBox(ref e) |
579         ExprUnary(_, ref e) |
580         ExprCast(ref e, _) |
581         ExprType(ref e, _) |
582         ExprField(ref e, _) |
583         ExprTupField(ref e, _) |
584         ExprAddrOf(_, ref e) |
585         ExprRepeat(ref e, _) => loop_exit_expr(e),
586         ExprArray(ref es) |
587         ExprMethodCall(_, _, ref es) |
588         ExprTup(ref es) => es.iter().any(|e| loop_exit_expr(e)),
589         ExprCall(ref e, ref es) => loop_exit_expr(e) || es.iter().any(|e| loop_exit_expr(e)),
590         ExprBinary(_, ref e1, ref e2) |
591         ExprAssign(ref e1, ref e2) |
592         ExprAssignOp(_, ref e1, ref e2) |
593         ExprIndex(ref e1, ref e2) => [e1, e2].iter().any(|e| loop_exit_expr(e)),
594         ExprIf(ref e, ref e2, ref e3) => {
595             loop_exit_expr(e) || e3.as_ref().map_or(false, |e| loop_exit_expr(e)) && loop_exit_expr(e2)
596         },
597         ExprWhile(ref e, ref b, _) => loop_exit_expr(e) || loop_exit_block(b),
598         ExprMatch(ref e, ref arms, _) => loop_exit_expr(e) || arms.iter().all(|a| loop_exit_expr(&a.body)),
599         ExprBlock(ref b) => loop_exit_block(b),
600         ExprBreak(_, _) | ExprAgain(_) | ExprRet(_) => true,
601         _ => false,
602     }
603 }
604
605 fn check_for_loop<'a, 'tcx>(
606     cx: &LateContext<'a, 'tcx>,
607     pat: &'tcx Pat,
608     arg: &'tcx Expr,
609     body: &'tcx Expr,
610     expr: &'tcx Expr,
611 ) {
612     check_for_loop_range(cx, pat, arg, body, expr);
613     check_for_loop_reverse_range(cx, arg, expr);
614     check_for_loop_arg(cx, pat, arg, expr);
615     check_for_loop_explicit_counter(cx, arg, body, expr);
616     check_for_loop_over_map_kv(cx, pat, arg, body, expr);
617     detect_manual_memcpy(cx, pat, arg, body, expr);
618 }
619
620 fn same_var<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &Expr, var: ast::NodeId) -> bool {
621     if_let_chain! {[
622         let ExprPath(ref qpath) = expr.node,
623         let QPath::Resolved(None, ref path) = *qpath,
624         path.segments.len() == 1,
625         let Def::Local(local_id) = cx.tables.qpath_def(qpath, expr.hir_id),
626         // our variable!
627         local_id == var
628     ], {
629         return true;
630     }}
631
632     false
633 }
634
635 struct Offset {
636     value: String,
637     negate: bool,
638 }
639
640 impl Offset {
641     fn negative(s: String) -> Self {
642         Self {
643             value: s,
644             negate: true,
645         }
646     }
647
648     fn positive(s: String) -> Self {
649         Self {
650             value: s,
651             negate: false,
652         }
653     }
654 }
655
656 struct FixedOffsetVar {
657     var_name: String,
658     offset: Offset,
659 }
660
661 fn is_slice_like<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, ty: Ty) -> bool {
662     let is_slice = match ty.sty {
663         ty::TyRef(_, ref subty) => is_slice_like(cx, subty.ty),
664         ty::TySlice(..) | ty::TyArray(..) => true,
665         _ => false,
666     };
667
668     is_slice || match_type(cx, ty, &paths::VEC) || match_type(cx, ty, &paths::VEC_DEQUE)
669 }
670
671 fn get_fixed_offset_var<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &Expr, var: ast::NodeId) -> Option<FixedOffsetVar> {
672     fn extract_offset<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, e: &Expr, var: ast::NodeId) -> Option<String> {
673         match e.node {
674             ExprLit(ref l) => {
675                 match l.node {
676                     ast::LitKind::Int(x, _ty) => Some(x.to_string()),
677                     _ => None,
678                 }
679             },
680             ExprPath(..) if !same_var(cx, e, var) => Some(snippet_opt(cx, e.span).unwrap_or_else(|| "??".into())),
681             _ => None,
682         }
683     }
684
685     if let ExprIndex(ref seqexpr, ref idx) = expr.node {
686         let ty = cx.tables.expr_ty(seqexpr);
687         if !is_slice_like(cx, ty) {
688             return None;
689         }
690
691         let offset = match idx.node {
692             ExprBinary(op, ref lhs, ref rhs) => {
693                 match op.node {
694                     BinOp_::BiAdd => {
695                         let offset_opt = if same_var(cx, lhs, var) {
696                             extract_offset(cx, rhs, var)
697                         } else if same_var(cx, rhs, var) {
698                             extract_offset(cx, lhs, var)
699                         } else {
700                             None
701                         };
702
703                         offset_opt.map(Offset::positive)
704                     },
705                     BinOp_::BiSub if same_var(cx, lhs, var) => extract_offset(cx, rhs, var).map(Offset::negative),
706                     _ => None,
707                 }
708             },
709             ExprPath(..) => {
710                 if same_var(cx, idx, var) {
711                     Some(Offset::positive("0".into()))
712                 } else {
713                     None
714                 }
715             },
716             _ => None,
717         };
718
719         offset.map(|o| {
720             FixedOffsetVar {
721                 var_name: snippet_opt(cx, seqexpr.span).unwrap_or_else(|| "???".into()),
722                 offset: o,
723             }
724         })
725     } else {
726         None
727     }
728 }
729
730 fn fetch_cloned_fixed_offset_var<'a, 'tcx>(
731     cx: &LateContext<'a, 'tcx>,
732     expr: &Expr,
733     var: ast::NodeId,
734 ) -> Option<FixedOffsetVar> {
735     if_let_chain! {[
736         let ExprMethodCall(ref method, _, ref args) = expr.node,
737         method.name == "clone",
738         args.len() == 1,
739         let Some(arg) = args.get(0),
740     ], {
741         return get_fixed_offset_var(cx, arg, var);
742     }}
743
744     get_fixed_offset_var(cx, expr, var)
745 }
746
747 fn get_indexed_assignments<'a, 'tcx>(
748     cx: &LateContext<'a, 'tcx>,
749     body: &Expr,
750     var: ast::NodeId,
751 ) -> Vec<(FixedOffsetVar, FixedOffsetVar)> {
752     fn get_assignment<'a, 'tcx>(
753         cx: &LateContext<'a, 'tcx>,
754         e: &Expr,
755         var: ast::NodeId,
756     ) -> Option<(FixedOffsetVar, FixedOffsetVar)> {
757         if let Expr_::ExprAssign(ref lhs, ref rhs) = e.node {
758             match (get_fixed_offset_var(cx, lhs, var), fetch_cloned_fixed_offset_var(cx, rhs, var)) {
759                 (Some(offset_left), Some(offset_right)) => Some((offset_left, offset_right)),
760                 _ => None,
761             }
762         } else {
763             None
764         }
765     }
766
767     if let Expr_::ExprBlock(ref b) = body.node {
768         let Block {
769             ref stmts,
770             ref expr,
771             ..
772         } = **b;
773
774         stmts
775             .iter()
776             .map(|stmt| match stmt.node {
777                 Stmt_::StmtDecl(..) => None,
778                 Stmt_::StmtExpr(ref e, _node_id) |
779                 Stmt_::StmtSemi(ref e, _node_id) => Some(get_assignment(cx, e, var)),
780             })
781             .chain(expr.as_ref().into_iter().map(|e| {
782                 Some(get_assignment(cx, &*e, var))
783             }))
784             .filter_map(|op| op)
785             .collect::<Option<Vec<_>>>()
786             .unwrap_or_else(|| vec![])
787     } else {
788         get_assignment(cx, body, var).into_iter().collect()
789     }
790 }
791
792 /// Check for for loops that sequentially copy items from one slice-like
793 /// object to another.
794 fn detect_manual_memcpy<'a, 'tcx>(
795     cx: &LateContext<'a, 'tcx>,
796     pat: &'tcx Pat,
797     arg: &'tcx Expr,
798     body: &'tcx Expr,
799     expr: &'tcx Expr,
800 ) {
801     if let Some(higher::Range {
802                     start: Some(start),
803                     ref end,
804                     limits,
805                 }) = higher::range(arg)
806     {
807         // the var must be a single name
808         if let PatKind::Binding(_, canonical_id, _, _) = pat.node {
809             let print_sum = |arg1: &Offset, arg2: &Offset| -> String {
810                 match (&arg1.value[..], arg1.negate, &arg2.value[..], arg2.negate) {
811                     ("0", _, "0", _) => "".into(),
812                     ("0", _, x, false) |
813                     (x, false, "0", false) => x.into(),
814                     ("0", _, x, true) |
815                     (x, false, "0", true) => format!("-{}", x),
816                     (x, false, y, false) => format!("({} + {})", x, y),
817                     (x, false, y, true) => format!("({} - {})", x, y),
818                     (x, true, y, false) => format!("({} - {})", y, x),
819                     (x, true, y, true) => format!("-({} + {})", x, y),
820                 }
821             };
822
823             let print_limit = |end: &Option<&Expr>, offset: Offset, var_name: &str| if let Some(end) = *end {
824                 if_let_chain! {[
825                     let ExprMethodCall(ref method, _, ref len_args) = end.node,
826                     method.name == "len",
827                     len_args.len() == 1,
828                     let Some(arg) = len_args.get(0),
829                     snippet(cx, arg.span, "??") == var_name,
830                 ], {
831                     return if offset.negate {
832                         format!("({} - {})", snippet(cx, end.span, "<src>.len()"), offset.value)
833                     } else {
834                         "".to_owned()
835                     };
836                 }}
837
838                 let end_str = match limits {
839                     ast::RangeLimits::Closed => {
840                         let end = sugg::Sugg::hir(cx, end, "<count>");
841                         format!("{}", end + sugg::ONE)
842                     },
843                     ast::RangeLimits::HalfOpen => format!("{}", snippet(cx, end.span, "..")),
844                 };
845
846                 print_sum(&Offset::positive(end_str), &offset)
847             } else {
848                 "..".into()
849             };
850
851             // The only statements in the for loops can be indexed assignments from
852             // indexed retrievals.
853             let manual_copies = get_indexed_assignments(cx, body, canonical_id);
854
855             let big_sugg = manual_copies
856                 .into_iter()
857                 .map(|(dst_var, src_var)| {
858                     let start_str = Offset::positive(snippet_opt(cx, start.span).unwrap_or_else(|| "".into()));
859                     let dst_offset = print_sum(&start_str, &dst_var.offset);
860                     let dst_limit = print_limit(end, dst_var.offset, &dst_var.var_name);
861                     let src_offset = print_sum(&start_str, &src_var.offset);
862                     let src_limit = print_limit(end, src_var.offset, &src_var.var_name);
863                     let dst = if dst_offset == "" && dst_limit == "" {
864                         dst_var.var_name
865                     } else {
866                         format!("{}[{}..{}]", dst_var.var_name, dst_offset, dst_limit)
867                     };
868
869                     format!("{}.clone_from_slice(&{}[{}..{}])", dst, src_var.var_name, src_offset, src_limit)
870                 })
871                 .join("\n    ");
872
873             if !big_sugg.is_empty() {
874                 span_lint_and_sugg(
875                     cx,
876                     MANUAL_MEMCPY,
877                     expr.span,
878                     "it looks like you're manually copying between slices",
879                     "try replacing the loop by",
880                     big_sugg,
881                 );
882             }
883         }
884     }
885 }
886
887 /// Check for looping over a range and then indexing a sequence with it.
888 /// The iteratee must be a range literal.
889 fn check_for_loop_range<'a, 'tcx>(
890     cx: &LateContext<'a, 'tcx>,
891     pat: &'tcx Pat,
892     arg: &'tcx Expr,
893     body: &'tcx Expr,
894     expr: &'tcx Expr,
895 ) {
896     if let Some(higher::Range {
897                     start: Some(start),
898                     ref end,
899                     limits,
900                 }) = higher::range(arg)
901     {
902         // the var must be a single name
903         if let PatKind::Binding(_, canonical_id, ref ident, _) = pat.node {
904             let mut visitor = VarVisitor {
905                 cx: cx,
906                 var: canonical_id,
907                 indexed: HashMap::new(),
908                 referenced: HashSet::new(),
909                 nonindex: false,
910             };
911             walk_expr(&mut visitor, body);
912
913             // linting condition: we only indexed one variable
914             if visitor.indexed.len() == 1 {
915                 let (indexed, indexed_extent) = visitor.indexed.into_iter().next().expect(
916                     "already checked that we have exactly 1 element",
917                 );
918
919                 // ensure that the indexed variable was declared before the loop, see #601
920                 if let Some(indexed_extent) = indexed_extent {
921                     let parent_id = cx.tcx.hir.get_parent(expr.id);
922                     let parent_def_id = cx.tcx.hir.local_def_id(parent_id);
923                     let region_scope_tree = cx.tcx.region_scope_tree(parent_def_id);
924                     let pat_extent = region_scope_tree.var_scope(pat.hir_id.local_id);
925                     if region_scope_tree.is_subscope_of(indexed_extent, pat_extent) {
926                         return;
927                     }
928                 }
929
930                 // don't lint if the container that is indexed into is also used without
931                 // indexing
932                 if visitor.referenced.contains(&indexed) {
933                     return;
934                 }
935
936                 let starts_at_zero = is_integer_literal(start, 0);
937
938                 let skip = if starts_at_zero {
939                     "".to_owned()
940                 } else {
941                     format!(".skip({})", snippet(cx, start.span, ".."))
942                 };
943
944                 let take = if let Some(end) = *end {
945                     if is_len_call(end, &indexed) {
946                         "".to_owned()
947                     } else {
948                         match limits {
949                             ast::RangeLimits::Closed => {
950                                 let end = sugg::Sugg::hir(cx, end, "<count>");
951                                 format!(".take({})", end + sugg::ONE)
952                             },
953                             ast::RangeLimits::HalfOpen => format!(".take({})", snippet(cx, end.span, "..")),
954                         }
955                     }
956                 } else {
957                     "".to_owned()
958                 };
959
960                 if visitor.nonindex {
961                     span_lint_and_then(
962                         cx,
963                         NEEDLESS_RANGE_LOOP,
964                         expr.span,
965                         &format!("the loop variable `{}` is used to index `{}`", ident.node, indexed),
966                         |db| {
967                             multispan_sugg(
968                                 db,
969                                 "consider using an iterator".to_string(),
970                                 vec![
971                                     (pat.span, format!("({}, <item>)", ident.node)),
972                                     (arg.span, format!("{}.iter().enumerate(){}{}", indexed, take, skip)),
973                                 ],
974                             );
975                         },
976                     );
977                 } else {
978                     let repl = if starts_at_zero && take.is_empty() {
979                         format!("&{}", indexed)
980                     } else {
981                         format!("{}.iter(){}{}", indexed, take, skip)
982                     };
983
984                     span_lint_and_then(
985                         cx,
986                         NEEDLESS_RANGE_LOOP,
987                         expr.span,
988                         &format!("the loop variable `{}` is only used to index `{}`.", ident.node, indexed),
989                         |db| {
990                             multispan_sugg(
991                                 db,
992                                 "consider using an iterator".to_string(),
993                                 vec![(pat.span, "<item>".to_string()), (arg.span, repl)],
994                             );
995                         },
996                     );
997                 }
998             }
999         }
1000     }
1001 }
1002
1003 fn is_len_call(expr: &Expr, var: &Name) -> bool {
1004     if_let_chain! {[
1005         let ExprMethodCall(ref method, _, ref len_args) = expr.node,
1006         len_args.len() == 1,
1007         method.name == "len",
1008         let ExprPath(QPath::Resolved(_, ref path)) = len_args[0].node,
1009         path.segments.len() == 1,
1010         path.segments[0].name == *var
1011     ], {
1012         return true;
1013     }}
1014
1015     false
1016 }
1017
1018 fn check_for_loop_reverse_range<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, arg: &'tcx Expr, expr: &'tcx Expr) {
1019     // if this for loop is iterating over a two-sided range...
1020     if let Some(higher::Range {
1021                     start: Some(start),
1022                     end: Some(end),
1023                     limits,
1024                 }) = higher::range(arg)
1025     {
1026         // ...and both sides are compile-time constant integers...
1027         let parent_item = cx.tcx.hir.get_parent(arg.id);
1028         let parent_def_id = cx.tcx.hir.local_def_id(parent_item);
1029         let substs = Substs::identity_for_item(cx.tcx, parent_def_id);
1030         let constcx = ConstContext::new(cx.tcx, cx.param_env.and(substs), cx.tables);
1031         if let Ok(start_idx) = constcx.eval(start) {
1032             if let Ok(end_idx) = constcx.eval(end) {
1033                 // ...and the start index is greater than the end index,
1034                 // this loop will never run. This is often confusing for developers
1035                 // who think that this will iterate from the larger value to the
1036                 // smaller value.
1037                 let (sup, eq) = match (start_idx, end_idx) {
1038                     (&ty::Const { val: ConstVal::Integral(start_idx), .. },
1039                      &ty::Const { val: ConstVal::Integral(end_idx), .. }) => {
1040                         (start_idx > end_idx, start_idx == end_idx)
1041                     },
1042                     _ => (false, false),
1043                 };
1044
1045                 if sup {
1046                     let start_snippet = snippet(cx, start.span, "_");
1047                     let end_snippet = snippet(cx, end.span, "_");
1048                     let dots = if limits == ast::RangeLimits::Closed {
1049                         "..."
1050                     } else {
1051                         ".."
1052                     };
1053
1054                     span_lint_and_then(
1055                         cx,
1056                         REVERSE_RANGE_LOOP,
1057                         expr.span,
1058                         "this range is empty so this for loop will never run",
1059                         |db| {
1060                             db.span_suggestion(
1061                                 arg.span,
1062                                 "consider using the following if you are attempting to iterate over this \
1063                                  range in reverse",
1064                                 format!(
1065                                     "({end}{dots}{start}).rev()",
1066                                     end = end_snippet,
1067                                     dots = dots,
1068                                     start = start_snippet
1069                                 ),
1070                             );
1071                         },
1072                     );
1073                 } else if eq && limits != ast::RangeLimits::Closed {
1074                     // if they are equal, it's also problematic - this loop
1075                     // will never run.
1076                     span_lint(
1077                         cx,
1078                         REVERSE_RANGE_LOOP,
1079                         expr.span,
1080                         "this range is empty so this for loop will never run",
1081                     );
1082                 }
1083             }
1084         }
1085     }
1086 }
1087
1088 fn lint_iter_method(cx: &LateContext, args: &[Expr], arg: &Expr, method_name: &str) {
1089     let object = snippet(cx, args[0].span, "_");
1090     let muta = if method_name == "iter_mut" {
1091         "mut "
1092     } else {
1093         ""
1094     };
1095     span_lint_and_sugg(
1096         cx,
1097         EXPLICIT_ITER_LOOP,
1098         arg.span,
1099         "it is more idiomatic to loop over references to containers instead of using explicit \
1100          iteration methods",
1101         "to write this more concisely, try",
1102         format!("&{}{}", muta, object),
1103     )
1104 }
1105
1106 fn check_for_loop_arg(cx: &LateContext, pat: &Pat, arg: &Expr, expr: &Expr) {
1107     let mut next_loop_linted = false; // whether or not ITER_NEXT_LOOP lint was used
1108     if let ExprMethodCall(ref method, _, ref args) = arg.node {
1109         // just the receiver, no arguments
1110         if args.len() == 1 {
1111             let method_name = &*method.name.as_str();
1112             // check for looping over x.iter() or x.iter_mut(), could use &x or &mut x
1113             if method_name == "iter" || method_name == "iter_mut" {
1114                 if is_ref_iterable_type(cx, &args[0]) {
1115                     lint_iter_method(cx, args, arg, method_name);
1116                 }
1117             } else if method_name == "into_iter" && match_trait_method(cx, arg, &paths::INTO_ITERATOR) {
1118                 let def_id = cx.tables.type_dependent_defs()[arg.hir_id].def_id();
1119                 let substs = cx.tables.node_substs(arg.hir_id);
1120                 let method_type = cx.tcx.type_of(def_id).subst(cx.tcx, substs);
1121
1122                 let fn_arg_tys = method_type.fn_sig(cx.tcx).inputs();
1123                 assert_eq!(fn_arg_tys.skip_binder().len(), 1);
1124                 if fn_arg_tys.skip_binder()[0].is_region_ptr() {
1125                     lint_iter_method(cx, args, arg, method_name);
1126                 } else {
1127                     let object = snippet(cx, args[0].span, "_");
1128                     span_lint_and_sugg(
1129                         cx,
1130                         EXPLICIT_INTO_ITER_LOOP,
1131                         arg.span,
1132                         "it is more idiomatic to loop over containers instead of using explicit \
1133                          iteration methods`",
1134                         "to write this more concisely, try",
1135                         object.to_string(),
1136                     );
1137                 }
1138             } else if method_name == "next" && match_trait_method(cx, arg, &paths::ITERATOR) {
1139                 span_lint(
1140                     cx,
1141                     ITER_NEXT_LOOP,
1142                     expr.span,
1143                     "you are iterating over `Iterator::next()` which is an Option; this will compile but is \
1144                      probably not what you want",
1145                 );
1146                 next_loop_linted = true;
1147             }
1148         }
1149     }
1150     if !next_loop_linted {
1151         check_arg_type(cx, pat, arg);
1152     }
1153 }
1154
1155 /// Check for `for` loops over `Option`s and `Results`
1156 fn check_arg_type(cx: &LateContext, pat: &Pat, arg: &Expr) {
1157     let ty = cx.tables.expr_ty(arg);
1158     if match_type(cx, ty, &paths::OPTION) {
1159         span_help_and_lint(
1160             cx,
1161             FOR_LOOP_OVER_OPTION,
1162             arg.span,
1163             &format!(
1164                 "for loop over `{0}`, which is an `Option`. This is more readably written as an \
1165                  `if let` statement.",
1166                 snippet(cx, arg.span, "_")
1167             ),
1168             &format!(
1169                 "consider replacing `for {0} in {1}` with `if let Some({0}) = {1}`",
1170                 snippet(cx, pat.span, "_"),
1171                 snippet(cx, arg.span, "_")
1172             ),
1173         );
1174     } else if match_type(cx, ty, &paths::RESULT) {
1175         span_help_and_lint(
1176             cx,
1177             FOR_LOOP_OVER_RESULT,
1178             arg.span,
1179             &format!(
1180                 "for loop over `{0}`, which is a `Result`. This is more readably written as an \
1181                  `if let` statement.",
1182                 snippet(cx, arg.span, "_")
1183             ),
1184             &format!(
1185                 "consider replacing `for {0} in {1}` with `if let Ok({0}) = {1}`",
1186                 snippet(cx, pat.span, "_"),
1187                 snippet(cx, arg.span, "_")
1188             ),
1189         );
1190     }
1191 }
1192
1193 fn check_for_loop_explicit_counter<'a, 'tcx>(
1194     cx: &LateContext<'a, 'tcx>,
1195     arg: &'tcx Expr,
1196     body: &'tcx Expr,
1197     expr: &'tcx Expr,
1198 ) {
1199     // Look for variables that are incremented once per loop iteration.
1200     let mut visitor = IncrementVisitor {
1201         cx: cx,
1202         states: HashMap::new(),
1203         depth: 0,
1204         done: false,
1205     };
1206     walk_expr(&mut visitor, body);
1207
1208     // For each candidate, check the parent block to see if
1209     // it's initialized to zero at the start of the loop.
1210     let map = &cx.tcx.hir;
1211     let parent_scope = map.get_enclosing_scope(expr.id).and_then(|id| {
1212         map.get_enclosing_scope(id)
1213     });
1214     if let Some(parent_id) = parent_scope {
1215         if let NodeBlock(block) = map.get(parent_id) {
1216             for (id, _) in visitor.states.iter().filter(
1217                 |&(_, v)| *v == VarState::IncrOnce,
1218             )
1219             {
1220                 let mut visitor2 = InitializeVisitor {
1221                     cx: cx,
1222                     end_expr: expr,
1223                     var_id: *id,
1224                     state: VarState::IncrOnce,
1225                     name: None,
1226                     depth: 0,
1227                     past_loop: false,
1228                 };
1229                 walk_block(&mut visitor2, block);
1230
1231                 if visitor2.state == VarState::Warn {
1232                     if let Some(name) = visitor2.name {
1233                         span_lint(
1234                             cx,
1235                             EXPLICIT_COUNTER_LOOP,
1236                             expr.span,
1237                             &format!(
1238                                 "the variable `{0}` is used as a loop counter. Consider using `for ({0}, \
1239                                  item) in {1}.enumerate()` or similar iterators",
1240                                 name,
1241                                 snippet(cx, arg.span, "_")
1242                             ),
1243                         );
1244                     }
1245                 }
1246             }
1247         }
1248     }
1249 }
1250
1251 /// Check for the `FOR_KV_MAP` lint.
1252 fn check_for_loop_over_map_kv<'a, 'tcx>(
1253     cx: &LateContext<'a, 'tcx>,
1254     pat: &'tcx Pat,
1255     arg: &'tcx Expr,
1256     body: &'tcx Expr,
1257     expr: &'tcx Expr,
1258 ) {
1259     let pat_span = pat.span;
1260
1261     if let PatKind::Tuple(ref pat, _) = pat.node {
1262         if pat.len() == 2 {
1263             let arg_span = arg.span;
1264             let (new_pat_span, kind, ty, mutbl) = match cx.tables.expr_ty(arg).sty {
1265                 ty::TyRef(_, ref tam) => {
1266                     match (&pat[0].node, &pat[1].node) {
1267                         (key, _) if pat_is_wild(key, body) => (pat[1].span, "value", tam.ty, tam.mutbl),
1268                         (_, value) if pat_is_wild(value, body) => (pat[0].span, "key", tam.ty, MutImmutable),
1269                         _ => return,
1270                     }
1271                 },
1272                 _ => return,
1273             };
1274             let mutbl = match mutbl {
1275                 MutImmutable => "",
1276                 MutMutable => "_mut",
1277             };
1278             let arg = match arg.node {
1279                 ExprAddrOf(_, ref expr) => &**expr,
1280                 _ => arg,
1281             };
1282
1283             if match_type(cx, ty, &paths::HASHMAP) || match_type(cx, ty, &paths::BTREEMAP) {
1284                 span_lint_and_then(
1285                     cx,
1286                     FOR_KV_MAP,
1287                     expr.span,
1288                     &format!("you seem to want to iterate on a map's {}s", kind),
1289                     |db| {
1290                         let map = sugg::Sugg::hir(cx, arg, "map");
1291                         multispan_sugg(
1292                             db,
1293                             "use the corresponding method".into(),
1294                             vec![
1295                                 (pat_span, snippet(cx, new_pat_span, kind).into_owned()),
1296                                 (arg_span, format!("{}.{}s{}()", map.maybe_par(), kind, mutbl)),
1297                             ],
1298                         );
1299                     },
1300                 );
1301             }
1302         }
1303     }
1304 }
1305
1306 /// Return true if the pattern is a `PatWild` or an ident prefixed with `'_'`.
1307 fn pat_is_wild<'tcx>(pat: &'tcx PatKind, body: &'tcx Expr) -> bool {
1308     match *pat {
1309         PatKind::Wild => true,
1310         PatKind::Binding(_, _, ident, None) if ident.node.as_str().starts_with('_') => {
1311             let mut visitor = UsedVisitor {
1312                 var: ident.node,
1313                 used: false,
1314             };
1315             walk_expr(&mut visitor, body);
1316             !visitor.used
1317         },
1318         _ => false,
1319     }
1320 }
1321
1322 struct UsedVisitor {
1323     var: ast::Name, // var to look for
1324     used: bool, // has the var been used otherwise?
1325 }
1326
1327 impl<'tcx> Visitor<'tcx> for UsedVisitor {
1328     fn visit_expr(&mut self, expr: &'tcx Expr) {
1329         if match_var(expr, self.var) {
1330             self.used = true;
1331         } else {
1332             walk_expr(self, expr);
1333         }
1334     }
1335
1336     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1337         NestedVisitorMap::None
1338     }
1339 }
1340
1341 struct LocalUsedVisitor<'a, 'tcx: 'a> {
1342     cx: &'a LateContext<'a, 'tcx>,
1343     local: ast::NodeId,
1344     used: bool,
1345 }
1346
1347 impl<'a, 'tcx: 'a> Visitor<'tcx> for LocalUsedVisitor<'a, 'tcx> {
1348     fn visit_expr(&mut self, expr: &'tcx Expr) {
1349         if same_var(self.cx, expr, self.local) {
1350             self.used = true;
1351         } else {
1352             walk_expr(self, expr);
1353         }
1354     }
1355
1356     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1357         NestedVisitorMap::None
1358     }
1359 }
1360
1361 struct VarVisitor<'a, 'tcx: 'a> {
1362     /// context reference
1363     cx: &'a LateContext<'a, 'tcx>,
1364     /// var name to look for as index
1365     var: ast::NodeId,
1366     /// indexed variables, the extend is `None` for global
1367     indexed: HashMap<Name, Option<region::Scope>>,
1368     /// Any names that are used outside an index operation.
1369     /// Used to detect things like `&mut vec` used together with `vec[i]`
1370     referenced: HashSet<Name>,
1371     /// has the loop variable been used in expressions other than the index of
1372     /// an index op?
1373     nonindex: bool,
1374 }
1375
1376 impl<'a, 'tcx> Visitor<'tcx> for VarVisitor<'a, 'tcx> {
1377     fn visit_expr(&mut self, expr: &'tcx Expr) {
1378         if_let_chain! {[
1379             // an index op
1380             let ExprIndex(ref seqexpr, ref idx) = expr.node,
1381             // the indexed container is referenced by a name
1382             let ExprPath(ref seqpath) = seqexpr.node,
1383             let QPath::Resolved(None, ref seqvar) = *seqpath,
1384             seqvar.segments.len() == 1,
1385         ], {
1386             let index_used = same_var(self.cx, idx, self.var) || {
1387                 let mut used_visitor = LocalUsedVisitor {
1388                     cx: self.cx,
1389                     local: self.var,
1390                     used: false,
1391                 };
1392                 walk_expr(&mut used_visitor, idx);
1393                 used_visitor.used
1394             };
1395
1396             if index_used {
1397                 let def = self.cx.tables.qpath_def(seqpath, seqexpr.hir_id);
1398                 match def {
1399                     Def::Local(node_id) | Def::Upvar(node_id, ..) => {
1400                         let hir_id = self.cx.tcx.hir.node_to_hir_id(node_id);
1401
1402                         let parent_id = self.cx.tcx.hir.get_parent(expr.id);
1403                         let parent_def_id = self.cx.tcx.hir.local_def_id(parent_id);
1404                         let extent = self.cx.tcx.region_scope_tree(parent_def_id).var_scope(hir_id.local_id);
1405                         self.indexed.insert(seqvar.segments[0].name, Some(extent));
1406                         return;  // no need to walk further *on the variable*
1407                     }
1408                     Def::Static(..) | Def::Const(..) => {
1409                         self.indexed.insert(seqvar.segments[0].name, None);
1410                         return;  // no need to walk further *on the variable*
1411                     }
1412                     _ => (),
1413                 }
1414             }
1415         }}
1416
1417         if_let_chain! {[
1418             // directly using a variable
1419             let ExprPath(ref qpath) = expr.node,
1420             let QPath::Resolved(None, ref path) = *qpath,
1421             path.segments.len() == 1,
1422             let Def::Local(local_id) = self.cx.tables.qpath_def(qpath, expr.hir_id),
1423         ], {
1424             if local_id == self.var {
1425                 // we are not indexing anything, record that
1426                 self.nonindex = true;
1427             } else {
1428                 // not the correct variable, but still a variable
1429                 self.referenced.insert(path.segments[0].name);
1430             }
1431         }}
1432
1433         walk_expr(self, expr);
1434     }
1435     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1436         NestedVisitorMap::None
1437     }
1438 }
1439
1440 fn is_iterator_used_after_while_let<'a, 'tcx: 'a>(cx: &LateContext<'a, 'tcx>, iter_expr: &'tcx Expr) -> bool {
1441     let def_id = match var_def_id(cx, iter_expr) {
1442         Some(id) => id,
1443         None => return false,
1444     };
1445     let mut visitor = VarUsedAfterLoopVisitor {
1446         cx: cx,
1447         def_id: def_id,
1448         iter_expr_id: iter_expr.id,
1449         past_while_let: false,
1450         var_used_after_while_let: false,
1451     };
1452     if let Some(enclosing_block) = get_enclosing_block(cx, def_id) {
1453         walk_block(&mut visitor, enclosing_block);
1454     }
1455     visitor.var_used_after_while_let
1456 }
1457
1458 struct VarUsedAfterLoopVisitor<'a, 'tcx: 'a> {
1459     cx: &'a LateContext<'a, 'tcx>,
1460     def_id: NodeId,
1461     iter_expr_id: NodeId,
1462     past_while_let: bool,
1463     var_used_after_while_let: bool,
1464 }
1465
1466 impl<'a, 'tcx> Visitor<'tcx> for VarUsedAfterLoopVisitor<'a, 'tcx> {
1467     fn visit_expr(&mut self, expr: &'tcx Expr) {
1468         if self.past_while_let {
1469             if Some(self.def_id) == var_def_id(self.cx, expr) {
1470                 self.var_used_after_while_let = true;
1471             }
1472         } else if self.iter_expr_id == expr.id {
1473             self.past_while_let = true;
1474         }
1475         walk_expr(self, expr);
1476     }
1477     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1478         NestedVisitorMap::None
1479     }
1480 }
1481
1482
1483 /// Return true if the type of expr is one that provides `IntoIterator` impls
1484 /// for `&T` and `&mut T`, such as `Vec`.
1485 #[cfg_attr(rustfmt, rustfmt_skip)]
1486 fn is_ref_iterable_type(cx: &LateContext, e: &Expr) -> bool {
1487     // no walk_ptrs_ty: calling iter() on a reference can make sense because it
1488     // will allow further borrows afterwards
1489     let ty = cx.tables.expr_ty(e);
1490     is_iterable_array(ty) ||
1491     match_type(cx, ty, &paths::VEC) ||
1492     match_type(cx, ty, &paths::LINKED_LIST) ||
1493     match_type(cx, ty, &paths::HASHMAP) ||
1494     match_type(cx, ty, &paths::HASHSET) ||
1495     match_type(cx, ty, &paths::VEC_DEQUE) ||
1496     match_type(cx, ty, &paths::BINARY_HEAP) ||
1497     match_type(cx, ty, &paths::BTREEMAP) ||
1498     match_type(cx, ty, &paths::BTREESET)
1499 }
1500
1501 fn is_iterable_array(ty: Ty) -> bool {
1502     // IntoIterator is currently only implemented for array sizes <= 32 in rustc
1503     match ty.sty {
1504         ty::TyArray(_, n) => (0...32).contains(const_to_u64(n)),
1505         _ => false,
1506     }
1507 }
1508
1509 /// If a block begins with a statement (possibly a `let` binding) and has an
1510 /// expression, return it.
1511 fn extract_expr_from_first_stmt(block: &Block) -> Option<&Expr> {
1512     if block.stmts.is_empty() {
1513         return None;
1514     }
1515     if let StmtDecl(ref decl, _) = block.stmts[0].node {
1516         if let DeclLocal(ref local) = decl.node {
1517             if let Some(ref expr) = local.init {
1518                 Some(expr)
1519             } else {
1520                 None
1521             }
1522         } else {
1523             None
1524         }
1525     } else {
1526         None
1527     }
1528 }
1529
1530 /// If a block begins with an expression (with or without semicolon), return it.
1531 fn extract_first_expr(block: &Block) -> Option<&Expr> {
1532     match block.expr {
1533         Some(ref expr) if block.stmts.is_empty() => Some(expr),
1534         None if !block.stmts.is_empty() => {
1535             match block.stmts[0].node {
1536                 StmtExpr(ref expr, _) |
1537                 StmtSemi(ref expr, _) => Some(expr),
1538                 StmtDecl(..) => None,
1539             }
1540         },
1541         _ => None,
1542     }
1543 }
1544
1545 /// Return true if expr contains a single break expr without destination label
1546 /// and
1547 /// passed expression. The expression may be within a block.
1548 fn is_simple_break_expr(expr: &Expr) -> bool {
1549     match expr.node {
1550         ExprBreak(dest, ref passed_expr) if dest.ident.is_none() && passed_expr.is_none() => true,
1551         ExprBlock(ref b) => {
1552             match extract_first_expr(b) {
1553                 Some(subexpr) => is_simple_break_expr(subexpr),
1554                 None => false,
1555             }
1556         },
1557         _ => false,
1558     }
1559 }
1560
1561 // To trigger the EXPLICIT_COUNTER_LOOP lint, a variable must be
1562 // incremented exactly once in the loop body, and initialized to zero
1563 // at the start of the loop.
1564 #[derive(PartialEq)]
1565 enum VarState {
1566     Initial, // Not examined yet
1567     IncrOnce, // Incremented exactly once, may be a loop counter
1568     Declared, // Declared but not (yet) initialized to zero
1569     Warn,
1570     DontWarn,
1571 }
1572
1573 /// Scan a for loop for variables that are incremented exactly once.
1574 struct IncrementVisitor<'a, 'tcx: 'a> {
1575     cx: &'a LateContext<'a, 'tcx>, // context reference
1576     states: HashMap<NodeId, VarState>, // incremented variables
1577     depth: u32, // depth of conditional expressions
1578     done: bool,
1579 }
1580
1581 impl<'a, 'tcx> Visitor<'tcx> for IncrementVisitor<'a, 'tcx> {
1582     fn visit_expr(&mut self, expr: &'tcx Expr) {
1583         if self.done {
1584             return;
1585         }
1586
1587         // If node is a variable
1588         if let Some(def_id) = var_def_id(self.cx, expr) {
1589             if let Some(parent) = get_parent_expr(self.cx, expr) {
1590                 let state = self.states.entry(def_id).or_insert(VarState::Initial);
1591
1592                 match parent.node {
1593                     ExprAssignOp(op, ref lhs, ref rhs) => {
1594                         if lhs.id == expr.id {
1595                             if op.node == BiAdd && is_integer_literal(rhs, 1) {
1596                                 *state = match *state {
1597                                     VarState::Initial if self.depth == 0 => VarState::IncrOnce,
1598                                     _ => VarState::DontWarn,
1599                                 };
1600                             } else {
1601                                 // Assigned some other value
1602                                 *state = VarState::DontWarn;
1603                             }
1604                         }
1605                     },
1606                     ExprAssign(ref lhs, _) if lhs.id == expr.id => *state = VarState::DontWarn,
1607                     ExprAddrOf(mutability, _) if mutability == MutMutable => *state = VarState::DontWarn,
1608                     _ => (),
1609                 }
1610             }
1611         } else if is_loop(expr) {
1612             self.states.clear();
1613             self.done = true;
1614             return;
1615         } else if is_conditional(expr) {
1616             self.depth += 1;
1617             walk_expr(self, expr);
1618             self.depth -= 1;
1619             return;
1620         }
1621         walk_expr(self, expr);
1622     }
1623     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1624         NestedVisitorMap::None
1625     }
1626 }
1627
1628 /// Check whether a variable is initialized to zero at the start of a loop.
1629 struct InitializeVisitor<'a, 'tcx: 'a> {
1630     cx: &'a LateContext<'a, 'tcx>, // context reference
1631     end_expr: &'tcx Expr, // the for loop. Stop scanning here.
1632     var_id: NodeId,
1633     state: VarState,
1634     name: Option<Name>,
1635     depth: u32, // depth of conditional expressions
1636     past_loop: bool,
1637 }
1638
1639 impl<'a, 'tcx> Visitor<'tcx> for InitializeVisitor<'a, 'tcx> {
1640     fn visit_decl(&mut self, decl: &'tcx Decl) {
1641         // Look for declarations of the variable
1642         if let DeclLocal(ref local) = decl.node {
1643             if local.pat.id == self.var_id {
1644                 if let PatKind::Binding(_, _, ref ident, _) = local.pat.node {
1645                     self.name = Some(ident.node);
1646
1647                     self.state = if let Some(ref init) = local.init {
1648                         if is_integer_literal(init, 0) {
1649                             VarState::Warn
1650                         } else {
1651                             VarState::Declared
1652                         }
1653                     } else {
1654                         VarState::Declared
1655                     }
1656                 }
1657             }
1658         }
1659         walk_decl(self, decl);
1660     }
1661
1662     fn visit_expr(&mut self, expr: &'tcx Expr) {
1663         if self.state == VarState::DontWarn {
1664             return;
1665         }
1666         if expr == self.end_expr {
1667             self.past_loop = true;
1668             return;
1669         }
1670         // No need to visit expressions before the variable is
1671         // declared
1672         if self.state == VarState::IncrOnce {
1673             return;
1674         }
1675
1676         // If node is the desired variable, see how it's used
1677         if var_def_id(self.cx, expr) == Some(self.var_id) {
1678             if let Some(parent) = get_parent_expr(self.cx, expr) {
1679                 match parent.node {
1680                     ExprAssignOp(_, ref lhs, _) if lhs.id == expr.id => {
1681                         self.state = VarState::DontWarn;
1682                     },
1683                     ExprAssign(ref lhs, ref rhs) if lhs.id == expr.id => {
1684                         self.state = if is_integer_literal(rhs, 0) && self.depth == 0 {
1685                             VarState::Warn
1686                         } else {
1687                             VarState::DontWarn
1688                         }
1689                     },
1690                     ExprAddrOf(mutability, _) if mutability == MutMutable => self.state = VarState::DontWarn,
1691                     _ => (),
1692                 }
1693             }
1694
1695             if self.past_loop {
1696                 self.state = VarState::DontWarn;
1697                 return;
1698             }
1699         } else if !self.past_loop && is_loop(expr) {
1700             self.state = VarState::DontWarn;
1701             return;
1702         } else if is_conditional(expr) {
1703             self.depth += 1;
1704             walk_expr(self, expr);
1705             self.depth -= 1;
1706             return;
1707         }
1708         walk_expr(self, expr);
1709     }
1710     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1711         NestedVisitorMap::None
1712     }
1713 }
1714
1715 fn var_def_id(cx: &LateContext, expr: &Expr) -> Option<NodeId> {
1716     if let ExprPath(ref qpath) = expr.node {
1717         let path_res = cx.tables.qpath_def(qpath, expr.hir_id);
1718         if let Def::Local(node_id) = path_res {
1719             return Some(node_id);
1720         }
1721     }
1722     None
1723 }
1724
1725 fn is_loop(expr: &Expr) -> bool {
1726     match expr.node {
1727         ExprLoop(..) | ExprWhile(..) => true,
1728         _ => false,
1729     }
1730 }
1731
1732 fn is_conditional(expr: &Expr) -> bool {
1733     match expr.node {
1734         ExprIf(..) | ExprMatch(..) => true,
1735         _ => false,
1736     }
1737 }
1738
1739 fn is_nested(cx: &LateContext, match_expr: &Expr, iter_expr: &Expr) -> bool {
1740     if_let_chain! {[
1741         let Some(loop_block) = get_enclosing_block(cx, match_expr.id),
1742         let Some(map::Node::NodeExpr(loop_expr)) = cx.tcx.hir.find(cx.tcx.hir.get_parent_node(loop_block.id)),
1743     ], {
1744         return is_loop_nested(cx, loop_expr, iter_expr)
1745     }}
1746     false
1747 }
1748
1749 fn is_loop_nested(cx: &LateContext, loop_expr: &Expr, iter_expr: &Expr) -> bool {
1750     let mut id = loop_expr.id;
1751     let iter_name = if let Some(name) = path_name(iter_expr) {
1752         name
1753     } else {
1754         return true;
1755     };
1756     loop {
1757         let parent = cx.tcx.hir.get_parent_node(id);
1758         if parent == id {
1759             return false;
1760         }
1761         match cx.tcx.hir.find(parent) {
1762             Some(NodeExpr(expr)) => {
1763                 match expr.node {
1764                     ExprLoop(..) | ExprWhile(..) => {
1765                         return true;
1766                     },
1767                     _ => (),
1768                 }
1769             },
1770             Some(NodeBlock(block)) => {
1771                 let mut block_visitor = LoopNestVisitor {
1772                     id: id,
1773                     iterator: iter_name,
1774                     nesting: Unknown,
1775                 };
1776                 walk_block(&mut block_visitor, block);
1777                 if block_visitor.nesting == RuledOut {
1778                     return false;
1779                 }
1780             },
1781             Some(NodeStmt(_)) => (),
1782             _ => {
1783                 return false;
1784             },
1785         }
1786         id = parent;
1787     }
1788 }
1789
1790 #[derive(PartialEq, Eq)]
1791 enum Nesting {
1792     Unknown, // no nesting detected yet
1793     RuledOut, // the iterator is initialized or assigned within scope
1794     LookFurther, // no nesting detected, no further walk required
1795 }
1796
1797 use self::Nesting::{LookFurther, RuledOut, Unknown};
1798
1799 struct LoopNestVisitor {
1800     id: NodeId,
1801     iterator: Name,
1802     nesting: Nesting,
1803 }
1804
1805 impl<'tcx> Visitor<'tcx> for LoopNestVisitor {
1806     fn visit_stmt(&mut self, stmt: &'tcx Stmt) {
1807         if stmt.node.id() == self.id {
1808             self.nesting = LookFurther;
1809         } else if self.nesting == Unknown {
1810             walk_stmt(self, stmt);
1811         }
1812     }
1813
1814     fn visit_expr(&mut self, expr: &'tcx Expr) {
1815         if self.nesting != Unknown {
1816             return;
1817         }
1818         if expr.id == self.id {
1819             self.nesting = LookFurther;
1820             return;
1821         }
1822         match expr.node {
1823             ExprAssign(ref path, _) |
1824             ExprAssignOp(_, ref path, _) => {
1825                 if match_var(path, self.iterator) {
1826                     self.nesting = RuledOut;
1827                 }
1828             },
1829             _ => walk_expr(self, expr),
1830         }
1831     }
1832
1833     fn visit_pat(&mut self, pat: &'tcx Pat) {
1834         if self.nesting != Unknown {
1835             return;
1836         }
1837         if let PatKind::Binding(_, _, span_name, _) = pat.node {
1838             if self.iterator == span_name.node {
1839                 self.nesting = RuledOut;
1840                 return;
1841             }
1842         }
1843         walk_pat(self, pat)
1844     }
1845
1846     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1847         NestedVisitorMap::None
1848     }
1849 }
1850
1851 fn path_name(e: &Expr) -> Option<Name> {
1852     if let ExprPath(QPath::Resolved(_, ref path)) = e.node {
1853         let segments = &path.segments;
1854         if segments.len() == 1 {
1855             return Some(segments[0].name);
1856         }
1857     };
1858     None
1859 }