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