]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/loops.rs
Merge commit '5034d47f721ff4c3a3ff2aca9ef2ef3e1d067f9f' into clippyup
[rust.git] / src / tools / clippy / clippy_lints / src / loops.rs
1 use crate::consts::constant;
2 use crate::utils::paths;
3 use crate::utils::sugg::Sugg;
4 use crate::utils::usage::{is_unused, mutated_variables};
5 use crate::utils::{
6     get_enclosing_block, get_parent_expr, get_trait_def_id, has_iter_method, higher, implements_trait,
7     is_integer_const, is_no_std_crate, is_refutable, is_type_diagnostic_item, last_path_segment, match_trait_method,
8     match_type, match_var, multispan_sugg, qpath_res, snippet, snippet_opt, snippet_with_applicability,
9     snippet_with_macro_callsite, span_lint, span_lint_and_help, span_lint_and_sugg, span_lint_and_then, sugg,
10     SpanlessEq,
11 };
12 use if_chain::if_chain;
13 use rustc_ast::ast;
14 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
15 use rustc_errors::Applicability;
16 use rustc_hir::def::{DefKind, Res};
17 use rustc_hir::intravisit::{walk_block, walk_expr, walk_pat, walk_stmt, NestedVisitorMap, Visitor};
18 use rustc_hir::{
19     def_id, BinOpKind, BindingAnnotation, Block, BorrowKind, Expr, ExprKind, GenericArg, HirId, InlineAsmOperand,
20     Local, LoopSource, MatchSource, Mutability, Node, Pat, PatKind, QPath, Stmt, StmtKind,
21 };
22 use rustc_infer::infer::TyCtxtInferExt;
23 use rustc_lint::{LateContext, LateLintPass, LintContext};
24 use rustc_middle::hir::map::Map;
25 use rustc_middle::lint::in_external_macro;
26 use rustc_middle::middle::region;
27 use rustc_middle::ty::{self, Ty, TyS};
28 use rustc_session::{declare_lint_pass, declare_tool_lint};
29 use rustc_span::source_map::Span;
30 use rustc_span::symbol::{sym, Ident, Symbol};
31 use rustc_typeck::expr_use_visitor::{ConsumeMode, Delegate, ExprUseVisitor, PlaceBase, PlaceWithHirId};
32 use std::iter::{once, Iterator};
33 use std::mem;
34
35 declare_clippy_lint! {
36     /// **What it does:** Checks for for-loops that manually copy items between
37     /// slices that could be optimized by having a memcpy.
38     ///
39     /// **Why is this bad?** It is not as fast as a memcpy.
40     ///
41     /// **Known problems:** None.
42     ///
43     /// **Example:**
44     /// ```rust
45     /// # let src = vec![1];
46     /// # let mut dst = vec![0; 65];
47     /// for i in 0..src.len() {
48     ///     dst[i + 64] = src[i];
49     /// }
50     /// ```
51     /// Could be written as:
52     /// ```rust
53     /// # let src = vec![1];
54     /// # let mut dst = vec![0; 65];
55     /// dst[64..(src.len() + 64)].clone_from_slice(&src[..]);
56     /// ```
57     pub MANUAL_MEMCPY,
58     perf,
59     "manually copying items between slices"
60 }
61
62 declare_clippy_lint! {
63     /// **What it does:** Checks for looping over the range of `0..len` of some
64     /// collection just to get the values by index.
65     ///
66     /// **Why is this bad?** Just iterating the collection itself makes the intent
67     /// more clear and is probably faster.
68     ///
69     /// **Known problems:** None.
70     ///
71     /// **Example:**
72     /// ```rust
73     /// let vec = vec!['a', 'b', 'c'];
74     /// for i in 0..vec.len() {
75     ///     println!("{}", vec[i]);
76     /// }
77     /// ```
78     /// Could be written as:
79     /// ```rust
80     /// let vec = vec!['a', 'b', 'c'];
81     /// for i in vec {
82     ///     println!("{}", i);
83     /// }
84     /// ```
85     pub NEEDLESS_RANGE_LOOP,
86     style,
87     "for-looping over a range of indices where an iterator over items would do"
88 }
89
90 declare_clippy_lint! {
91     /// **What it does:** Checks for loops on `x.iter()` where `&x` will do, and
92     /// suggests the latter.
93     ///
94     /// **Why is this bad?** Readability.
95     ///
96     /// **Known problems:** False negatives. We currently only warn on some known
97     /// types.
98     ///
99     /// **Example:**
100     /// ```rust
101     /// // with `y` a `Vec` or slice:
102     /// # let y = vec![1];
103     /// for x in y.iter() {
104     ///     // ..
105     /// }
106     /// ```
107     /// can be rewritten to
108     /// ```rust
109     /// # let y = vec![1];
110     /// for x in &y {
111     ///     // ..
112     /// }
113     /// ```
114     pub EXPLICIT_ITER_LOOP,
115     pedantic,
116     "for-looping over `_.iter()` or `_.iter_mut()` when `&_` or `&mut _` would do"
117 }
118
119 declare_clippy_lint! {
120     /// **What it does:** Checks for loops on `y.into_iter()` where `y` will do, and
121     /// suggests the latter.
122     ///
123     /// **Why is this bad?** Readability.
124     ///
125     /// **Known problems:** None
126     ///
127     /// **Example:**
128     /// ```rust
129     /// # let y = vec![1];
130     /// // with `y` a `Vec` or slice:
131     /// for x in y.into_iter() {
132     ///     // ..
133     /// }
134     /// ```
135     /// can be rewritten to
136     /// ```rust
137     /// # let y = vec![1];
138     /// for x in y {
139     ///     // ..
140     /// }
141     /// ```
142     pub EXPLICIT_INTO_ITER_LOOP,
143     pedantic,
144     "for-looping over `_.into_iter()` when `_` would do"
145 }
146
147 declare_clippy_lint! {
148     /// **What it does:** Checks for loops on `x.next()`.
149     ///
150     /// **Why is this bad?** `next()` returns either `Some(value)` if there was a
151     /// value, or `None` otherwise. The insidious thing is that `Option<_>`
152     /// implements `IntoIterator`, so that possibly one value will be iterated,
153     /// leading to some hard to find bugs. No one will want to write such code
154     /// [except to win an Underhanded Rust
155     /// Contest](https://www.reddit.com/r/rust/comments/3hb0wm/underhanded_rust_contest/cu5yuhr).
156     ///
157     /// **Known problems:** None.
158     ///
159     /// **Example:**
160     /// ```ignore
161     /// for x in y.next() {
162     ///     ..
163     /// }
164     /// ```
165     pub ITER_NEXT_LOOP,
166     correctness,
167     "for-looping over `_.next()` which is probably not intended"
168 }
169
170 declare_clippy_lint! {
171     /// **What it does:** Checks for `for` loops over `Option` or `Result` values.
172     ///
173     /// **Why is this bad?** Readability. This is more clearly expressed as an `if
174     /// let`.
175     ///
176     /// **Known problems:** None.
177     ///
178     /// **Example:**
179     /// ```rust
180     /// # let opt = Some(1);
181     ///
182     /// // Bad
183     /// for x in opt {
184     ///     // ..
185     /// }
186     ///
187     /// // Good
188     /// if let Some(x) = opt {
189     ///     // ..
190     /// }
191     /// ```
192     ///
193     /// // or
194     ///
195     /// ```rust
196     /// # let res: Result<i32, std::io::Error> = Ok(1);
197     ///
198     /// // Bad
199     /// for x in &res {
200     ///     // ..
201     /// }
202     ///
203     /// // Good
204     /// if let Ok(x) = res {
205     ///     // ..
206     /// }
207     /// ```
208     pub FOR_LOOPS_OVER_FALLIBLES,
209     correctness,
210     "for-looping over an `Option` or a `Result`, which is more clearly expressed as an `if let`"
211 }
212
213 declare_clippy_lint! {
214     /// **What it does:** Detects `loop + match` combinations that are easier
215     /// written as a `while let` loop.
216     ///
217     /// **Why is this bad?** The `while let` loop is usually shorter and more
218     /// readable.
219     ///
220     /// **Known problems:** Sometimes the wrong binding is displayed (#383).
221     ///
222     /// **Example:**
223     /// ```rust,no_run
224     /// # let y = Some(1);
225     /// loop {
226     ///     let x = match y {
227     ///         Some(x) => x,
228     ///         None => break,
229     ///     };
230     ///     // .. do something with x
231     /// }
232     /// // is easier written as
233     /// while let Some(x) = y {
234     ///     // .. do something with x
235     /// };
236     /// ```
237     pub WHILE_LET_LOOP,
238     complexity,
239     "`loop { if let { ... } else break }`, which can be written as a `while let` loop"
240 }
241
242 declare_clippy_lint! {
243     /// **What it does:** Checks for functions collecting an iterator when collect
244     /// is not needed.
245     ///
246     /// **Why is this bad?** `collect` causes the allocation of a new data structure,
247     /// when this allocation may not be needed.
248     ///
249     /// **Known problems:**
250     /// None
251     ///
252     /// **Example:**
253     /// ```rust
254     /// # let iterator = vec![1].into_iter();
255     /// let len = iterator.clone().collect::<Vec<_>>().len();
256     /// // should be
257     /// let len = iterator.count();
258     /// ```
259     pub NEEDLESS_COLLECT,
260     perf,
261     "collecting an iterator when collect is not needed"
262 }
263
264 declare_clippy_lint! {
265     /// **What it does:** Checks `for` loops over slices with an explicit counter
266     /// and suggests the use of `.enumerate()`.
267     ///
268     /// **Why is it bad?** Using `.enumerate()` makes the intent more clear,
269     /// declutters the code and may be faster in some instances.
270     ///
271     /// **Known problems:** None.
272     ///
273     /// **Example:**
274     /// ```rust
275     /// # let v = vec![1];
276     /// # fn bar(bar: usize, baz: usize) {}
277     /// let mut i = 0;
278     /// for item in &v {
279     ///     bar(i, *item);
280     ///     i += 1;
281     /// }
282     /// ```
283     /// Could be written as
284     /// ```rust
285     /// # let v = vec![1];
286     /// # fn bar(bar: usize, baz: usize) {}
287     /// for (i, item) in v.iter().enumerate() { bar(i, *item); }
288     /// ```
289     pub EXPLICIT_COUNTER_LOOP,
290     complexity,
291     "for-looping with an explicit counter when `_.enumerate()` would do"
292 }
293
294 declare_clippy_lint! {
295     /// **What it does:** Checks for empty `loop` expressions.
296     ///
297     /// **Why is this bad?** Those busy loops burn CPU cycles without doing
298     /// anything. Think of the environment and either block on something or at least
299     /// make the thread sleep for some microseconds.
300     ///
301     /// **Known problems:** None.
302     ///
303     /// **Example:**
304     /// ```no_run
305     /// loop {}
306     /// ```
307     pub EMPTY_LOOP,
308     style,
309     "empty `loop {}`, which should block or sleep"
310 }
311
312 declare_clippy_lint! {
313     /// **What it does:** Checks for `while let` expressions on iterators.
314     ///
315     /// **Why is this bad?** Readability. A simple `for` loop is shorter and conveys
316     /// the intent better.
317     ///
318     /// **Known problems:** None.
319     ///
320     /// **Example:**
321     /// ```ignore
322     /// while let Some(val) = iter() {
323     ///     ..
324     /// }
325     /// ```
326     pub WHILE_LET_ON_ITERATOR,
327     style,
328     "using a while-let loop instead of a for loop on an iterator"
329 }
330
331 declare_clippy_lint! {
332     /// **What it does:** Checks for iterating a map (`HashMap` or `BTreeMap`) and
333     /// ignoring either the keys or values.
334     ///
335     /// **Why is this bad?** Readability. There are `keys` and `values` methods that
336     /// can be used to express that don't need the values or keys.
337     ///
338     /// **Known problems:** None.
339     ///
340     /// **Example:**
341     /// ```ignore
342     /// for (k, _) in &map {
343     ///     ..
344     /// }
345     /// ```
346     ///
347     /// could be replaced by
348     ///
349     /// ```ignore
350     /// for k in map.keys() {
351     ///     ..
352     /// }
353     /// ```
354     pub FOR_KV_MAP,
355     style,
356     "looping on a map using `iter` when `keys` or `values` would do"
357 }
358
359 declare_clippy_lint! {
360     /// **What it does:** Checks for loops that will always `break`, `return` or
361     /// `continue` an outer loop.
362     ///
363     /// **Why is this bad?** This loop never loops, all it does is obfuscating the
364     /// code.
365     ///
366     /// **Known problems:** None
367     ///
368     /// **Example:**
369     /// ```rust
370     /// loop {
371     ///     ..;
372     ///     break;
373     /// }
374     /// ```
375     pub NEVER_LOOP,
376     correctness,
377     "any loop that will always `break` or `return`"
378 }
379
380 declare_clippy_lint! {
381     /// **What it does:** Checks for loops which have a range bound that is a mutable variable
382     ///
383     /// **Why is this bad?** One might think that modifying the mutable variable changes the loop bounds
384     ///
385     /// **Known problems:** None
386     ///
387     /// **Example:**
388     /// ```rust
389     /// let mut foo = 42;
390     /// for i in 0..foo {
391     ///     foo -= 1;
392     ///     println!("{}", i); // prints numbers from 0 to 42, not 0 to 21
393     /// }
394     /// ```
395     pub MUT_RANGE_BOUND,
396     complexity,
397     "for loop over a range where one of the bounds is a mutable variable"
398 }
399
400 declare_clippy_lint! {
401     /// **What it does:** Checks whether variables used within while loop condition
402     /// can be (and are) mutated in the body.
403     ///
404     /// **Why is this bad?** If the condition is unchanged, entering the body of the loop
405     /// will lead to an infinite loop.
406     ///
407     /// **Known problems:** If the `while`-loop is in a closure, the check for mutation of the
408     /// condition variables in the body can cause false negatives. For example when only `Upvar` `a` is
409     /// in the condition and only `Upvar` `b` gets mutated in the body, the lint will not trigger.
410     ///
411     /// **Example:**
412     /// ```rust
413     /// let i = 0;
414     /// while i > 10 {
415     ///     println!("let me loop forever!");
416     /// }
417     /// ```
418     pub WHILE_IMMUTABLE_CONDITION,
419     correctness,
420     "variables used within while expression are not mutated in the body"
421 }
422
423 declare_clippy_lint! {
424     /// **What it does:** Checks whether a for loop is being used to push a constant
425     /// value into a Vec.
426     ///
427     /// **Why is this bad?** This kind of operation can be expressed more succinctly with
428     /// `vec![item;SIZE]` or `vec.resize(NEW_SIZE, item)` and using these alternatives may also
429     /// have better performance.
430     /// **Known problems:** None
431     ///
432     /// **Example:**
433     /// ```rust
434     /// let item1 = 2;
435     /// let item2 = 3;
436     /// let mut vec: Vec<u8> = Vec::new();
437     /// for _ in 0..20 {
438     ///    vec.push(item1);
439     /// }
440     /// for _ in 0..30 {
441     ///     vec.push(item2);
442     /// }
443     /// ```
444     /// could be written as
445     /// ```rust
446     /// let item1 = 2;
447     /// let item2 = 3;
448     /// let mut vec: Vec<u8> = vec![item1; 20];
449     /// vec.resize(20 + 30, item2);
450     /// ```
451     pub SAME_ITEM_PUSH,
452     style,
453     "the same item is pushed inside of a for loop"
454 }
455
456 declare_lint_pass!(Loops => [
457     MANUAL_MEMCPY,
458     NEEDLESS_RANGE_LOOP,
459     EXPLICIT_ITER_LOOP,
460     EXPLICIT_INTO_ITER_LOOP,
461     ITER_NEXT_LOOP,
462     FOR_LOOPS_OVER_FALLIBLES,
463     WHILE_LET_LOOP,
464     NEEDLESS_COLLECT,
465     EXPLICIT_COUNTER_LOOP,
466     EMPTY_LOOP,
467     WHILE_LET_ON_ITERATOR,
468     FOR_KV_MAP,
469     NEVER_LOOP,
470     MUT_RANGE_BOUND,
471     WHILE_IMMUTABLE_CONDITION,
472     SAME_ITEM_PUSH,
473 ]);
474
475 impl<'tcx> LateLintPass<'tcx> for Loops {
476     #[allow(clippy::too_many_lines)]
477     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
478         if let Some((pat, arg, body)) = higher::for_loop(expr) {
479             // we don't want to check expanded macros
480             // this check is not at the top of the function
481             // since higher::for_loop expressions are marked as expansions
482             if body.span.from_expansion() {
483                 return;
484             }
485             check_for_loop(cx, pat, arg, body, expr);
486         }
487
488         // we don't want to check expanded macros
489         if expr.span.from_expansion() {
490             return;
491         }
492
493         // check for never_loop
494         if let ExprKind::Loop(ref block, _, _) = expr.kind {
495             match never_loop_block(block, expr.hir_id) {
496                 NeverLoopResult::AlwaysBreak => span_lint(cx, NEVER_LOOP, expr.span, "this loop never actually loops"),
497                 NeverLoopResult::MayContinueMainLoop | NeverLoopResult::Otherwise => (),
498             }
499         }
500
501         // check for `loop { if let {} else break }` that could be `while let`
502         // (also matches an explicit "match" instead of "if let")
503         // (even if the "match" or "if let" is used for declaration)
504         if let ExprKind::Loop(ref block, _, LoopSource::Loop) = expr.kind {
505             // also check for empty `loop {}` statements
506             if block.stmts.is_empty() && block.expr.is_none() && !is_no_std_crate(cx.tcx.hir().krate()) {
507                 span_lint(
508                     cx,
509                     EMPTY_LOOP,
510                     expr.span,
511                     "empty `loop {}` detected. You may want to either use `panic!()` or add \
512                      `std::thread::sleep(..);` to the loop body.",
513                 );
514             }
515
516             // extract the expression from the first statement (if any) in a block
517             let inner_stmt_expr = extract_expr_from_first_stmt(block);
518             // or extract the first expression (if any) from the block
519             if let Some(inner) = inner_stmt_expr.or_else(|| extract_first_expr(block)) {
520                 if let ExprKind::Match(ref matchexpr, ref arms, ref source) = inner.kind {
521                     // ensure "if let" compatible match structure
522                     match *source {
523                         MatchSource::Normal | MatchSource::IfLetDesugar { .. } => {
524                             if arms.len() == 2
525                                 && arms[0].guard.is_none()
526                                 && arms[1].guard.is_none()
527                                 && is_simple_break_expr(&arms[1].body)
528                             {
529                                 if in_external_macro(cx.sess(), expr.span) {
530                                     return;
531                                 }
532
533                                 // NOTE: we used to build a body here instead of using
534                                 // ellipsis, this was removed because:
535                                 // 1) it was ugly with big bodies;
536                                 // 2) it was not indented properly;
537                                 // 3) it wasn’t very smart (see #675).
538                                 let mut applicability = Applicability::HasPlaceholders;
539                                 span_lint_and_sugg(
540                                     cx,
541                                     WHILE_LET_LOOP,
542                                     expr.span,
543                                     "this loop could be written as a `while let` loop",
544                                     "try",
545                                     format!(
546                                         "while let {} = {} {{ .. }}",
547                                         snippet_with_applicability(cx, arms[0].pat.span, "..", &mut applicability),
548                                         snippet_with_applicability(cx, matchexpr.span, "..", &mut applicability),
549                                     ),
550                                     applicability,
551                                 );
552                             }
553                         },
554                         _ => (),
555                     }
556                 }
557             }
558         }
559         if let ExprKind::Match(ref match_expr, ref arms, MatchSource::WhileLetDesugar) = expr.kind {
560             let pat = &arms[0].pat.kind;
561             if let (
562                 &PatKind::TupleStruct(ref qpath, ref pat_args, _),
563                 &ExprKind::MethodCall(ref method_path, _, ref method_args, _),
564             ) = (pat, &match_expr.kind)
565             {
566                 let iter_expr = &method_args[0];
567
568                 // Don't lint when the iterator is recreated on every iteration
569                 if_chain! {
570                     if let ExprKind::MethodCall(..) | ExprKind::Call(..) = iter_expr.kind;
571                     if let Some(iter_def_id) = get_trait_def_id(cx, &paths::ITERATOR);
572                     if implements_trait(cx, cx.typeck_results().expr_ty(iter_expr), iter_def_id, &[]);
573                     then {
574                         return;
575                     }
576                 }
577
578                 let lhs_constructor = last_path_segment(qpath);
579                 if method_path.ident.name == sym!(next)
580                     && match_trait_method(cx, match_expr, &paths::ITERATOR)
581                     && lhs_constructor.ident.name == sym!(Some)
582                     && (pat_args.is_empty()
583                         || !is_refutable(cx, &pat_args[0])
584                             && !is_used_inside(cx, iter_expr, &arms[0].body)
585                             && !is_iterator_used_after_while_let(cx, iter_expr)
586                             && !is_nested(cx, expr, &method_args[0]))
587                 {
588                     let mut applicability = Applicability::MachineApplicable;
589                     let iterator = snippet_with_applicability(cx, method_args[0].span, "_", &mut applicability);
590                     let loop_var = if pat_args.is_empty() {
591                         "_".to_string()
592                     } else {
593                         snippet_with_applicability(cx, pat_args[0].span, "_", &mut applicability).into_owned()
594                     };
595                     span_lint_and_sugg(
596                         cx,
597                         WHILE_LET_ON_ITERATOR,
598                         expr.span.with_hi(match_expr.span.hi()),
599                         "this loop could be written as a `for` loop",
600                         "try",
601                         format!("for {} in {}", loop_var, iterator),
602                         applicability,
603                     );
604                 }
605             }
606         }
607
608         if let Some((cond, body)) = higher::while_loop(&expr) {
609             check_infinite_loop(cx, cond, body);
610         }
611
612         check_needless_collect(expr, cx);
613     }
614 }
615
616 enum NeverLoopResult {
617     // A break/return always get triggered but not necessarily for the main loop.
618     AlwaysBreak,
619     // A continue may occur for the main loop.
620     MayContinueMainLoop,
621     Otherwise,
622 }
623
624 #[must_use]
625 fn absorb_break(arg: &NeverLoopResult) -> NeverLoopResult {
626     match *arg {
627         NeverLoopResult::AlwaysBreak | NeverLoopResult::Otherwise => NeverLoopResult::Otherwise,
628         NeverLoopResult::MayContinueMainLoop => NeverLoopResult::MayContinueMainLoop,
629     }
630 }
631
632 // Combine two results for parts that are called in order.
633 #[must_use]
634 fn combine_seq(first: NeverLoopResult, second: NeverLoopResult) -> NeverLoopResult {
635     match first {
636         NeverLoopResult::AlwaysBreak | NeverLoopResult::MayContinueMainLoop => first,
637         NeverLoopResult::Otherwise => second,
638     }
639 }
640
641 // Combine two results where both parts are called but not necessarily in order.
642 #[must_use]
643 fn combine_both(left: NeverLoopResult, right: NeverLoopResult) -> NeverLoopResult {
644     match (left, right) {
645         (NeverLoopResult::MayContinueMainLoop, _) | (_, NeverLoopResult::MayContinueMainLoop) => {
646             NeverLoopResult::MayContinueMainLoop
647         },
648         (NeverLoopResult::AlwaysBreak, _) | (_, NeverLoopResult::AlwaysBreak) => NeverLoopResult::AlwaysBreak,
649         (NeverLoopResult::Otherwise, NeverLoopResult::Otherwise) => NeverLoopResult::Otherwise,
650     }
651 }
652
653 // Combine two results where only one of the part may have been executed.
654 #[must_use]
655 fn combine_branches(b1: NeverLoopResult, b2: NeverLoopResult) -> NeverLoopResult {
656     match (b1, b2) {
657         (NeverLoopResult::AlwaysBreak, NeverLoopResult::AlwaysBreak) => NeverLoopResult::AlwaysBreak,
658         (NeverLoopResult::MayContinueMainLoop, _) | (_, NeverLoopResult::MayContinueMainLoop) => {
659             NeverLoopResult::MayContinueMainLoop
660         },
661         (NeverLoopResult::Otherwise, _) | (_, NeverLoopResult::Otherwise) => NeverLoopResult::Otherwise,
662     }
663 }
664
665 fn never_loop_block(block: &Block<'_>, main_loop_id: HirId) -> NeverLoopResult {
666     let stmts = block.stmts.iter().map(stmt_to_expr);
667     let expr = once(block.expr.as_deref());
668     let mut iter = stmts.chain(expr).filter_map(|e| e);
669     never_loop_expr_seq(&mut iter, main_loop_id)
670 }
671
672 fn stmt_to_expr<'tcx>(stmt: &Stmt<'tcx>) -> Option<&'tcx Expr<'tcx>> {
673     match stmt.kind {
674         StmtKind::Semi(ref e, ..) | StmtKind::Expr(ref e, ..) => Some(e),
675         StmtKind::Local(ref local) => local.init.as_deref(),
676         _ => None,
677     }
678 }
679
680 fn never_loop_expr(expr: &Expr<'_>, main_loop_id: HirId) -> NeverLoopResult {
681     match expr.kind {
682         ExprKind::Box(ref e)
683         | ExprKind::Unary(_, ref e)
684         | ExprKind::Cast(ref e, _)
685         | ExprKind::Type(ref e, _)
686         | ExprKind::Field(ref e, _)
687         | ExprKind::AddrOf(_, _, ref e)
688         | ExprKind::Struct(_, _, Some(ref e))
689         | ExprKind::Repeat(ref e, _)
690         | ExprKind::DropTemps(ref e) => never_loop_expr(e, main_loop_id),
691         ExprKind::Array(ref es) | ExprKind::MethodCall(_, _, ref es, _) | ExprKind::Tup(ref es) => {
692             never_loop_expr_all(&mut es.iter(), main_loop_id)
693         },
694         ExprKind::Call(ref e, ref es) => never_loop_expr_all(&mut once(&**e).chain(es.iter()), main_loop_id),
695         ExprKind::Binary(_, ref e1, ref e2)
696         | ExprKind::Assign(ref e1, ref e2, _)
697         | ExprKind::AssignOp(_, ref e1, ref e2)
698         | ExprKind::Index(ref e1, ref e2) => never_loop_expr_all(&mut [&**e1, &**e2].iter().cloned(), main_loop_id),
699         ExprKind::Loop(ref b, _, _) => {
700             // Break can come from the inner loop so remove them.
701             absorb_break(&never_loop_block(b, main_loop_id))
702         },
703         ExprKind::Match(ref e, ref arms, _) => {
704             let e = never_loop_expr(e, main_loop_id);
705             if arms.is_empty() {
706                 e
707             } else {
708                 let arms = never_loop_expr_branch(&mut arms.iter().map(|a| &*a.body), main_loop_id);
709                 combine_seq(e, arms)
710             }
711         },
712         ExprKind::Block(ref b, _) => never_loop_block(b, main_loop_id),
713         ExprKind::Continue(d) => {
714             let id = d
715                 .target_id
716                 .expect("target ID can only be missing in the presence of compilation errors");
717             if id == main_loop_id {
718                 NeverLoopResult::MayContinueMainLoop
719             } else {
720                 NeverLoopResult::AlwaysBreak
721             }
722         },
723         ExprKind::Break(_, ref e) | ExprKind::Ret(ref e) => e.as_ref().map_or(NeverLoopResult::AlwaysBreak, |e| {
724             combine_seq(never_loop_expr(e, main_loop_id), NeverLoopResult::AlwaysBreak)
725         }),
726         ExprKind::InlineAsm(ref asm) => asm
727             .operands
728             .iter()
729             .map(|o| match o {
730                 InlineAsmOperand::In { expr, .. }
731                 | InlineAsmOperand::InOut { expr, .. }
732                 | InlineAsmOperand::Const { expr }
733                 | InlineAsmOperand::Sym { expr } => never_loop_expr(expr, main_loop_id),
734                 InlineAsmOperand::Out { expr, .. } => never_loop_expr_all(&mut expr.iter(), main_loop_id),
735                 InlineAsmOperand::SplitInOut { in_expr, out_expr, .. } => {
736                     never_loop_expr_all(&mut once(in_expr).chain(out_expr.iter()), main_loop_id)
737                 },
738             })
739             .fold(NeverLoopResult::Otherwise, combine_both),
740         ExprKind::Struct(_, _, None)
741         | ExprKind::Yield(_, _)
742         | ExprKind::Closure(_, _, _, _, _)
743         | ExprKind::LlvmInlineAsm(_)
744         | ExprKind::Path(_)
745         | ExprKind::Lit(_)
746         | ExprKind::Err => NeverLoopResult::Otherwise,
747     }
748 }
749
750 fn never_loop_expr_seq<'a, T: Iterator<Item = &'a Expr<'a>>>(es: &mut T, main_loop_id: HirId) -> NeverLoopResult {
751     es.map(|e| never_loop_expr(e, main_loop_id))
752         .fold(NeverLoopResult::Otherwise, combine_seq)
753 }
754
755 fn never_loop_expr_all<'a, T: Iterator<Item = &'a Expr<'a>>>(es: &mut T, main_loop_id: HirId) -> NeverLoopResult {
756     es.map(|e| never_loop_expr(e, main_loop_id))
757         .fold(NeverLoopResult::Otherwise, combine_both)
758 }
759
760 fn never_loop_expr_branch<'a, T: Iterator<Item = &'a Expr<'a>>>(e: &mut T, main_loop_id: HirId) -> NeverLoopResult {
761     e.map(|e| never_loop_expr(e, main_loop_id))
762         .fold(NeverLoopResult::AlwaysBreak, combine_branches)
763 }
764
765 fn check_for_loop<'tcx>(
766     cx: &LateContext<'tcx>,
767     pat: &'tcx Pat<'_>,
768     arg: &'tcx Expr<'_>,
769     body: &'tcx Expr<'_>,
770     expr: &'tcx Expr<'_>,
771 ) {
772     check_for_loop_range(cx, pat, arg, body, expr);
773     check_for_loop_arg(cx, pat, arg, expr);
774     check_for_loop_explicit_counter(cx, pat, arg, body, expr);
775     check_for_loop_over_map_kv(cx, pat, arg, body, expr);
776     check_for_mut_range_bound(cx, arg, body);
777     detect_manual_memcpy(cx, pat, arg, body, expr);
778     detect_same_item_push(cx, pat, arg, body, expr);
779 }
780
781 fn same_var<'tcx>(cx: &LateContext<'tcx>, expr: &Expr<'_>, var: HirId) -> bool {
782     if_chain! {
783         if let ExprKind::Path(qpath) = &expr.kind;
784         if let QPath::Resolved(None, path) = qpath;
785         if path.segments.len() == 1;
786         if let Res::Local(local_id) = qpath_res(cx, qpath, expr.hir_id);
787         then {
788             // our variable!
789             local_id == var
790         } else {
791             false
792         }
793     }
794 }
795
796 #[derive(Clone, Copy)]
797 enum OffsetSign {
798     Positive,
799     Negative,
800 }
801
802 struct Offset {
803     value: String,
804     sign: OffsetSign,
805 }
806
807 impl Offset {
808     fn negative(value: String) -> Self {
809         Self {
810             value,
811             sign: OffsetSign::Negative,
812         }
813     }
814
815     fn positive(value: String) -> Self {
816         Self {
817             value,
818             sign: OffsetSign::Positive,
819         }
820     }
821 }
822
823 struct FixedOffsetVar<'hir> {
824     var: &'hir Expr<'hir>,
825     offset: Offset,
826 }
827
828 fn is_slice_like<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'_>) -> bool {
829     let is_slice = match ty.kind() {
830         ty::Ref(_, subty, _) => is_slice_like(cx, subty),
831         ty::Slice(..) | ty::Array(..) => true,
832         _ => false,
833     };
834
835     is_slice || is_type_diagnostic_item(cx, ty, sym!(vec_type)) || is_type_diagnostic_item(cx, ty, sym!(vecdeque_type))
836 }
837
838 fn fetch_cloned_expr<'tcx>(expr: &'tcx Expr<'tcx>) -> &'tcx Expr<'tcx> {
839     if_chain! {
840         if let ExprKind::MethodCall(method, _, args, _) = expr.kind;
841         if method.ident.name == sym!(clone);
842         if args.len() == 1;
843         if let Some(arg) = args.get(0);
844         then { arg } else { expr }
845     }
846 }
847
848 fn get_offset<'tcx>(cx: &LateContext<'tcx>, idx: &Expr<'_>, var: HirId) -> Option<Offset> {
849     fn extract_offset<'tcx>(cx: &LateContext<'tcx>, e: &Expr<'_>, var: HirId) -> Option<String> {
850         match &e.kind {
851             ExprKind::Lit(l) => match l.node {
852                 ast::LitKind::Int(x, _ty) => Some(x.to_string()),
853                 _ => None,
854             },
855             ExprKind::Path(..) if !same_var(cx, e, var) => Some(snippet_opt(cx, e.span).unwrap_or_else(|| "??".into())),
856             _ => None,
857         }
858     }
859
860     match idx.kind {
861         ExprKind::Binary(op, lhs, rhs) => match op.node {
862             BinOpKind::Add => {
863                 let offset_opt = if same_var(cx, lhs, var) {
864                     extract_offset(cx, rhs, var)
865                 } else if same_var(cx, rhs, var) {
866                     extract_offset(cx, lhs, var)
867                 } else {
868                     None
869                 };
870
871                 offset_opt.map(Offset::positive)
872             },
873             BinOpKind::Sub if same_var(cx, lhs, var) => extract_offset(cx, rhs, var).map(Offset::negative),
874             _ => None,
875         },
876         ExprKind::Path(..) if same_var(cx, idx, var) => Some(Offset::positive("0".into())),
877         _ => None,
878     }
879 }
880
881 fn get_assignments<'tcx>(body: &'tcx Expr<'tcx>) -> impl Iterator<Item = Option<(&'tcx Expr<'tcx>, &'tcx Expr<'tcx>)>> {
882     fn get_assignment<'tcx>(e: &'tcx Expr<'tcx>) -> Option<(&'tcx Expr<'tcx>, &'tcx Expr<'tcx>)> {
883         if let ExprKind::Assign(lhs, rhs, _) = e.kind {
884             Some((lhs, rhs))
885         } else {
886             None
887         }
888     }
889
890     // This is one of few ways to return different iterators
891     // derived from: https://stackoverflow.com/questions/29760668/conditionally-iterate-over-one-of-several-possible-iterators/52064434#52064434
892     let mut iter_a = None;
893     let mut iter_b = None;
894
895     if let ExprKind::Block(b, _) = body.kind {
896         let Block { stmts, expr, .. } = *b;
897
898         iter_a = stmts
899             .iter()
900             .filter_map(|stmt| match stmt.kind {
901                 StmtKind::Local(..) | StmtKind::Item(..) => None,
902                 StmtKind::Expr(e) | StmtKind::Semi(e) => Some(e),
903             })
904             .chain(expr.into_iter())
905             .map(get_assignment)
906             .into()
907     } else {
908         iter_b = Some(get_assignment(body))
909     }
910
911     iter_a.into_iter().flatten().chain(iter_b.into_iter())
912 }
913
914 fn build_manual_memcpy_suggestion<'tcx>(
915     cx: &LateContext<'tcx>,
916     start: &Expr<'_>,
917     end: &Expr<'_>,
918     limits: ast::RangeLimits,
919     dst_var: FixedOffsetVar<'_>,
920     src_var: FixedOffsetVar<'_>,
921 ) -> String {
922     fn print_sum(arg1: &str, arg2: &Offset) -> String {
923         match (arg1, &arg2.value[..], arg2.sign) {
924             ("0", "0", _) => "0".into(),
925             ("0", x, OffsetSign::Positive) | (x, "0", _) => x.into(),
926             ("0", x, OffsetSign::Negative) => format!("-{}", x),
927             (x, y, OffsetSign::Positive) => format!("({} + {})", x, y),
928             (x, y, OffsetSign::Negative) => {
929                 if x == y {
930                     "0".into()
931                 } else {
932                     format!("({} - {})", x, y)
933                 }
934             },
935         }
936     }
937
938     fn print_offset(start_str: &str, inline_offset: &Offset) -> String {
939         let offset = print_sum(start_str, inline_offset);
940         if offset.as_str() == "0" {
941             "".into()
942         } else {
943             offset
944         }
945     }
946
947     let print_limit = |end: &Expr<'_>, offset: Offset, var: &Expr<'_>| {
948         if_chain! {
949             if let ExprKind::MethodCall(method, _, len_args, _) = end.kind;
950             if method.ident.name == sym!(len);
951             if len_args.len() == 1;
952             if let Some(arg) = len_args.get(0);
953             if var_def_id(cx, arg) == var_def_id(cx, var);
954             then {
955                 match offset.sign {
956                     OffsetSign::Negative => format!("({} - {})", snippet(cx, end.span, "<src>.len()"), offset.value),
957                     OffsetSign::Positive => "".into(),
958                 }
959             } else {
960                 let end_str = match limits {
961                     ast::RangeLimits::Closed => {
962                         let end = sugg::Sugg::hir(cx, end, "<count>");
963                         format!("{}", end + sugg::ONE)
964                     },
965                     ast::RangeLimits::HalfOpen => format!("{}", snippet(cx, end.span, "..")),
966                 };
967
968                 print_sum(&end_str, &offset)
969             }
970         }
971     };
972
973     let start_str = snippet(cx, start.span, "").to_string();
974     let dst_offset = print_offset(&start_str, &dst_var.offset);
975     let dst_limit = print_limit(end, dst_var.offset, dst_var.var);
976     let src_offset = print_offset(&start_str, &src_var.offset);
977     let src_limit = print_limit(end, src_var.offset, src_var.var);
978
979     let dst_var_name = snippet_opt(cx, dst_var.var.span).unwrap_or_else(|| "???".into());
980     let src_var_name = snippet_opt(cx, src_var.var.span).unwrap_or_else(|| "???".into());
981
982     let dst = if dst_offset == "" && dst_limit == "" {
983         dst_var_name
984     } else {
985         format!("{}[{}..{}]", dst_var_name, dst_offset, dst_limit)
986     };
987
988     format!(
989         "{}.clone_from_slice(&{}[{}..{}])",
990         dst, src_var_name, src_offset, src_limit
991     )
992 }
993 /// Checks for for loops that sequentially copy items from one slice-like
994 /// object to another.
995 fn detect_manual_memcpy<'tcx>(
996     cx: &LateContext<'tcx>,
997     pat: &'tcx Pat<'_>,
998     arg: &'tcx Expr<'_>,
999     body: &'tcx Expr<'_>,
1000     expr: &'tcx Expr<'_>,
1001 ) {
1002     if let Some(higher::Range {
1003         start: Some(start),
1004         end: Some(end),
1005         limits,
1006     }) = higher::range(arg)
1007     {
1008         // the var must be a single name
1009         if let PatKind::Binding(_, canonical_id, _, _) = pat.kind {
1010             // The only statements in the for loops can be indexed assignments from
1011             // indexed retrievals.
1012             let big_sugg = get_assignments(body)
1013                 .map(|o| {
1014                     o.and_then(|(lhs, rhs)| {
1015                         let rhs = fetch_cloned_expr(rhs);
1016                         if_chain! {
1017                             if let ExprKind::Index(seqexpr_left, idx_left) = lhs.kind;
1018                             if let ExprKind::Index(seqexpr_right, idx_right) = rhs.kind;
1019                             if is_slice_like(cx, cx.typeck_results().expr_ty(seqexpr_left))
1020                                 && is_slice_like(cx, cx.typeck_results().expr_ty(seqexpr_right));
1021                             if let Some(offset_left) = get_offset(cx, &idx_left, canonical_id);
1022                             if let Some(offset_right) = get_offset(cx, &idx_right, canonical_id);
1023
1024                             // Source and destination must be different
1025                             if var_def_id(cx, seqexpr_left) != var_def_id(cx, seqexpr_right);
1026                             then {
1027                                 Some((FixedOffsetVar { var: seqexpr_left, offset: offset_left },
1028                                     FixedOffsetVar { var: seqexpr_right, offset: offset_right }))
1029                             } else {
1030                                 None
1031                             }
1032                         }
1033                     })
1034                 })
1035                 .map(|o| o.map(|(dst, src)| build_manual_memcpy_suggestion(cx, start, end, limits, dst, src)))
1036                 .collect::<Option<Vec<_>>>()
1037                 .filter(|v| !v.is_empty())
1038                 .map(|v| v.join("\n    "));
1039
1040             if let Some(big_sugg) = big_sugg {
1041                 span_lint_and_sugg(
1042                     cx,
1043                     MANUAL_MEMCPY,
1044                     expr.span,
1045                     "it looks like you're manually copying between slices",
1046                     "try replacing the loop by",
1047                     big_sugg,
1048                     Applicability::Unspecified,
1049                 );
1050             }
1051         }
1052     }
1053 }
1054
1055 // Scans the body of the for loop and determines whether lint should be given
1056 struct SameItemPushVisitor<'a, 'tcx> {
1057     should_lint: bool,
1058     // this field holds the last vec push operation visited, which should be the only push seen
1059     vec_push: Option<(&'tcx Expr<'tcx>, &'tcx Expr<'tcx>)>,
1060     cx: &'a LateContext<'tcx>,
1061 }
1062
1063 impl<'a, 'tcx> Visitor<'tcx> for SameItemPushVisitor<'a, 'tcx> {
1064     type Map = Map<'tcx>;
1065
1066     fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
1067         match &expr.kind {
1068             // Non-determinism may occur ... don't give a lint
1069             ExprKind::Loop(_, _, _) | ExprKind::Match(_, _, _) => self.should_lint = false,
1070             ExprKind::Block(block, _) => self.visit_block(block),
1071             _ => {},
1072         }
1073     }
1074
1075     fn visit_block(&mut self, b: &'tcx Block<'_>) {
1076         for stmt in b.stmts.iter() {
1077             self.visit_stmt(stmt);
1078         }
1079     }
1080
1081     fn visit_stmt(&mut self, s: &'tcx Stmt<'_>) {
1082         let vec_push_option = get_vec_push(self.cx, s);
1083         if vec_push_option.is_none() {
1084             // Current statement is not a push so visit inside
1085             match &s.kind {
1086                 StmtKind::Expr(expr) | StmtKind::Semi(expr) => self.visit_expr(&expr),
1087                 _ => {},
1088             }
1089         } else {
1090             // Current statement is a push ...check whether another
1091             // push had been previously done
1092             if self.vec_push.is_none() {
1093                 self.vec_push = vec_push_option;
1094             } else {
1095                 // There are multiple pushes ... don't lint
1096                 self.should_lint = false;
1097             }
1098         }
1099     }
1100
1101     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
1102         NestedVisitorMap::None
1103     }
1104 }
1105
1106 // Given some statement, determine if that statement is a push on a Vec. If it is, return
1107 // the Vec being pushed into and the item being pushed
1108 fn get_vec_push<'tcx>(cx: &LateContext<'tcx>, stmt: &'tcx Stmt<'_>) -> Option<(&'tcx Expr<'tcx>, &'tcx Expr<'tcx>)> {
1109     if_chain! {
1110             // Extract method being called
1111             if let StmtKind::Semi(semi_stmt) = &stmt.kind;
1112             if let ExprKind::MethodCall(path, _, args, _) = &semi_stmt.kind;
1113             // Figure out the parameters for the method call
1114             if let Some(self_expr) = args.get(0);
1115             if let Some(pushed_item) = args.get(1);
1116             // Check that the method being called is push() on a Vec
1117             if match_type(cx, cx.typeck_results().expr_ty(self_expr), &paths::VEC);
1118             if path.ident.name.as_str() == "push";
1119             then {
1120                 return Some((self_expr, pushed_item))
1121             }
1122     }
1123     None
1124 }
1125
1126 /// Detects for loop pushing the same item into a Vec
1127 fn detect_same_item_push<'tcx>(
1128     cx: &LateContext<'tcx>,
1129     pat: &'tcx Pat<'_>,
1130     _: &'tcx Expr<'_>,
1131     body: &'tcx Expr<'_>,
1132     _: &'tcx Expr<'_>,
1133 ) {
1134     fn emit_lint(cx: &LateContext<'_>, vec: &Expr<'_>, pushed_item: &Expr<'_>) {
1135         let vec_str = snippet_with_macro_callsite(cx, vec.span, "");
1136         let item_str = snippet_with_macro_callsite(cx, pushed_item.span, "");
1137
1138         span_lint_and_help(
1139             cx,
1140             SAME_ITEM_PUSH,
1141             vec.span,
1142             "it looks like the same item is being pushed into this Vec",
1143             None,
1144             &format!(
1145                 "try using vec![{};SIZE] or {}.resize(NEW_SIZE, {})",
1146                 item_str, vec_str, item_str
1147             ),
1148         )
1149     }
1150
1151     if !matches!(pat.kind, PatKind::Wild) {
1152         return;
1153     }
1154
1155     // Determine whether it is safe to lint the body
1156     let mut same_item_push_visitor = SameItemPushVisitor {
1157         should_lint: true,
1158         vec_push: None,
1159         cx,
1160     };
1161     walk_expr(&mut same_item_push_visitor, body);
1162     if same_item_push_visitor.should_lint {
1163         if let Some((vec, pushed_item)) = same_item_push_visitor.vec_push {
1164             let vec_ty = cx.typeck_results().expr_ty(vec);
1165             let ty = vec_ty.walk().nth(1).unwrap().expect_ty();
1166             if cx
1167                 .tcx
1168                 .lang_items()
1169                 .clone_trait()
1170                 .map_or(false, |id| implements_trait(cx, ty, id, &[]))
1171             {
1172                 // Make sure that the push does not involve possibly mutating values
1173                 match pushed_item.kind {
1174                     ExprKind::Path(ref qpath) => {
1175                         match qpath_res(cx, qpath, pushed_item.hir_id) {
1176                             // immutable bindings that are initialized with literal or constant
1177                             Res::Local(hir_id) => {
1178                                 if_chain! {
1179                                     let node = cx.tcx.hir().get(hir_id);
1180                                     if let Node::Binding(pat) = node;
1181                                     if let PatKind::Binding(bind_ann, ..) = pat.kind;
1182                                     if !matches!(bind_ann, BindingAnnotation::RefMut | BindingAnnotation::Mutable);
1183                                     let parent_node = cx.tcx.hir().get_parent_node(hir_id);
1184                                     if let Some(Node::Local(parent_let_expr)) = cx.tcx.hir().find(parent_node);
1185                                     if let Some(init) = parent_let_expr.init;
1186                                     then {
1187                                         match init.kind {
1188                                             // immutable bindings that are initialized with literal
1189                                             ExprKind::Lit(..) => emit_lint(cx, vec, pushed_item),
1190                                             // immutable bindings that are initialized with constant
1191                                             ExprKind::Path(ref path) => {
1192                                                 if let Res::Def(DefKind::Const, ..) = qpath_res(cx, path, init.hir_id) {
1193                                                     emit_lint(cx, vec, pushed_item);
1194                                                 }
1195                                             }
1196                                             _ => {},
1197                                         }
1198                                     }
1199                                 }
1200                             },
1201                             // constant
1202                             Res::Def(DefKind::Const, ..) => emit_lint(cx, vec, pushed_item),
1203                             _ => {},
1204                         }
1205                     },
1206                     ExprKind::Lit(..) => emit_lint(cx, vec, pushed_item),
1207                     _ => {},
1208                 }
1209             }
1210         }
1211     }
1212 }
1213
1214 /// Checks for looping over a range and then indexing a sequence with it.
1215 /// The iteratee must be a range literal.
1216 #[allow(clippy::too_many_lines)]
1217 fn check_for_loop_range<'tcx>(
1218     cx: &LateContext<'tcx>,
1219     pat: &'tcx Pat<'_>,
1220     arg: &'tcx Expr<'_>,
1221     body: &'tcx Expr<'_>,
1222     expr: &'tcx Expr<'_>,
1223 ) {
1224     if let Some(higher::Range {
1225         start: Some(start),
1226         ref end,
1227         limits,
1228     }) = higher::range(arg)
1229     {
1230         // the var must be a single name
1231         if let PatKind::Binding(_, canonical_id, ident, _) = pat.kind {
1232             let mut visitor = VarVisitor {
1233                 cx,
1234                 var: canonical_id,
1235                 indexed_mut: FxHashSet::default(),
1236                 indexed_indirectly: FxHashMap::default(),
1237                 indexed_directly: FxHashMap::default(),
1238                 referenced: FxHashSet::default(),
1239                 nonindex: false,
1240                 prefer_mutable: false,
1241             };
1242             walk_expr(&mut visitor, body);
1243
1244             // linting condition: we only indexed one variable, and indexed it directly
1245             if visitor.indexed_indirectly.is_empty() && visitor.indexed_directly.len() == 1 {
1246                 let (indexed, (indexed_extent, indexed_ty)) = visitor
1247                     .indexed_directly
1248                     .into_iter()
1249                     .next()
1250                     .expect("already checked that we have exactly 1 element");
1251
1252                 // ensure that the indexed variable was declared before the loop, see #601
1253                 if let Some(indexed_extent) = indexed_extent {
1254                     let parent_id = cx.tcx.hir().get_parent_item(expr.hir_id);
1255                     let parent_def_id = cx.tcx.hir().local_def_id(parent_id);
1256                     let region_scope_tree = cx.tcx.region_scope_tree(parent_def_id);
1257                     let pat_extent = region_scope_tree.var_scope(pat.hir_id.local_id);
1258                     if region_scope_tree.is_subscope_of(indexed_extent, pat_extent) {
1259                         return;
1260                     }
1261                 }
1262
1263                 // don't lint if the container that is indexed does not have .iter() method
1264                 let has_iter = has_iter_method(cx, indexed_ty);
1265                 if has_iter.is_none() {
1266                     return;
1267                 }
1268
1269                 // don't lint if the container that is indexed into is also used without
1270                 // indexing
1271                 if visitor.referenced.contains(&indexed) {
1272                     return;
1273                 }
1274
1275                 let starts_at_zero = is_integer_const(cx, start, 0);
1276
1277                 let skip = if starts_at_zero {
1278                     String::new()
1279                 } else {
1280                     format!(".skip({})", snippet(cx, start.span, ".."))
1281                 };
1282
1283                 let mut end_is_start_plus_val = false;
1284
1285                 let take = if let Some(end) = *end {
1286                     let mut take_expr = end;
1287
1288                     if let ExprKind::Binary(ref op, ref left, ref right) = end.kind {
1289                         if let BinOpKind::Add = op.node {
1290                             let start_equal_left = SpanlessEq::new(cx).eq_expr(start, left);
1291                             let start_equal_right = SpanlessEq::new(cx).eq_expr(start, right);
1292
1293                             if start_equal_left {
1294                                 take_expr = right;
1295                             } else if start_equal_right {
1296                                 take_expr = left;
1297                             }
1298
1299                             end_is_start_plus_val = start_equal_left | start_equal_right;
1300                         }
1301                     }
1302
1303                     if is_len_call(end, indexed) || is_end_eq_array_len(cx, end, limits, indexed_ty) {
1304                         String::new()
1305                     } else {
1306                         match limits {
1307                             ast::RangeLimits::Closed => {
1308                                 let take_expr = sugg::Sugg::hir(cx, take_expr, "<count>");
1309                                 format!(".take({})", take_expr + sugg::ONE)
1310                             },
1311                             ast::RangeLimits::HalfOpen => format!(".take({})", snippet(cx, take_expr.span, "..")),
1312                         }
1313                     }
1314                 } else {
1315                     String::new()
1316                 };
1317
1318                 let (ref_mut, method) = if visitor.indexed_mut.contains(&indexed) {
1319                     ("mut ", "iter_mut")
1320                 } else {
1321                     ("", "iter")
1322                 };
1323
1324                 let take_is_empty = take.is_empty();
1325                 let mut method_1 = take;
1326                 let mut method_2 = skip;
1327
1328                 if end_is_start_plus_val {
1329                     mem::swap(&mut method_1, &mut method_2);
1330                 }
1331
1332                 if visitor.nonindex {
1333                     span_lint_and_then(
1334                         cx,
1335                         NEEDLESS_RANGE_LOOP,
1336                         expr.span,
1337                         &format!("the loop variable `{}` is used to index `{}`", ident.name, indexed),
1338                         |diag| {
1339                             multispan_sugg(
1340                                 diag,
1341                                 "consider using an iterator",
1342                                 vec![
1343                                     (pat.span, format!("({}, <item>)", ident.name)),
1344                                     (
1345                                         arg.span,
1346                                         format!("{}.{}().enumerate(){}{}", indexed, method, method_1, method_2),
1347                                     ),
1348                                 ],
1349                             );
1350                         },
1351                     );
1352                 } else {
1353                     let repl = if starts_at_zero && take_is_empty {
1354                         format!("&{}{}", ref_mut, indexed)
1355                     } else {
1356                         format!("{}.{}(){}{}", indexed, method, method_1, method_2)
1357                     };
1358
1359                     span_lint_and_then(
1360                         cx,
1361                         NEEDLESS_RANGE_LOOP,
1362                         expr.span,
1363                         &format!(
1364                             "the loop variable `{}` is only used to index `{}`.",
1365                             ident.name, indexed
1366                         ),
1367                         |diag| {
1368                             multispan_sugg(
1369                                 diag,
1370                                 "consider using an iterator",
1371                                 vec![(pat.span, "<item>".to_string()), (arg.span, repl)],
1372                             );
1373                         },
1374                     );
1375                 }
1376             }
1377         }
1378     }
1379 }
1380
1381 fn is_len_call(expr: &Expr<'_>, var: Symbol) -> bool {
1382     if_chain! {
1383         if let ExprKind::MethodCall(ref method, _, ref len_args, _) = expr.kind;
1384         if len_args.len() == 1;
1385         if method.ident.name == sym!(len);
1386         if let ExprKind::Path(QPath::Resolved(_, ref path)) = len_args[0].kind;
1387         if path.segments.len() == 1;
1388         if path.segments[0].ident.name == var;
1389         then {
1390             return true;
1391         }
1392     }
1393
1394     false
1395 }
1396
1397 fn is_end_eq_array_len<'tcx>(
1398     cx: &LateContext<'tcx>,
1399     end: &Expr<'_>,
1400     limits: ast::RangeLimits,
1401     indexed_ty: Ty<'tcx>,
1402 ) -> bool {
1403     if_chain! {
1404         if let ExprKind::Lit(ref lit) = end.kind;
1405         if let ast::LitKind::Int(end_int, _) = lit.node;
1406         if let ty::Array(_, arr_len_const) = indexed_ty.kind();
1407         if let Some(arr_len) = arr_len_const.try_eval_usize(cx.tcx, cx.param_env);
1408         then {
1409             return match limits {
1410                 ast::RangeLimits::Closed => end_int + 1 >= arr_len.into(),
1411                 ast::RangeLimits::HalfOpen => end_int >= arr_len.into(),
1412             };
1413         }
1414     }
1415
1416     false
1417 }
1418
1419 fn lint_iter_method(cx: &LateContext<'_>, args: &[Expr<'_>], arg: &Expr<'_>, method_name: &str) {
1420     let mut applicability = Applicability::MachineApplicable;
1421     let object = snippet_with_applicability(cx, args[0].span, "_", &mut applicability);
1422     let muta = if method_name == "iter_mut" { "mut " } else { "" };
1423     span_lint_and_sugg(
1424         cx,
1425         EXPLICIT_ITER_LOOP,
1426         arg.span,
1427         "it is more concise to loop over references to containers instead of using explicit \
1428          iteration methods",
1429         "to write this more concisely, try",
1430         format!("&{}{}", muta, object),
1431         applicability,
1432     )
1433 }
1434
1435 fn check_for_loop_arg(cx: &LateContext<'_>, pat: &Pat<'_>, arg: &Expr<'_>, expr: &Expr<'_>) {
1436     let mut next_loop_linted = false; // whether or not ITER_NEXT_LOOP lint was used
1437     if let ExprKind::MethodCall(ref method, _, ref args, _) = arg.kind {
1438         // just the receiver, no arguments
1439         if args.len() == 1 {
1440             let method_name = &*method.ident.as_str();
1441             // check for looping over x.iter() or x.iter_mut(), could use &x or &mut x
1442             if method_name == "iter" || method_name == "iter_mut" {
1443                 if is_ref_iterable_type(cx, &args[0]) {
1444                     lint_iter_method(cx, args, arg, method_name);
1445                 }
1446             } else if method_name == "into_iter" && match_trait_method(cx, arg, &paths::INTO_ITERATOR) {
1447                 let receiver_ty = cx.typeck_results().expr_ty(&args[0]);
1448                 let receiver_ty_adjusted = cx.typeck_results().expr_ty_adjusted(&args[0]);
1449                 if TyS::same_type(receiver_ty, receiver_ty_adjusted) {
1450                     let mut applicability = Applicability::MachineApplicable;
1451                     let object = snippet_with_applicability(cx, args[0].span, "_", &mut applicability);
1452                     span_lint_and_sugg(
1453                         cx,
1454                         EXPLICIT_INTO_ITER_LOOP,
1455                         arg.span,
1456                         "it is more concise to loop over containers instead of using explicit \
1457                          iteration methods",
1458                         "to write this more concisely, try",
1459                         object.to_string(),
1460                         applicability,
1461                     );
1462                 } else {
1463                     let ref_receiver_ty = cx.tcx.mk_ref(
1464                         cx.tcx.lifetimes.re_erased,
1465                         ty::TypeAndMut {
1466                             ty: receiver_ty,
1467                             mutbl: Mutability::Not,
1468                         },
1469                     );
1470                     if TyS::same_type(receiver_ty_adjusted, ref_receiver_ty) {
1471                         lint_iter_method(cx, args, arg, method_name)
1472                     }
1473                 }
1474             } else if method_name == "next" && match_trait_method(cx, arg, &paths::ITERATOR) {
1475                 span_lint(
1476                     cx,
1477                     ITER_NEXT_LOOP,
1478                     expr.span,
1479                     "you are iterating over `Iterator::next()` which is an Option; this will compile but is \
1480                     probably not what you want",
1481                 );
1482                 next_loop_linted = true;
1483             }
1484         }
1485     }
1486     if !next_loop_linted {
1487         check_arg_type(cx, pat, arg);
1488     }
1489 }
1490
1491 /// Checks for `for` loops over `Option`s and `Result`s.
1492 fn check_arg_type(cx: &LateContext<'_>, pat: &Pat<'_>, arg: &Expr<'_>) {
1493     let ty = cx.typeck_results().expr_ty(arg);
1494     if is_type_diagnostic_item(cx, ty, sym!(option_type)) {
1495         span_lint_and_help(
1496             cx,
1497             FOR_LOOPS_OVER_FALLIBLES,
1498             arg.span,
1499             &format!(
1500                 "for loop over `{0}`, which is an `Option`. This is more readably written as an \
1501                 `if let` statement.",
1502                 snippet(cx, arg.span, "_")
1503             ),
1504             None,
1505             &format!(
1506                 "consider replacing `for {0} in {1}` with `if let Some({0}) = {1}`",
1507                 snippet(cx, pat.span, "_"),
1508                 snippet(cx, arg.span, "_")
1509             ),
1510         );
1511     } else if is_type_diagnostic_item(cx, ty, sym!(result_type)) {
1512         span_lint_and_help(
1513             cx,
1514             FOR_LOOPS_OVER_FALLIBLES,
1515             arg.span,
1516             &format!(
1517                 "for loop over `{0}`, which is a `Result`. This is more readably written as an \
1518                 `if let` statement.",
1519                 snippet(cx, arg.span, "_")
1520             ),
1521             None,
1522             &format!(
1523                 "consider replacing `for {0} in {1}` with `if let Ok({0}) = {1}`",
1524                 snippet(cx, pat.span, "_"),
1525                 snippet(cx, arg.span, "_")
1526             ),
1527         );
1528     }
1529 }
1530
1531 fn check_for_loop_explicit_counter<'tcx>(
1532     cx: &LateContext<'tcx>,
1533     pat: &'tcx Pat<'_>,
1534     arg: &'tcx Expr<'_>,
1535     body: &'tcx Expr<'_>,
1536     expr: &'tcx Expr<'_>,
1537 ) {
1538     // Look for variables that are incremented once per loop iteration.
1539     let mut visitor = IncrementVisitor {
1540         cx,
1541         states: FxHashMap::default(),
1542         depth: 0,
1543         done: false,
1544     };
1545     walk_expr(&mut visitor, body);
1546
1547     // For each candidate, check the parent block to see if
1548     // it's initialized to zero at the start of the loop.
1549     if let Some(block) = get_enclosing_block(&cx, expr.hir_id) {
1550         for (id, _) in visitor.states.iter().filter(|&(_, v)| *v == VarState::IncrOnce) {
1551             let mut visitor2 = InitializeVisitor {
1552                 cx,
1553                 end_expr: expr,
1554                 var_id: *id,
1555                 state: VarState::IncrOnce,
1556                 name: None,
1557                 depth: 0,
1558                 past_loop: false,
1559             };
1560             walk_block(&mut visitor2, block);
1561
1562             if visitor2.state == VarState::Warn {
1563                 if let Some(name) = visitor2.name {
1564                     let mut applicability = Applicability::MachineApplicable;
1565
1566                     // for some reason this is the only way to get the `Span`
1567                     // of the entire `for` loop
1568                     let for_span = if let ExprKind::Match(_, arms, _) = &expr.kind {
1569                         arms[0].body.span
1570                     } else {
1571                         unreachable!()
1572                     };
1573
1574                     span_lint_and_sugg(
1575                         cx,
1576                         EXPLICIT_COUNTER_LOOP,
1577                         for_span.with_hi(arg.span.hi()),
1578                         &format!("the variable `{}` is used as a loop counter.", name),
1579                         "consider using",
1580                         format!(
1581                             "for ({}, {}) in {}.enumerate()",
1582                             name,
1583                             snippet_with_applicability(cx, pat.span, "item", &mut applicability),
1584                             make_iterator_snippet(cx, arg, &mut applicability),
1585                         ),
1586                         applicability,
1587                     );
1588                 }
1589             }
1590         }
1591     }
1592 }
1593
1594 /// If `arg` was the argument to a `for` loop, return the "cleanest" way of writing the
1595 /// actual `Iterator` that the loop uses.
1596 fn make_iterator_snippet(cx: &LateContext<'_>, arg: &Expr<'_>, applic_ref: &mut Applicability) -> String {
1597     let impls_iterator = get_trait_def_id(cx, &paths::ITERATOR).map_or(false, |id| {
1598         implements_trait(cx, cx.typeck_results().expr_ty(arg), id, &[])
1599     });
1600     if impls_iterator {
1601         format!(
1602             "{}",
1603             sugg::Sugg::hir_with_applicability(cx, arg, "_", applic_ref).maybe_par()
1604         )
1605     } else {
1606         // (&x).into_iter() ==> x.iter()
1607         // (&mut x).into_iter() ==> x.iter_mut()
1608         match &arg.kind {
1609             ExprKind::AddrOf(BorrowKind::Ref, mutability, arg_inner)
1610                 if has_iter_method(cx, cx.typeck_results().expr_ty(&arg_inner)).is_some() =>
1611             {
1612                 let meth_name = match mutability {
1613                     Mutability::Mut => "iter_mut",
1614                     Mutability::Not => "iter",
1615                 };
1616                 format!(
1617                     "{}.{}()",
1618                     sugg::Sugg::hir_with_applicability(cx, &arg_inner, "_", applic_ref).maybe_par(),
1619                     meth_name,
1620                 )
1621             }
1622             _ => format!(
1623                 "{}.into_iter()",
1624                 sugg::Sugg::hir_with_applicability(cx, arg, "_", applic_ref).maybe_par()
1625             ),
1626         }
1627     }
1628 }
1629
1630 /// Checks for the `FOR_KV_MAP` lint.
1631 fn check_for_loop_over_map_kv<'tcx>(
1632     cx: &LateContext<'tcx>,
1633     pat: &'tcx Pat<'_>,
1634     arg: &'tcx Expr<'_>,
1635     body: &'tcx Expr<'_>,
1636     expr: &'tcx Expr<'_>,
1637 ) {
1638     let pat_span = pat.span;
1639
1640     if let PatKind::Tuple(ref pat, _) = pat.kind {
1641         if pat.len() == 2 {
1642             let arg_span = arg.span;
1643             let (new_pat_span, kind, ty, mutbl) = match *cx.typeck_results().expr_ty(arg).kind() {
1644                 ty::Ref(_, ty, mutbl) => match (&pat[0].kind, &pat[1].kind) {
1645                     (key, _) if pat_is_wild(key, body) => (pat[1].span, "value", ty, mutbl),
1646                     (_, value) if pat_is_wild(value, body) => (pat[0].span, "key", ty, Mutability::Not),
1647                     _ => return,
1648                 },
1649                 _ => return,
1650             };
1651             let mutbl = match mutbl {
1652                 Mutability::Not => "",
1653                 Mutability::Mut => "_mut",
1654             };
1655             let arg = match arg.kind {
1656                 ExprKind::AddrOf(BorrowKind::Ref, _, ref expr) => &**expr,
1657                 _ => arg,
1658             };
1659
1660             if is_type_diagnostic_item(cx, ty, sym!(hashmap_type)) || match_type(cx, ty, &paths::BTREEMAP) {
1661                 span_lint_and_then(
1662                     cx,
1663                     FOR_KV_MAP,
1664                     expr.span,
1665                     &format!("you seem to want to iterate on a map's {}s", kind),
1666                     |diag| {
1667                         let map = sugg::Sugg::hir(cx, arg, "map");
1668                         multispan_sugg(
1669                             diag,
1670                             "use the corresponding method",
1671                             vec![
1672                                 (pat_span, snippet(cx, new_pat_span, kind).into_owned()),
1673                                 (arg_span, format!("{}.{}s{}()", map.maybe_par(), kind, mutbl)),
1674                             ],
1675                         );
1676                     },
1677                 );
1678             }
1679         }
1680     }
1681 }
1682
1683 struct MutatePairDelegate<'a, 'tcx> {
1684     cx: &'a LateContext<'tcx>,
1685     hir_id_low: Option<HirId>,
1686     hir_id_high: Option<HirId>,
1687     span_low: Option<Span>,
1688     span_high: Option<Span>,
1689 }
1690
1691 impl<'tcx> Delegate<'tcx> for MutatePairDelegate<'_, 'tcx> {
1692     fn consume(&mut self, _: &PlaceWithHirId<'tcx>, _: ConsumeMode) {}
1693
1694     fn borrow(&mut self, cmt: &PlaceWithHirId<'tcx>, bk: ty::BorrowKind) {
1695         if let ty::BorrowKind::MutBorrow = bk {
1696             if let PlaceBase::Local(id) = cmt.place.base {
1697                 if Some(id) == self.hir_id_low {
1698                     self.span_low = Some(self.cx.tcx.hir().span(cmt.hir_id))
1699                 }
1700                 if Some(id) == self.hir_id_high {
1701                     self.span_high = Some(self.cx.tcx.hir().span(cmt.hir_id))
1702                 }
1703             }
1704         }
1705     }
1706
1707     fn mutate(&mut self, cmt: &PlaceWithHirId<'tcx>) {
1708         if let PlaceBase::Local(id) = cmt.place.base {
1709             if Some(id) == self.hir_id_low {
1710                 self.span_low = Some(self.cx.tcx.hir().span(cmt.hir_id))
1711             }
1712             if Some(id) == self.hir_id_high {
1713                 self.span_high = Some(self.cx.tcx.hir().span(cmt.hir_id))
1714             }
1715         }
1716     }
1717 }
1718
1719 impl MutatePairDelegate<'_, '_> {
1720     fn mutation_span(&self) -> (Option<Span>, Option<Span>) {
1721         (self.span_low, self.span_high)
1722     }
1723 }
1724
1725 fn check_for_mut_range_bound(cx: &LateContext<'_>, arg: &Expr<'_>, body: &Expr<'_>) {
1726     if let Some(higher::Range {
1727         start: Some(start),
1728         end: Some(end),
1729         ..
1730     }) = higher::range(arg)
1731     {
1732         let mut_ids = vec![check_for_mutability(cx, start), check_for_mutability(cx, end)];
1733         if mut_ids[0].is_some() || mut_ids[1].is_some() {
1734             let (span_low, span_high) = check_for_mutation(cx, body, &mut_ids);
1735             mut_warn_with_span(cx, span_low);
1736             mut_warn_with_span(cx, span_high);
1737         }
1738     }
1739 }
1740
1741 fn mut_warn_with_span(cx: &LateContext<'_>, span: Option<Span>) {
1742     if let Some(sp) = span {
1743         span_lint(
1744             cx,
1745             MUT_RANGE_BOUND,
1746             sp,
1747             "attempt to mutate range bound within loop; note that the range of the loop is unchanged",
1748         );
1749     }
1750 }
1751
1752 fn check_for_mutability(cx: &LateContext<'_>, bound: &Expr<'_>) -> Option<HirId> {
1753     if_chain! {
1754         if let ExprKind::Path(ref qpath) = bound.kind;
1755         if let QPath::Resolved(None, _) = *qpath;
1756         then {
1757             let res = qpath_res(cx, qpath, bound.hir_id);
1758             if let Res::Local(hir_id) = res {
1759                 let node_str = cx.tcx.hir().get(hir_id);
1760                 if_chain! {
1761                     if let Node::Binding(pat) = node_str;
1762                     if let PatKind::Binding(bind_ann, ..) = pat.kind;
1763                     if let BindingAnnotation::Mutable = bind_ann;
1764                     then {
1765                         return Some(hir_id);
1766                     }
1767                 }
1768             }
1769         }
1770     }
1771     None
1772 }
1773
1774 fn check_for_mutation<'tcx>(
1775     cx: &LateContext<'tcx>,
1776     body: &Expr<'_>,
1777     bound_ids: &[Option<HirId>],
1778 ) -> (Option<Span>, Option<Span>) {
1779     let mut delegate = MutatePairDelegate {
1780         cx,
1781         hir_id_low: bound_ids[0],
1782         hir_id_high: bound_ids[1],
1783         span_low: None,
1784         span_high: None,
1785     };
1786     let def_id = body.hir_id.owner.to_def_id();
1787     cx.tcx.infer_ctxt().enter(|infcx| {
1788         ExprUseVisitor::new(
1789             &mut delegate,
1790             &infcx,
1791             def_id.expect_local(),
1792             cx.param_env,
1793             cx.typeck_results(),
1794         )
1795         .walk_expr(body);
1796     });
1797     delegate.mutation_span()
1798 }
1799
1800 /// Returns `true` if the pattern is a `PatWild` or an ident prefixed with `_`.
1801 fn pat_is_wild<'tcx>(pat: &'tcx PatKind<'_>, body: &'tcx Expr<'_>) -> bool {
1802     match *pat {
1803         PatKind::Wild => true,
1804         PatKind::Binding(.., ident, None) if ident.as_str().starts_with('_') => is_unused(&ident, body),
1805         _ => false,
1806     }
1807 }
1808
1809 struct LocalUsedVisitor<'a, 'tcx> {
1810     cx: &'a LateContext<'tcx>,
1811     local: HirId,
1812     used: bool,
1813 }
1814
1815 impl<'a, 'tcx> Visitor<'tcx> for LocalUsedVisitor<'a, 'tcx> {
1816     type Map = Map<'tcx>;
1817
1818     fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
1819         if same_var(self.cx, expr, self.local) {
1820             self.used = true;
1821         } else {
1822             walk_expr(self, expr);
1823         }
1824     }
1825
1826     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
1827         NestedVisitorMap::None
1828     }
1829 }
1830
1831 struct VarVisitor<'a, 'tcx> {
1832     /// context reference
1833     cx: &'a LateContext<'tcx>,
1834     /// var name to look for as index
1835     var: HirId,
1836     /// indexed variables that are used mutably
1837     indexed_mut: FxHashSet<Symbol>,
1838     /// indirectly indexed variables (`v[(i + 4) % N]`), the extend is `None` for global
1839     indexed_indirectly: FxHashMap<Symbol, Option<region::Scope>>,
1840     /// subset of `indexed` of vars that are indexed directly: `v[i]`
1841     /// this will not contain cases like `v[calc_index(i)]` or `v[(i + 4) % N]`
1842     indexed_directly: FxHashMap<Symbol, (Option<region::Scope>, Ty<'tcx>)>,
1843     /// Any names that are used outside an index operation.
1844     /// Used to detect things like `&mut vec` used together with `vec[i]`
1845     referenced: FxHashSet<Symbol>,
1846     /// has the loop variable been used in expressions other than the index of
1847     /// an index op?
1848     nonindex: bool,
1849     /// Whether we are inside the `$` in `&mut $` or `$ = foo` or `$.bar`, where bar
1850     /// takes `&mut self`
1851     prefer_mutable: bool,
1852 }
1853
1854 impl<'a, 'tcx> VarVisitor<'a, 'tcx> {
1855     fn check(&mut self, idx: &'tcx Expr<'_>, seqexpr: &'tcx Expr<'_>, expr: &'tcx Expr<'_>) -> bool {
1856         if_chain! {
1857             // the indexed container is referenced by a name
1858             if let ExprKind::Path(ref seqpath) = seqexpr.kind;
1859             if let QPath::Resolved(None, ref seqvar) = *seqpath;
1860             if seqvar.segments.len() == 1;
1861             then {
1862                 let index_used_directly = same_var(self.cx, idx, self.var);
1863                 let indexed_indirectly = {
1864                     let mut used_visitor = LocalUsedVisitor {
1865                         cx: self.cx,
1866                         local: self.var,
1867                         used: false,
1868                     };
1869                     walk_expr(&mut used_visitor, idx);
1870                     used_visitor.used
1871                 };
1872
1873                 if indexed_indirectly || index_used_directly {
1874                     if self.prefer_mutable {
1875                         self.indexed_mut.insert(seqvar.segments[0].ident.name);
1876                     }
1877                     let res = qpath_res(self.cx, seqpath, seqexpr.hir_id);
1878                     match res {
1879                         Res::Local(hir_id) => {
1880                             let parent_id = self.cx.tcx.hir().get_parent_item(expr.hir_id);
1881                             let parent_def_id = self.cx.tcx.hir().local_def_id(parent_id);
1882                             let extent = self.cx.tcx.region_scope_tree(parent_def_id).var_scope(hir_id.local_id);
1883                             if indexed_indirectly {
1884                                 self.indexed_indirectly.insert(seqvar.segments[0].ident.name, Some(extent));
1885                             }
1886                             if index_used_directly {
1887                                 self.indexed_directly.insert(
1888                                     seqvar.segments[0].ident.name,
1889                                     (Some(extent), self.cx.typeck_results().node_type(seqexpr.hir_id)),
1890                                 );
1891                             }
1892                             return false;  // no need to walk further *on the variable*
1893                         }
1894                         Res::Def(DefKind::Static | DefKind::Const, ..) => {
1895                             if indexed_indirectly {
1896                                 self.indexed_indirectly.insert(seqvar.segments[0].ident.name, None);
1897                             }
1898                             if index_used_directly {
1899                                 self.indexed_directly.insert(
1900                                     seqvar.segments[0].ident.name,
1901                                     (None, self.cx.typeck_results().node_type(seqexpr.hir_id)),
1902                                 );
1903                             }
1904                             return false;  // no need to walk further *on the variable*
1905                         }
1906                         _ => (),
1907                     }
1908                 }
1909             }
1910         }
1911         true
1912     }
1913 }
1914
1915 impl<'a, 'tcx> Visitor<'tcx> for VarVisitor<'a, 'tcx> {
1916     type Map = Map<'tcx>;
1917
1918     fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
1919         if_chain! {
1920             // a range index op
1921             if let ExprKind::MethodCall(ref meth, _, ref args, _) = expr.kind;
1922             if (meth.ident.name == sym!(index) && match_trait_method(self.cx, expr, &paths::INDEX))
1923                 || (meth.ident.name == sym!(index_mut) && match_trait_method(self.cx, expr, &paths::INDEX_MUT));
1924             if !self.check(&args[1], &args[0], expr);
1925             then { return }
1926         }
1927
1928         if_chain! {
1929             // an index op
1930             if let ExprKind::Index(ref seqexpr, ref idx) = expr.kind;
1931             if !self.check(idx, seqexpr, expr);
1932             then { return }
1933         }
1934
1935         if_chain! {
1936             // directly using a variable
1937             if let ExprKind::Path(ref qpath) = expr.kind;
1938             if let QPath::Resolved(None, ref path) = *qpath;
1939             if path.segments.len() == 1;
1940             then {
1941                 if let Res::Local(local_id) = qpath_res(self.cx, qpath, expr.hir_id) {
1942                     if local_id == self.var {
1943                         self.nonindex = true;
1944                     } else {
1945                         // not the correct variable, but still a variable
1946                         self.referenced.insert(path.segments[0].ident.name);
1947                     }
1948                 }
1949             }
1950         }
1951
1952         let old = self.prefer_mutable;
1953         match expr.kind {
1954             ExprKind::AssignOp(_, ref lhs, ref rhs) | ExprKind::Assign(ref lhs, ref rhs, _) => {
1955                 self.prefer_mutable = true;
1956                 self.visit_expr(lhs);
1957                 self.prefer_mutable = false;
1958                 self.visit_expr(rhs);
1959             },
1960             ExprKind::AddrOf(BorrowKind::Ref, mutbl, ref expr) => {
1961                 if mutbl == Mutability::Mut {
1962                     self.prefer_mutable = true;
1963                 }
1964                 self.visit_expr(expr);
1965             },
1966             ExprKind::Call(ref f, args) => {
1967                 self.visit_expr(f);
1968                 for expr in args {
1969                     let ty = self.cx.typeck_results().expr_ty_adjusted(expr);
1970                     self.prefer_mutable = false;
1971                     if let ty::Ref(_, _, mutbl) = *ty.kind() {
1972                         if mutbl == Mutability::Mut {
1973                             self.prefer_mutable = true;
1974                         }
1975                     }
1976                     self.visit_expr(expr);
1977                 }
1978             },
1979             ExprKind::MethodCall(_, _, args, _) => {
1980                 let def_id = self.cx.typeck_results().type_dependent_def_id(expr.hir_id).unwrap();
1981                 for (ty, expr) in self.cx.tcx.fn_sig(def_id).inputs().skip_binder().iter().zip(args) {
1982                     self.prefer_mutable = false;
1983                     if let ty::Ref(_, _, mutbl) = *ty.kind() {
1984                         if mutbl == Mutability::Mut {
1985                             self.prefer_mutable = true;
1986                         }
1987                     }
1988                     self.visit_expr(expr);
1989                 }
1990             },
1991             ExprKind::Closure(_, _, body_id, ..) => {
1992                 let body = self.cx.tcx.hir().body(body_id);
1993                 self.visit_expr(&body.value);
1994             },
1995             _ => walk_expr(self, expr),
1996         }
1997         self.prefer_mutable = old;
1998     }
1999     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
2000         NestedVisitorMap::None
2001     }
2002 }
2003
2004 fn is_used_inside<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, container: &'tcx Expr<'_>) -> bool {
2005     let def_id = match var_def_id(cx, expr) {
2006         Some(id) => id,
2007         None => return false,
2008     };
2009     if let Some(used_mutably) = mutated_variables(container, cx) {
2010         if used_mutably.contains(&def_id) {
2011             return true;
2012         }
2013     }
2014     false
2015 }
2016
2017 fn is_iterator_used_after_while_let<'tcx>(cx: &LateContext<'tcx>, iter_expr: &'tcx Expr<'_>) -> bool {
2018     let def_id = match var_def_id(cx, iter_expr) {
2019         Some(id) => id,
2020         None => return false,
2021     };
2022     let mut visitor = VarUsedAfterLoopVisitor {
2023         cx,
2024         def_id,
2025         iter_expr_id: iter_expr.hir_id,
2026         past_while_let: false,
2027         var_used_after_while_let: false,
2028     };
2029     if let Some(enclosing_block) = get_enclosing_block(cx, def_id) {
2030         walk_block(&mut visitor, enclosing_block);
2031     }
2032     visitor.var_used_after_while_let
2033 }
2034
2035 struct VarUsedAfterLoopVisitor<'a, 'tcx> {
2036     cx: &'a LateContext<'tcx>,
2037     def_id: HirId,
2038     iter_expr_id: HirId,
2039     past_while_let: bool,
2040     var_used_after_while_let: bool,
2041 }
2042
2043 impl<'a, 'tcx> Visitor<'tcx> for VarUsedAfterLoopVisitor<'a, 'tcx> {
2044     type Map = Map<'tcx>;
2045
2046     fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
2047         if self.past_while_let {
2048             if Some(self.def_id) == var_def_id(self.cx, expr) {
2049                 self.var_used_after_while_let = true;
2050             }
2051         } else if self.iter_expr_id == expr.hir_id {
2052             self.past_while_let = true;
2053         }
2054         walk_expr(self, expr);
2055     }
2056     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
2057         NestedVisitorMap::None
2058     }
2059 }
2060
2061 /// Returns `true` if the type of expr is one that provides `IntoIterator` impls
2062 /// for `&T` and `&mut T`, such as `Vec`.
2063 #[rustfmt::skip]
2064 fn is_ref_iterable_type(cx: &LateContext<'_>, e: &Expr<'_>) -> bool {
2065     // no walk_ptrs_ty: calling iter() on a reference can make sense because it
2066     // will allow further borrows afterwards
2067     let ty = cx.typeck_results().expr_ty(e);
2068     is_iterable_array(ty, cx) ||
2069     is_type_diagnostic_item(cx, ty, sym!(vec_type)) ||
2070     match_type(cx, ty, &paths::LINKED_LIST) ||
2071     is_type_diagnostic_item(cx, ty, sym!(hashmap_type)) ||
2072     is_type_diagnostic_item(cx, ty, sym!(hashset_type)) ||
2073     is_type_diagnostic_item(cx, ty, sym!(vecdeque_type)) ||
2074     match_type(cx, ty, &paths::BINARY_HEAP) ||
2075     match_type(cx, ty, &paths::BTREEMAP) ||
2076     match_type(cx, ty, &paths::BTREESET)
2077 }
2078
2079 fn is_iterable_array<'tcx>(ty: Ty<'tcx>, cx: &LateContext<'tcx>) -> bool {
2080     // IntoIterator is currently only implemented for array sizes <= 32 in rustc
2081     match ty.kind() {
2082         ty::Array(_, n) => n
2083             .try_eval_usize(cx.tcx, cx.param_env)
2084             .map_or(false, |val| (0..=32).contains(&val)),
2085         _ => false,
2086     }
2087 }
2088
2089 /// If a block begins with a statement (possibly a `let` binding) and has an
2090 /// expression, return it.
2091 fn extract_expr_from_first_stmt<'tcx>(block: &Block<'tcx>) -> Option<&'tcx Expr<'tcx>> {
2092     if block.stmts.is_empty() {
2093         return None;
2094     }
2095     if let StmtKind::Local(ref local) = block.stmts[0].kind {
2096         local.init //.map(|expr| expr)
2097     } else {
2098         None
2099     }
2100 }
2101
2102 /// If a block begins with an expression (with or without semicolon), return it.
2103 fn extract_first_expr<'tcx>(block: &Block<'tcx>) -> Option<&'tcx Expr<'tcx>> {
2104     match block.expr {
2105         Some(ref expr) if block.stmts.is_empty() => Some(expr),
2106         None if !block.stmts.is_empty() => match block.stmts[0].kind {
2107             StmtKind::Expr(ref expr) | StmtKind::Semi(ref expr) => Some(expr),
2108             StmtKind::Local(..) | StmtKind::Item(..) => None,
2109         },
2110         _ => None,
2111     }
2112 }
2113
2114 /// Returns `true` if expr contains a single break expr without destination label
2115 /// and
2116 /// passed expression. The expression may be within a block.
2117 fn is_simple_break_expr(expr: &Expr<'_>) -> bool {
2118     match expr.kind {
2119         ExprKind::Break(dest, ref passed_expr) if dest.label.is_none() && passed_expr.is_none() => true,
2120         ExprKind::Block(ref b, _) => extract_first_expr(b).map_or(false, |subexpr| is_simple_break_expr(subexpr)),
2121         _ => false,
2122     }
2123 }
2124
2125 // To trigger the EXPLICIT_COUNTER_LOOP lint, a variable must be
2126 // incremented exactly once in the loop body, and initialized to zero
2127 // at the start of the loop.
2128 #[derive(Debug, PartialEq)]
2129 enum VarState {
2130     Initial,  // Not examined yet
2131     IncrOnce, // Incremented exactly once, may be a loop counter
2132     Declared, // Declared but not (yet) initialized to zero
2133     Warn,
2134     DontWarn,
2135 }
2136
2137 /// Scan a for loop for variables that are incremented exactly once.
2138 struct IncrementVisitor<'a, 'tcx> {
2139     cx: &'a LateContext<'tcx>,          // context reference
2140     states: FxHashMap<HirId, VarState>, // incremented variables
2141     depth: u32,                         // depth of conditional expressions
2142     done: bool,
2143 }
2144
2145 impl<'a, 'tcx> Visitor<'tcx> for IncrementVisitor<'a, 'tcx> {
2146     type Map = Map<'tcx>;
2147
2148     fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
2149         if self.done {
2150             return;
2151         }
2152
2153         // If node is a variable
2154         if let Some(def_id) = var_def_id(self.cx, expr) {
2155             if let Some(parent) = get_parent_expr(self.cx, expr) {
2156                 let state = self.states.entry(def_id).or_insert(VarState::Initial);
2157
2158                 match parent.kind {
2159                     ExprKind::AssignOp(op, ref lhs, ref rhs) => {
2160                         if lhs.hir_id == expr.hir_id {
2161                             if op.node == BinOpKind::Add && is_integer_const(self.cx, rhs, 1) {
2162                                 *state = match *state {
2163                                     VarState::Initial if self.depth == 0 => VarState::IncrOnce,
2164                                     _ => VarState::DontWarn,
2165                                 };
2166                             } else {
2167                                 // Assigned some other value
2168                                 *state = VarState::DontWarn;
2169                             }
2170                         }
2171                     },
2172                     ExprKind::Assign(ref lhs, _, _) if lhs.hir_id == expr.hir_id => *state = VarState::DontWarn,
2173                     ExprKind::AddrOf(BorrowKind::Ref, mutability, _) if mutability == Mutability::Mut => {
2174                         *state = VarState::DontWarn
2175                     },
2176                     _ => (),
2177                 }
2178             }
2179         } else if is_loop(expr) || is_conditional(expr) {
2180             self.depth += 1;
2181             walk_expr(self, expr);
2182             self.depth -= 1;
2183             return;
2184         } else if let ExprKind::Continue(_) = expr.kind {
2185             self.done = true;
2186             return;
2187         }
2188         walk_expr(self, expr);
2189     }
2190     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
2191         NestedVisitorMap::None
2192     }
2193 }
2194
2195 /// Checks whether a variable is initialized to zero at the start of a loop.
2196 struct InitializeVisitor<'a, 'tcx> {
2197     cx: &'a LateContext<'tcx>,  // context reference
2198     end_expr: &'tcx Expr<'tcx>, // the for loop. Stop scanning here.
2199     var_id: HirId,
2200     state: VarState,
2201     name: Option<Symbol>,
2202     depth: u32, // depth of conditional expressions
2203     past_loop: bool,
2204 }
2205
2206 impl<'a, 'tcx> Visitor<'tcx> for InitializeVisitor<'a, 'tcx> {
2207     type Map = Map<'tcx>;
2208
2209     fn visit_stmt(&mut self, stmt: &'tcx Stmt<'_>) {
2210         // Look for declarations of the variable
2211         if let StmtKind::Local(ref local) = stmt.kind {
2212             if local.pat.hir_id == self.var_id {
2213                 if let PatKind::Binding(.., ident, _) = local.pat.kind {
2214                     self.name = Some(ident.name);
2215
2216                     self.state = local.init.as_ref().map_or(VarState::Declared, |init| {
2217                         if is_integer_const(&self.cx, init, 0) {
2218                             VarState::Warn
2219                         } else {
2220                             VarState::Declared
2221                         }
2222                     })
2223                 }
2224             }
2225         }
2226         walk_stmt(self, stmt);
2227     }
2228
2229     fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
2230         if self.state == VarState::DontWarn {
2231             return;
2232         }
2233         if expr.hir_id == self.end_expr.hir_id {
2234             self.past_loop = true;
2235             return;
2236         }
2237         // No need to visit expressions before the variable is
2238         // declared
2239         if self.state == VarState::IncrOnce {
2240             return;
2241         }
2242
2243         // If node is the desired variable, see how it's used
2244         if var_def_id(self.cx, expr) == Some(self.var_id) {
2245             if let Some(parent) = get_parent_expr(self.cx, expr) {
2246                 match parent.kind {
2247                     ExprKind::AssignOp(_, ref lhs, _) if lhs.hir_id == expr.hir_id => {
2248                         self.state = VarState::DontWarn;
2249                     },
2250                     ExprKind::Assign(ref lhs, ref rhs, _) if lhs.hir_id == expr.hir_id => {
2251                         self.state = if is_integer_const(&self.cx, rhs, 0) && self.depth == 0 {
2252                             VarState::Warn
2253                         } else {
2254                             VarState::DontWarn
2255                         }
2256                     },
2257                     ExprKind::AddrOf(BorrowKind::Ref, mutability, _) if mutability == Mutability::Mut => {
2258                         self.state = VarState::DontWarn
2259                     },
2260                     _ => (),
2261                 }
2262             }
2263
2264             if self.past_loop {
2265                 self.state = VarState::DontWarn;
2266                 return;
2267             }
2268         } else if !self.past_loop && is_loop(expr) {
2269             self.state = VarState::DontWarn;
2270             return;
2271         } else if is_conditional(expr) {
2272             self.depth += 1;
2273             walk_expr(self, expr);
2274             self.depth -= 1;
2275             return;
2276         }
2277         walk_expr(self, expr);
2278     }
2279
2280     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
2281         NestedVisitorMap::OnlyBodies(self.cx.tcx.hir())
2282     }
2283 }
2284
2285 fn var_def_id(cx: &LateContext<'_>, expr: &Expr<'_>) -> Option<HirId> {
2286     if let ExprKind::Path(ref qpath) = expr.kind {
2287         let path_res = qpath_res(cx, qpath, expr.hir_id);
2288         if let Res::Local(hir_id) = path_res {
2289             return Some(hir_id);
2290         }
2291     }
2292     None
2293 }
2294
2295 fn is_loop(expr: &Expr<'_>) -> bool {
2296     matches!(expr.kind, ExprKind::Loop(..))
2297 }
2298
2299 fn is_conditional(expr: &Expr<'_>) -> bool {
2300     matches!(expr.kind, ExprKind::Match(..))
2301 }
2302
2303 fn is_nested(cx: &LateContext<'_>, match_expr: &Expr<'_>, iter_expr: &Expr<'_>) -> bool {
2304     if_chain! {
2305         if let Some(loop_block) = get_enclosing_block(cx, match_expr.hir_id);
2306         let parent_node = cx.tcx.hir().get_parent_node(loop_block.hir_id);
2307         if let Some(Node::Expr(loop_expr)) = cx.tcx.hir().find(parent_node);
2308         then {
2309             return is_loop_nested(cx, loop_expr, iter_expr)
2310         }
2311     }
2312     false
2313 }
2314
2315 fn is_loop_nested(cx: &LateContext<'_>, loop_expr: &Expr<'_>, iter_expr: &Expr<'_>) -> bool {
2316     let mut id = loop_expr.hir_id;
2317     let iter_name = if let Some(name) = path_name(iter_expr) {
2318         name
2319     } else {
2320         return true;
2321     };
2322     loop {
2323         let parent = cx.tcx.hir().get_parent_node(id);
2324         if parent == id {
2325             return false;
2326         }
2327         match cx.tcx.hir().find(parent) {
2328             Some(Node::Expr(expr)) => {
2329                 if let ExprKind::Loop(..) = expr.kind {
2330                     return true;
2331                 };
2332             },
2333             Some(Node::Block(block)) => {
2334                 let mut block_visitor = LoopNestVisitor {
2335                     hir_id: id,
2336                     iterator: iter_name,
2337                     nesting: Unknown,
2338                 };
2339                 walk_block(&mut block_visitor, block);
2340                 if block_visitor.nesting == RuledOut {
2341                     return false;
2342                 }
2343             },
2344             Some(Node::Stmt(_)) => (),
2345             _ => {
2346                 return false;
2347             },
2348         }
2349         id = parent;
2350     }
2351 }
2352
2353 #[derive(PartialEq, Eq)]
2354 enum Nesting {
2355     Unknown,     // no nesting detected yet
2356     RuledOut,    // the iterator is initialized or assigned within scope
2357     LookFurther, // no nesting detected, no further walk required
2358 }
2359
2360 use self::Nesting::{LookFurther, RuledOut, Unknown};
2361
2362 struct LoopNestVisitor {
2363     hir_id: HirId,
2364     iterator: Symbol,
2365     nesting: Nesting,
2366 }
2367
2368 impl<'tcx> Visitor<'tcx> for LoopNestVisitor {
2369     type Map = Map<'tcx>;
2370
2371     fn visit_stmt(&mut self, stmt: &'tcx Stmt<'_>) {
2372         if stmt.hir_id == self.hir_id {
2373             self.nesting = LookFurther;
2374         } else if self.nesting == Unknown {
2375             walk_stmt(self, stmt);
2376         }
2377     }
2378
2379     fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
2380         if self.nesting != Unknown {
2381             return;
2382         }
2383         if expr.hir_id == self.hir_id {
2384             self.nesting = LookFurther;
2385             return;
2386         }
2387         match expr.kind {
2388             ExprKind::Assign(ref path, _, _) | ExprKind::AssignOp(_, ref path, _) => {
2389                 if match_var(path, self.iterator) {
2390                     self.nesting = RuledOut;
2391                 }
2392             },
2393             _ => walk_expr(self, expr),
2394         }
2395     }
2396
2397     fn visit_pat(&mut self, pat: &'tcx Pat<'_>) {
2398         if self.nesting != Unknown {
2399             return;
2400         }
2401         if let PatKind::Binding(.., span_name, _) = pat.kind {
2402             if self.iterator == span_name.name {
2403                 self.nesting = RuledOut;
2404                 return;
2405             }
2406         }
2407         walk_pat(self, pat)
2408     }
2409
2410     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
2411         NestedVisitorMap::None
2412     }
2413 }
2414
2415 fn path_name(e: &Expr<'_>) -> Option<Symbol> {
2416     if let ExprKind::Path(QPath::Resolved(_, ref path)) = e.kind {
2417         let segments = &path.segments;
2418         if segments.len() == 1 {
2419             return Some(segments[0].ident.name);
2420         }
2421     };
2422     None
2423 }
2424
2425 fn check_infinite_loop<'tcx>(cx: &LateContext<'tcx>, cond: &'tcx Expr<'_>, expr: &'tcx Expr<'_>) {
2426     if constant(cx, cx.typeck_results(), cond).is_some() {
2427         // A pure constant condition (e.g., `while false`) is not linted.
2428         return;
2429     }
2430
2431     let mut var_visitor = VarCollectorVisitor {
2432         cx,
2433         ids: FxHashSet::default(),
2434         def_ids: FxHashMap::default(),
2435         skip: false,
2436     };
2437     var_visitor.visit_expr(cond);
2438     if var_visitor.skip {
2439         return;
2440     }
2441     let used_in_condition = &var_visitor.ids;
2442     let no_cond_variable_mutated = if let Some(used_mutably) = mutated_variables(expr, cx) {
2443         used_in_condition.is_disjoint(&used_mutably)
2444     } else {
2445         return;
2446     };
2447     let mutable_static_in_cond = var_visitor.def_ids.iter().any(|(_, v)| *v);
2448
2449     let mut has_break_or_return_visitor = HasBreakOrReturnVisitor {
2450         has_break_or_return: false,
2451     };
2452     has_break_or_return_visitor.visit_expr(expr);
2453     let has_break_or_return = has_break_or_return_visitor.has_break_or_return;
2454
2455     if no_cond_variable_mutated && !mutable_static_in_cond {
2456         span_lint_and_then(
2457             cx,
2458             WHILE_IMMUTABLE_CONDITION,
2459             cond.span,
2460             "variables in the condition are not mutated in the loop body",
2461             |diag| {
2462                 diag.note("this may lead to an infinite or to a never running loop");
2463
2464                 if has_break_or_return {
2465                     diag.note("this loop contains `return`s or `break`s");
2466                     diag.help("rewrite it as `if cond { loop { } }`");
2467                 }
2468             },
2469         );
2470     }
2471 }
2472
2473 struct HasBreakOrReturnVisitor {
2474     has_break_or_return: bool,
2475 }
2476
2477 impl<'tcx> Visitor<'tcx> for HasBreakOrReturnVisitor {
2478     type Map = Map<'tcx>;
2479
2480     fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
2481         if self.has_break_or_return {
2482             return;
2483         }
2484
2485         match expr.kind {
2486             ExprKind::Ret(_) | ExprKind::Break(_, _) => {
2487                 self.has_break_or_return = true;
2488                 return;
2489             },
2490             _ => {},
2491         }
2492
2493         walk_expr(self, expr);
2494     }
2495
2496     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
2497         NestedVisitorMap::None
2498     }
2499 }
2500
2501 /// Collects the set of variables in an expression
2502 /// Stops analysis if a function call is found
2503 /// Note: In some cases such as `self`, there are no mutable annotation,
2504 /// All variables definition IDs are collected
2505 struct VarCollectorVisitor<'a, 'tcx> {
2506     cx: &'a LateContext<'tcx>,
2507     ids: FxHashSet<HirId>,
2508     def_ids: FxHashMap<def_id::DefId, bool>,
2509     skip: bool,
2510 }
2511
2512 impl<'a, 'tcx> VarCollectorVisitor<'a, 'tcx> {
2513     fn insert_def_id(&mut self, ex: &'tcx Expr<'_>) {
2514         if_chain! {
2515             if let ExprKind::Path(ref qpath) = ex.kind;
2516             if let QPath::Resolved(None, _) = *qpath;
2517             let res = qpath_res(self.cx, qpath, ex.hir_id);
2518             then {
2519                 match res {
2520                     Res::Local(hir_id) => {
2521                         self.ids.insert(hir_id);
2522                     },
2523                     Res::Def(DefKind::Static, def_id) => {
2524                         let mutable = self.cx.tcx.is_mutable_static(def_id);
2525                         self.def_ids.insert(def_id, mutable);
2526                     },
2527                     _ => {},
2528                 }
2529             }
2530         }
2531     }
2532 }
2533
2534 impl<'a, 'tcx> Visitor<'tcx> for VarCollectorVisitor<'a, 'tcx> {
2535     type Map = Map<'tcx>;
2536
2537     fn visit_expr(&mut self, ex: &'tcx Expr<'_>) {
2538         match ex.kind {
2539             ExprKind::Path(_) => self.insert_def_id(ex),
2540             // If there is any function/method call… we just stop analysis
2541             ExprKind::Call(..) | ExprKind::MethodCall(..) => self.skip = true,
2542
2543             _ => walk_expr(self, ex),
2544         }
2545     }
2546
2547     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
2548         NestedVisitorMap::None
2549     }
2550 }
2551
2552 const NEEDLESS_COLLECT_MSG: &str = "avoid using `collect()` when not needed";
2553
2554 fn check_needless_collect<'tcx>(expr: &'tcx Expr<'_>, cx: &LateContext<'tcx>) {
2555     check_needless_collect_direct_usage(expr, cx);
2556     check_needless_collect_indirect_usage(expr, cx);
2557 }
2558 fn check_needless_collect_direct_usage<'tcx>(expr: &'tcx Expr<'_>, cx: &LateContext<'tcx>) {
2559     if_chain! {
2560         if let ExprKind::MethodCall(ref method, _, ref args, _) = expr.kind;
2561         if let ExprKind::MethodCall(ref chain_method, _, _, _) = args[0].kind;
2562         if chain_method.ident.name == sym!(collect) && match_trait_method(cx, &args[0], &paths::ITERATOR);
2563         if let Some(ref generic_args) = chain_method.args;
2564         if let Some(GenericArg::Type(ref ty)) = generic_args.args.get(0);
2565         then {
2566             let ty = cx.typeck_results().node_type(ty.hir_id);
2567             if is_type_diagnostic_item(cx, ty, sym!(vec_type)) ||
2568                 is_type_diagnostic_item(cx, ty, sym!(vecdeque_type)) ||
2569                 match_type(cx, ty, &paths::BTREEMAP) ||
2570                 is_type_diagnostic_item(cx, ty, sym!(hashmap_type)) {
2571                 if method.ident.name == sym!(len) {
2572                     let span = shorten_needless_collect_span(expr);
2573                     span_lint_and_sugg(
2574                         cx,
2575                         NEEDLESS_COLLECT,
2576                         span,
2577                         NEEDLESS_COLLECT_MSG,
2578                         "replace with",
2579                         "count()".to_string(),
2580                         Applicability::MachineApplicable,
2581                     );
2582                 }
2583                 if method.ident.name == sym!(is_empty) {
2584                     let span = shorten_needless_collect_span(expr);
2585                     span_lint_and_sugg(
2586                         cx,
2587                         NEEDLESS_COLLECT,
2588                         span,
2589                         NEEDLESS_COLLECT_MSG,
2590                         "replace with",
2591                         "next().is_none()".to_string(),
2592                         Applicability::MachineApplicable,
2593                     );
2594                 }
2595                 if method.ident.name == sym!(contains) {
2596                     let contains_arg = snippet(cx, args[1].span, "??");
2597                     let span = shorten_needless_collect_span(expr);
2598                     span_lint_and_then(
2599                         cx,
2600                         NEEDLESS_COLLECT,
2601                         span,
2602                         NEEDLESS_COLLECT_MSG,
2603                         |diag| {
2604                             let (arg, pred) = if contains_arg.starts_with('&') {
2605                                 ("x", &contains_arg[1..])
2606                             } else {
2607                                 ("&x", &*contains_arg)
2608                             };
2609                             diag.span_suggestion(
2610                                 span,
2611                                 "replace with",
2612                                 format!(
2613                                     "any(|{}| x == {})",
2614                                     arg, pred
2615                                 ),
2616                                 Applicability::MachineApplicable,
2617                             );
2618                         }
2619                     );
2620                 }
2621             }
2622         }
2623     }
2624 }
2625
2626 fn check_needless_collect_indirect_usage<'tcx>(expr: &'tcx Expr<'_>, cx: &LateContext<'tcx>) {
2627     if let ExprKind::Block(ref block, _) = expr.kind {
2628         for ref stmt in block.stmts {
2629             if_chain! {
2630                 if let StmtKind::Local(
2631                     Local { pat: Pat { kind: PatKind::Binding(_, _, ident, .. ), .. },
2632                     init: Some(ref init_expr), .. }
2633                 ) = stmt.kind;
2634                 if let ExprKind::MethodCall(ref method_name, _, &[ref iter_source], ..) = init_expr.kind;
2635                 if method_name.ident.name == sym!(collect) && match_trait_method(cx, &init_expr, &paths::ITERATOR);
2636                 if let Some(ref generic_args) = method_name.args;
2637                 if let Some(GenericArg::Type(ref ty)) = generic_args.args.get(0);
2638                 if let ty = cx.typeck_results().node_type(ty.hir_id);
2639                 if is_type_diagnostic_item(cx, ty, sym::vec_type) ||
2640                     is_type_diagnostic_item(cx, ty, sym!(vecdeque_type)) ||
2641                     match_type(cx, ty, &paths::LINKED_LIST);
2642                 if let Some(iter_calls) = detect_iter_and_into_iters(block, *ident);
2643                 if iter_calls.len() == 1;
2644                 then {
2645                     // Suggest replacing iter_call with iter_replacement, and removing stmt
2646                     let iter_call = &iter_calls[0];
2647                     span_lint_and_then(
2648                         cx,
2649                         NEEDLESS_COLLECT,
2650                         stmt.span.until(iter_call.span),
2651                         NEEDLESS_COLLECT_MSG,
2652                         |diag| {
2653                             let iter_replacement = format!("{}{}", Sugg::hir(cx, iter_source, ".."), iter_call.get_iter_method(cx));
2654                             diag.multipart_suggestion(
2655                                 iter_call.get_suggestion_text(),
2656                                 vec![
2657                                     (stmt.span, String::new()),
2658                                     (iter_call.span, iter_replacement)
2659                                 ],
2660                                 Applicability::MachineApplicable,// MaybeIncorrect,
2661                             ).emit();
2662                         },
2663                     );
2664                 }
2665             }
2666         }
2667     }
2668 }
2669
2670 struct IterFunction {
2671     func: IterFunctionKind,
2672     span: Span,
2673 }
2674 impl IterFunction {
2675     fn get_iter_method(&self, cx: &LateContext<'_>) -> String {
2676         match &self.func {
2677             IterFunctionKind::IntoIter => String::new(),
2678             IterFunctionKind::Len => String::from(".count()"),
2679             IterFunctionKind::IsEmpty => String::from(".next().is_none()"),
2680             IterFunctionKind::Contains(span) => format!(".any(|x| x == {})", snippet(cx, *span, "..")),
2681         }
2682     }
2683     fn get_suggestion_text(&self) -> &'static str {
2684         match &self.func {
2685             IterFunctionKind::IntoIter => {
2686                 "Use the original Iterator instead of collecting it and then producing a new one"
2687             },
2688             IterFunctionKind::Len => {
2689                 "Take the original Iterator's count instead of collecting it and finding the length"
2690             },
2691             IterFunctionKind::IsEmpty => {
2692                 "Check if the original Iterator has anything instead of collecting it and seeing if it's empty"
2693             },
2694             IterFunctionKind::Contains(_) => {
2695                 "Check if the original Iterator contains an element instead of collecting then checking"
2696             },
2697         }
2698     }
2699 }
2700 enum IterFunctionKind {
2701     IntoIter,
2702     Len,
2703     IsEmpty,
2704     Contains(Span),
2705 }
2706
2707 struct IterFunctionVisitor {
2708     uses: Vec<IterFunction>,
2709     seen_other: bool,
2710     target: Ident,
2711 }
2712 impl<'tcx> Visitor<'tcx> for IterFunctionVisitor {
2713     fn visit_expr(&mut self, expr: &'tcx Expr<'tcx>) {
2714         // Check function calls on our collection
2715         if_chain! {
2716             if let ExprKind::MethodCall(method_name, _, ref args, _) = &expr.kind;
2717             if let Some(Expr { kind: ExprKind::Path(QPath::Resolved(_, ref path)), .. }) = args.get(0);
2718             if let &[name] = &path.segments;
2719             if name.ident == self.target;
2720             then {
2721                 let len = sym!(len);
2722                 let is_empty = sym!(is_empty);
2723                 let contains = sym!(contains);
2724                 match method_name.ident.name {
2725                     sym::into_iter => self.uses.push(
2726                         IterFunction { func: IterFunctionKind::IntoIter, span: expr.span }
2727                     ),
2728                     name if name == len => self.uses.push(
2729                         IterFunction { func: IterFunctionKind::Len, span: expr.span }
2730                     ),
2731                     name if name == is_empty => self.uses.push(
2732                         IterFunction { func: IterFunctionKind::IsEmpty, span: expr.span }
2733                     ),
2734                     name if name == contains => self.uses.push(
2735                         IterFunction { func: IterFunctionKind::Contains(args[1].span), span: expr.span }
2736                     ),
2737                     _ => self.seen_other = true,
2738                 }
2739                 return
2740             }
2741         }
2742         // Check if the collection is used for anything else
2743         if_chain! {
2744             if let Expr { kind: ExprKind::Path(QPath::Resolved(_, ref path)), .. } = expr;
2745             if let &[name] = &path.segments;
2746             if name.ident == self.target;
2747             then {
2748                 self.seen_other = true;
2749             } else {
2750                 walk_expr(self, expr);
2751             }
2752         }
2753     }
2754
2755     type Map = Map<'tcx>;
2756     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
2757         NestedVisitorMap::None
2758     }
2759 }
2760
2761 /// Detect the occurences of calls to `iter` or `into_iter` for the
2762 /// given identifier
2763 fn detect_iter_and_into_iters<'tcx>(block: &'tcx Block<'tcx>, identifier: Ident) -> Option<Vec<IterFunction>> {
2764     let mut visitor = IterFunctionVisitor {
2765         uses: Vec::new(),
2766         target: identifier,
2767         seen_other: false,
2768     };
2769     visitor.visit_block(block);
2770     if visitor.seen_other {
2771         None
2772     } else {
2773         Some(visitor.uses)
2774     }
2775 }
2776
2777 fn shorten_needless_collect_span(expr: &Expr<'_>) -> Span {
2778     if_chain! {
2779         if let ExprKind::MethodCall(.., args, _) = &expr.kind;
2780         if let ExprKind::MethodCall(_, span, ..) = &args[0].kind;
2781         then {
2782             return expr.span.with_lo(span.lo());
2783         }
2784     }
2785     unreachable!();
2786 }