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