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