1 use itertools::Itertools;
4 use rustc::hir::def::Def;
5 use rustc::hir::intravisit::{walk_block, walk_decl, walk_expr, walk_pat, walk_stmt, NestedVisitorMap, Visitor};
6 use rustc::hir::map::Node::{NodeBlock, NodeExpr, NodeStmt};
8 use rustc::middle::const_val::ConstVal;
9 use rustc::middle::region;
10 use rustc::ty::{self, Ty};
11 use rustc::ty::subst::{Subst, Substs};
12 use rustc_const_eval::ConstContext;
13 use std::collections::{HashMap, HashSet};
16 use utils::const_to_u64;
18 use utils::{get_enclosing_block, get_parent_expr, higher, in_external_macro, is_integer_literal, is_refutable,
19 last_path_segment, match_trait_method, match_type, match_var, multispan_sugg, snippet, snippet_opt,
20 span_help_and_lint, span_lint, span_lint_and_sugg, span_lint_and_then};
23 /// **What it does:** Checks for for-loops that manually copy items between
24 /// slices that could be optimized by having a memcpy.
26 /// **Why is this bad?** It is not as fast as a memcpy.
28 /// **Known problems:** None.
32 /// for i in 0..src.len() {
33 /// dst[i + 64] = src[i];
39 "manually copying items between slices"
42 /// **What it does:** Checks for looping over the range of `0..len` of some
43 /// collection just to get the values by index.
45 /// **Why is this bad?** Just iterating the collection itself makes the intent
46 /// more clear and is probably faster.
48 /// **Known problems:** None.
52 /// for i in 0..vec.len() {
53 /// println!("{}", vec[i]);
57 pub NEEDLESS_RANGE_LOOP,
59 "for-looping over a range of indices where an iterator over items would do"
62 /// **What it does:** Checks for loops on `x.iter()` where `&x` will do, and
63 /// suggests the latter.
65 /// **Why is this bad?** Readability.
67 /// **Known problems:** False negatives. We currently only warn on some known
72 /// // with `y` a `Vec` or slice:
73 /// for x in y.iter() { .. }
76 pub EXPLICIT_ITER_LOOP,
78 "for-looping over `_.iter()` or `_.iter_mut()` when `&_` or `&mut _` would do"
81 /// **What it does:** Checks for loops on `y.into_iter()` where `y` will do, and
82 /// suggests the latter.
84 /// **Why is this bad?** Readability.
86 /// **Known problems:** None
90 /// // with `y` a `Vec` or slice:
91 /// for x in y.into_iter() { .. }
94 pub EXPLICIT_INTO_ITER_LOOP,
96 "for-looping over `_.into_iter()` when `_` would do"
99 /// **What it does:** Checks for loops on `x.next()`.
101 /// **Why is this bad?** `next()` returns either `Some(value)` if there was a
102 /// value, or `None` otherwise. The insidious thing is that `Option<_>`
103 /// implements `IntoIterator`, so that possibly one value will be iterated,
104 /// leading to some hard to find bugs. No one will want to write such code
105 /// [except to win an Underhanded Rust
106 /// Contest](https://www.reddit.
107 /// com/r/rust/comments/3hb0wm/underhanded_rust_contest/cu5yuhr).
109 /// **Known problems:** None.
113 /// for x in y.next() { .. }
118 "for-looping over `_.next()` which is probably not intended"
121 /// **What it does:** Checks for `for` loops over `Option` values.
123 /// **Why is this bad?** Readability. This is more clearly expressed as an `if
126 /// **Known problems:** None.
130 /// for x in option { .. }
135 /// if let Some(x) = option { .. }
138 pub FOR_LOOP_OVER_OPTION,
140 "for-looping over an `Option`, which is more clearly expressed as an `if let`"
143 /// **What it does:** Checks for `for` loops over `Result` values.
145 /// **Why is this bad?** Readability. This is more clearly expressed as an `if
148 /// **Known problems:** None.
152 /// for x in result { .. }
157 /// if let Ok(x) = result { .. }
160 pub FOR_LOOP_OVER_RESULT,
162 "for-looping over a `Result`, which is more clearly expressed as an `if let`"
165 /// **What it does:** Detects `loop + match` combinations that are easier
166 /// written as a `while let` loop.
168 /// **Why is this bad?** The `while let` loop is usually shorter and more
171 /// **Known problems:** Sometimes the wrong binding is displayed (#383).
176 /// let x = match y {
180 /// // .. do something with x
182 /// // is easier written as
183 /// while let Some(x) = y {
184 /// // .. do something with x
190 "`loop { if let { ... } else break }`, which can be written as a `while let` loop"
193 /// **What it does:** Checks for using `collect()` on an iterator without using
196 /// **Why is this bad?** It is more idiomatic to use a `for` loop over the
197 /// iterator instead.
199 /// **Known problems:** None.
203 /// vec.iter().map(|x| /* some operation returning () */).collect::<Vec<_>>();
208 "`collect()`ing an iterator without using the result; this is usually better \
209 written as a for loop"
212 /// **What it does:** Checks for loops over ranges `x..y` where both `x` and `y`
213 /// are constant and `x` is greater or equal to `y`, unless the range is
214 /// reversed or has a negative `.step_by(_)`.
216 /// **Why is it bad?** Such loops will either be skipped or loop until
217 /// wrap-around (in debug code, this may `panic!()`). Both options are probably
220 /// **Known problems:** The lint cannot catch loops over dynamically defined
221 /// ranges. Doing this would require simulating all possible inputs and code
222 /// paths through the program, which would be complex and error-prone.
226 /// for x in 5..10-5 { .. } // oops, stray `-`
229 pub REVERSE_RANGE_LOOP,
231 "iteration over an empty range, such as `10..0` or `5..5`"
234 /// **What it does:** Checks `for` loops over slices with an explicit counter
235 /// and suggests the use of `.enumerate()`.
237 /// **Why is it bad?** Not only is the version using `.enumerate()` more
238 /// readable, the compiler is able to remove bounds checks which can lead to
239 /// faster code in some instances.
241 /// **Known problems:** None.
245 /// for i in 0..v.len() { foo(v[i]);
246 /// for i in 0..v.len() { bar(i, v[i]); }
249 pub EXPLICIT_COUNTER_LOOP,
251 "for-looping with an explicit counter when `_.enumerate()` would do"
254 /// **What it does:** Checks for empty `loop` expressions.
256 /// **Why is this bad?** Those busy loops burn CPU cycles without doing
257 /// anything. Think of the environment and either block on something or at least
258 /// make the thread sleep for some microseconds.
260 /// **Known problems:** None.
269 "empty `loop {}`, which should block or sleep"
272 /// **What it does:** Checks for `while let` expressions on iterators.
274 /// **Why is this bad?** Readability. A simple `for` loop is shorter and conveys
275 /// the intent better.
277 /// **Known problems:** None.
281 /// while let Some(val) = iter() { .. }
284 pub WHILE_LET_ON_ITERATOR,
286 "using a while-let loop instead of a for loop on an iterator"
289 /// **What it does:** Checks for iterating a map (`HashMap` or `BTreeMap`) and
290 /// ignoring either the keys or values.
292 /// **Why is this bad?** Readability. There are `keys` and `values` methods that
293 /// can be used to express that don't need the values or keys.
295 /// **Known problems:** None.
299 /// for (k, _) in &map { .. }
302 /// could be replaced by
305 /// for k in map.keys() { .. }
310 "looping on a map using `iter` when `keys` or `values` would do"
313 /// **What it does:** Checks for loops that will always `break`, `return` or
314 /// `continue` an outer loop.
316 /// **Why is this bad?** This loop never loops, all it does is obfuscating the
319 /// **Known problems:** None
323 /// loop { ..; break; }
328 "any loop that will always `break` or `return`"
331 #[derive(Copy, Clone)]
334 impl LintPass for Pass {
335 fn get_lints(&self) -> LintArray {
340 EXPLICIT_INTO_ITER_LOOP,
342 FOR_LOOP_OVER_RESULT,
343 FOR_LOOP_OVER_OPTION,
347 EXPLICIT_COUNTER_LOOP,
349 WHILE_LET_ON_ITERATOR,
356 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
357 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
358 if let Some((pat, arg, body)) = higher::for_loop(expr) {
359 check_for_loop(cx, pat, arg, body, expr);
362 // check for never_loop
364 ExprWhile(_, ref block, _) |
365 ExprLoop(ref block, _, _) => {
366 if never_loop(block, &expr.id) {
367 span_lint(cx, NEVER_LOOP, expr.span, "this loop never actually loops");
373 // check for `loop { if let {} else break }` that could be `while let`
374 // (also matches an explicit "match" instead of "if let")
375 // (even if the "match" or "if let" is used for declaration)
376 if let ExprLoop(ref block, _, LoopSource::Loop) = expr.node {
377 // also check for empty `loop {}` statements
378 if block.stmts.is_empty() && block.expr.is_none() {
383 "empty `loop {}` detected. You may want to either use `panic!()` or add \
384 `std::thread::sleep(..);` to the loop body.",
388 // extract the expression from the first statement (if any) in a block
389 let inner_stmt_expr = extract_expr_from_first_stmt(block);
390 // or extract the first expression (if any) from the block
391 if let Some(inner) = inner_stmt_expr.or_else(|| extract_first_expr(block)) {
392 if let ExprMatch(ref matchexpr, ref arms, ref source) = inner.node {
393 // ensure "if let" compatible match structure
395 MatchSource::Normal |
396 MatchSource::IfLetDesugar { .. } => {
397 if arms.len() == 2 && arms[0].pats.len() == 1 && arms[0].guard.is_none() &&
398 arms[1].pats.len() == 1 && arms[1].guard.is_none() &&
399 is_simple_break_expr(&arms[1].body)
401 if in_external_macro(cx, expr.span) {
405 // NOTE: we used to make build a body here instead of using
406 // ellipsis, this was removed because:
407 // 1) it was ugly with big bodies;
408 // 2) it was not indented properly;
409 // 3) it wasn’t very smart (see #675).
414 "this loop could be written as a `while let` loop",
417 "while let {} = {} {{ .. }}",
418 snippet(cx, arms[0].pats[0].span, ".."),
419 snippet(cx, matchexpr.span, "..")
429 if let ExprMatch(ref match_expr, ref arms, MatchSource::WhileLetDesugar) = expr.node {
430 let pat = &arms[0].pats[0].node;
431 if let (&PatKind::TupleStruct(ref qpath, ref pat_args, _),
432 &ExprMethodCall(ref method_path, _, ref method_args)) = (pat, &match_expr.node)
434 let iter_expr = &method_args[0];
435 let lhs_constructor = last_path_segment(qpath);
436 if method_path.name == "next" && match_trait_method(cx, match_expr, &paths::ITERATOR) &&
437 lhs_constructor.name == "Some" && !is_refutable(cx, &pat_args[0]) &&
438 !is_iterator_used_after_while_let(cx, iter_expr) &&
439 !is_nested(cx, expr, &method_args[0])
441 let iterator = snippet(cx, method_args[0].span, "_");
442 let loop_var = snippet(cx, pat_args[0].span, "_");
445 WHILE_LET_ON_ITERATOR,
447 "this loop could be written as a `for` loop",
449 format!("for {} in {} {{ .. }}", loop_var, iterator),
456 fn check_stmt(&mut self, cx: &LateContext<'a, 'tcx>, stmt: &'tcx Stmt) {
457 if let StmtSemi(ref expr, _) = stmt.node {
458 if let ExprMethodCall(ref method, _, ref args) = expr.node {
459 if args.len() == 1 && method.name == "collect" && match_trait_method(cx, expr, &paths::ITERATOR) {
464 "you are collect()ing an iterator and throwing away the result. \
465 Consider using an explicit for loop to exhaust the iterator",
473 fn never_loop(block: &Block, id: &NodeId) -> bool {
474 !contains_continue_block(block, id) && loop_exit_block(block)
477 fn contains_continue_block(block: &Block, dest: &NodeId) -> bool {
478 block.stmts.iter().any(|e| contains_continue_stmt(e, dest)) ||
479 block.expr.as_ref().map_or(
481 |e| contains_continue_expr(e, dest),
485 fn contains_continue_stmt(stmt: &Stmt, dest: &NodeId) -> bool {
488 StmtExpr(ref e, _) => contains_continue_expr(e, dest),
489 StmtDecl(ref d, _) => contains_continue_decl(d, dest),
493 fn contains_continue_decl(decl: &Decl, dest: &NodeId) -> bool {
495 DeclLocal(ref local) => {
496 local.init.as_ref().map_or(
498 |e| contains_continue_expr(e, dest),
505 fn contains_continue_expr(expr: &Expr, dest: &NodeId) -> bool {
507 ExprRet(Some(ref e)) |
509 ExprUnary(_, ref e) |
512 ExprField(ref e, _) |
513 ExprTupField(ref e, _) |
514 ExprAddrOf(_, ref e) |
515 ExprRepeat(ref e, _) => contains_continue_expr(e, dest),
517 ExprMethodCall(_, _, ref es) |
518 ExprTup(ref es) => es.iter().any(|e| contains_continue_expr(e, dest)),
519 ExprCall(ref e, ref es) => {
520 contains_continue_expr(e, dest) || es.iter().any(|e| contains_continue_expr(e, dest))
522 ExprBinary(_, ref e1, ref e2) |
523 ExprAssign(ref e1, ref e2) |
524 ExprAssignOp(_, ref e1, ref e2) |
525 ExprIndex(ref e1, ref e2) => [e1, e2].iter().any(|e| contains_continue_expr(e, dest)),
526 ExprIf(ref e, ref e2, ref e3) => {
527 [e, e2].iter().chain(e3.as_ref().iter()).any(|e| {
528 contains_continue_expr(e, dest)
531 ExprWhile(ref e, ref b, _) => contains_continue_expr(e, dest) || contains_continue_block(b, dest),
532 ExprMatch(ref e, ref arms, _) => {
533 contains_continue_expr(e, dest) || arms.iter().any(|a| contains_continue_expr(&a.body, dest))
535 ExprBlock(ref block) |
536 ExprLoop(ref block, ..) => contains_continue_block(block, dest),
537 ExprStruct(_, _, ref base) => {
538 base.as_ref().map_or(
540 |e| contains_continue_expr(e, dest),
543 ExprAgain(d) => d.target_id.opt_id().map_or(false, |id| id == *dest),
548 fn loop_exit_block(block: &Block) -> bool {
549 block.stmts.iter().any(|e| loop_exit_stmt(e)) || block.expr.as_ref().map_or(false, |e| loop_exit_expr(e))
552 fn loop_exit_stmt(stmt: &Stmt) -> bool {
555 StmtExpr(ref e, _) => loop_exit_expr(e),
556 StmtDecl(ref d, _) => loop_exit_decl(d),
560 fn loop_exit_decl(decl: &Decl) -> bool {
562 DeclLocal(ref local) => local.init.as_ref().map_or(false, |e| loop_exit_expr(e)),
567 fn loop_exit_expr(expr: &Expr) -> bool {
570 ExprUnary(_, ref e) |
573 ExprField(ref e, _) |
574 ExprTupField(ref e, _) |
575 ExprAddrOf(_, ref e) |
576 ExprRepeat(ref e, _) => loop_exit_expr(e),
578 ExprMethodCall(_, _, ref es) |
579 ExprTup(ref es) => es.iter().any(|e| loop_exit_expr(e)),
580 ExprCall(ref e, ref es) => loop_exit_expr(e) || es.iter().any(|e| loop_exit_expr(e)),
581 ExprBinary(_, ref e1, ref e2) |
582 ExprAssign(ref e1, ref e2) |
583 ExprAssignOp(_, ref e1, ref e2) |
584 ExprIndex(ref e1, ref e2) => [e1, e2].iter().any(|e| loop_exit_expr(e)),
585 ExprIf(ref e, ref e2, ref e3) => {
586 loop_exit_expr(e) || e3.as_ref().map_or(false, |e| loop_exit_expr(e)) && loop_exit_expr(e2)
588 ExprWhile(ref e, ref b, _) => loop_exit_expr(e) || loop_exit_block(b),
589 ExprMatch(ref e, ref arms, _) => loop_exit_expr(e) || arms.iter().all(|a| loop_exit_expr(&a.body)),
590 ExprBlock(ref b) => loop_exit_block(b),
591 ExprBreak(_, _) | ExprAgain(_) | ExprRet(_) => true,
596 fn check_for_loop<'a, 'tcx>(
597 cx: &LateContext<'a, 'tcx>,
603 check_for_loop_range(cx, pat, arg, body, expr);
604 check_for_loop_reverse_range(cx, arg, expr);
605 check_for_loop_arg(cx, pat, arg, expr);
606 check_for_loop_explicit_counter(cx, arg, body, expr);
607 check_for_loop_over_map_kv(cx, pat, arg, body, expr);
608 detect_manual_memcpy(cx, pat, arg, body, expr);
611 fn same_var<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &Expr, var: ast::NodeId) -> bool {
613 let ExprPath(ref qpath) = expr.node,
614 let QPath::Resolved(None, ref path) = *qpath,
615 path.segments.len() == 1,
616 let Def::Local(local_id) = cx.tables.qpath_def(qpath, expr.hir_id),
632 fn negative(s: String) -> Self {
639 fn positive(s: String) -> Self {
647 struct FixedOffsetVar {
652 fn is_slice_like<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, ty: Ty) -> bool {
653 let is_slice = match ty.sty {
654 ty::TyRef(_, ref subty) => is_slice_like(cx, subty.ty),
655 ty::TySlice(..) | ty::TyArray(..) => true,
659 is_slice || match_type(cx, ty, &paths::VEC) || match_type(cx, ty, &paths::VEC_DEQUE)
662 fn get_fixed_offset_var<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &Expr, var: ast::NodeId) -> Option<FixedOffsetVar> {
663 fn extract_offset<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, e: &Expr, var: ast::NodeId) -> Option<String> {
667 ast::LitKind::Int(x, _ty) => Some(x.to_string()),
671 ExprPath(..) if !same_var(cx, e, var) => Some(snippet_opt(cx, e.span).unwrap_or_else(|| "??".into())),
676 if let ExprIndex(ref seqexpr, ref idx) = expr.node {
677 let ty = cx.tables.expr_ty(seqexpr);
678 if !is_slice_like(cx, ty) {
682 let offset = match idx.node {
683 ExprBinary(op, ref lhs, ref rhs) => {
686 let offset_opt = if same_var(cx, lhs, var) {
687 extract_offset(cx, rhs, var)
688 } else if same_var(cx, rhs, var) {
689 extract_offset(cx, lhs, var)
694 offset_opt.map(Offset::positive)
696 BinOp_::BiSub if same_var(cx, lhs, var) => extract_offset(cx, rhs, var).map(Offset::negative),
701 if same_var(cx, idx, var) {
702 Some(Offset::positive("0".into()))
712 var_name: snippet_opt(cx, seqexpr.span).unwrap_or_else(|| "???".into()),
721 fn fetch_cloned_fixed_offset_var<'a, 'tcx>(
722 cx: &LateContext<'a, 'tcx>,
725 ) -> Option<FixedOffsetVar> {
727 let ExprMethodCall(ref method, _, ref args) = expr.node,
728 method.name == "clone",
730 let Some(arg) = args.get(0),
732 return get_fixed_offset_var(cx, arg, var);
735 get_fixed_offset_var(cx, expr, var)
738 fn get_indexed_assignments<'a, 'tcx>(
739 cx: &LateContext<'a, 'tcx>,
742 ) -> Vec<(FixedOffsetVar, FixedOffsetVar)> {
743 fn get_assignment<'a, 'tcx>(
744 cx: &LateContext<'a, 'tcx>,
747 ) -> Option<(FixedOffsetVar, FixedOffsetVar)> {
748 if let Expr_::ExprAssign(ref lhs, ref rhs) = e.node {
749 match (get_fixed_offset_var(cx, lhs, var), fetch_cloned_fixed_offset_var(cx, rhs, var)) {
750 (Some(offset_left), Some(offset_right)) => Some((offset_left, offset_right)),
758 if let Expr_::ExprBlock(ref b) = body.node {
767 .map(|stmt| match stmt.node {
768 Stmt_::StmtDecl(..) => None,
769 Stmt_::StmtExpr(ref e, _node_id) |
770 Stmt_::StmtSemi(ref e, _node_id) => Some(get_assignment(cx, e, var)),
772 .chain(expr.as_ref().into_iter().map(|e| {
773 Some(get_assignment(cx, &*e, var))
776 .collect::<Option<Vec<_>>>()
777 .unwrap_or_else(|| vec![])
779 get_assignment(cx, body, var).into_iter().collect()
783 /// Check for for loops that sequentially copy items from one slice-like
784 /// object to another.
785 fn detect_manual_memcpy<'a, 'tcx>(
786 cx: &LateContext<'a, 'tcx>,
792 if let Some(higher::Range {
796 }) = higher::range(arg)
798 // the var must be a single name
799 if let PatKind::Binding(_, canonical_id, _, _) = pat.node {
800 let print_sum = |arg1: &Offset, arg2: &Offset| -> String {
801 match (&arg1.value[..], arg1.negate, &arg2.value[..], arg2.negate) {
802 ("0", _, "0", _) => "".into(),
804 (x, false, "0", false) => x.into(),
806 (x, false, "0", true) => format!("-{}", x),
807 (x, false, y, false) => format!("({} + {})", x, y),
808 (x, false, y, true) => format!("({} - {})", x, y),
809 (x, true, y, false) => format!("({} - {})", y, x),
810 (x, true, y, true) => format!("-({} + {})", x, y),
814 let print_limit = |end: &Option<&Expr>, offset: Offset, var_name: &str| if let Some(end) = *end {
816 let ExprMethodCall(ref method, _, ref len_args) = end.node,
817 method.name == "len",
819 let Some(arg) = len_args.get(0),
820 snippet(cx, arg.span, "??") == var_name,
822 return if offset.negate {
823 format!("({} - {})", snippet(cx, end.span, "<src>.len()"), offset.value)
829 let end_str = match limits {
830 ast::RangeLimits::Closed => {
831 let end = sugg::Sugg::hir(cx, end, "<count>");
832 format!("{}", end + sugg::ONE)
834 ast::RangeLimits::HalfOpen => format!("{}", snippet(cx, end.span, "..")),
837 print_sum(&Offset::positive(end_str), &offset)
842 // The only statements in the for loops can be indexed assignments from
843 // indexed retrievals.
844 let manual_copies = get_indexed_assignments(cx, body, canonical_id);
846 let big_sugg = manual_copies
848 .map(|(dst_var, src_var)| {
849 let start_str = Offset::positive(snippet_opt(cx, start.span).unwrap_or_else(|| "".into()));
850 let dst_offset = print_sum(&start_str, &dst_var.offset);
851 let dst_limit = print_limit(end, dst_var.offset, &dst_var.var_name);
852 let src_offset = print_sum(&start_str, &src_var.offset);
853 let src_limit = print_limit(end, src_var.offset, &src_var.var_name);
854 let dst = if dst_offset == "" && dst_limit == "" {
857 format!("{}[{}..{}]", dst_var.var_name, dst_offset, dst_limit)
860 format!("{}.clone_from_slice(&{}[{}..{}])", dst, src_var.var_name, src_offset, src_limit)
864 if !big_sugg.is_empty() {
869 "it looks like you're manually copying between slices",
870 "try replacing the loop by",
878 /// Check for looping over a range and then indexing a sequence with it.
879 /// The iteratee must be a range literal.
880 fn check_for_loop_range<'a, 'tcx>(
881 cx: &LateContext<'a, 'tcx>,
887 if let Some(higher::Range {
891 }) = higher::range(arg)
893 // the var must be a single name
894 if let PatKind::Binding(_, canonical_id, ref ident, _) = pat.node {
895 let mut visitor = VarVisitor {
898 indexed: HashMap::new(),
899 referenced: HashSet::new(),
902 walk_expr(&mut visitor, body);
904 // linting condition: we only indexed one variable
905 if visitor.indexed.len() == 1 {
906 let (indexed, indexed_extent) = visitor.indexed.into_iter().next().expect(
907 "already checked that we have exactly 1 element",
910 // ensure that the indexed variable was declared before the loop, see #601
911 if let Some(indexed_extent) = indexed_extent {
912 let parent_id = cx.tcx.hir.get_parent(expr.id);
913 let parent_def_id = cx.tcx.hir.local_def_id(parent_id);
914 let region_scope_tree = cx.tcx.region_scope_tree(parent_def_id);
915 let pat_extent = region_scope_tree.var_scope(pat.hir_id.local_id);
916 if region_scope_tree.is_subscope_of(indexed_extent, pat_extent) {
921 // don't lint if the container that is indexed into is also used without
923 if visitor.referenced.contains(&indexed) {
927 let starts_at_zero = is_integer_literal(start, 0);
929 let skip = if starts_at_zero {
932 format!(".skip({})", snippet(cx, start.span, ".."))
935 let take = if let Some(end) = *end {
936 if is_len_call(end, &indexed) {
940 ast::RangeLimits::Closed => {
941 let end = sugg::Sugg::hir(cx, end, "<count>");
942 format!(".take({})", end + sugg::ONE)
944 ast::RangeLimits::HalfOpen => format!(".take({})", snippet(cx, end.span, "..")),
951 if visitor.nonindex {
956 &format!("the loop variable `{}` is used to index `{}`", ident.node, indexed),
960 "consider using an iterator".to_string(),
962 (pat.span, format!("({}, <item>)", ident.node)),
963 (arg.span, format!("{}.iter().enumerate(){}{}", indexed, take, skip)),
969 let repl = if starts_at_zero && take.is_empty() {
970 format!("&{}", indexed)
972 format!("{}.iter(){}{}", indexed, take, skip)
979 &format!("the loop variable `{}` is only used to index `{}`.", ident.node, indexed),
983 "consider using an iterator".to_string(),
984 vec![(pat.span, "<item>".to_string()), (arg.span, repl)],
994 fn is_len_call(expr: &Expr, var: &Name) -> bool {
996 let ExprMethodCall(ref method, _, ref len_args) = expr.node,
998 method.name == "len",
999 let ExprPath(QPath::Resolved(_, ref path)) = len_args[0].node,
1000 path.segments.len() == 1,
1001 path.segments[0].name == *var
1009 fn check_for_loop_reverse_range<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, arg: &'tcx Expr, expr: &'tcx Expr) {
1010 // if this for loop is iterating over a two-sided range...
1011 if let Some(higher::Range {
1015 }) = higher::range(arg)
1017 // ...and both sides are compile-time constant integers...
1018 let parent_item = cx.tcx.hir.get_parent(arg.id);
1019 let parent_def_id = cx.tcx.hir.local_def_id(parent_item);
1020 let substs = Substs::identity_for_item(cx.tcx, parent_def_id);
1021 let constcx = ConstContext::new(cx.tcx, cx.param_env.and(substs), cx.tables);
1022 if let Ok(start_idx) = constcx.eval(start) {
1023 if let Ok(end_idx) = constcx.eval(end) {
1024 // ...and the start index is greater than the end index,
1025 // this loop will never run. This is often confusing for developers
1026 // who think that this will iterate from the larger value to the
1028 let (sup, eq) = match (start_idx, end_idx) {
1029 (&ty::Const { val: ConstVal::Integral(start_idx), .. },
1030 &ty::Const { val: ConstVal::Integral(end_idx), .. }) => {
1031 (start_idx > end_idx, start_idx == end_idx)
1033 _ => (false, false),
1037 let start_snippet = snippet(cx, start.span, "_");
1038 let end_snippet = snippet(cx, end.span, "_");
1039 let dots = if limits == ast::RangeLimits::Closed {
1049 "this range is empty so this for loop will never run",
1053 "consider using the following if you are attempting to iterate over this \
1056 "({end}{dots}{start}).rev()",
1059 start = start_snippet
1064 } else if eq && limits != ast::RangeLimits::Closed {
1065 // if they are equal, it's also problematic - this loop
1071 "this range is empty so this for loop will never run",
1079 fn lint_iter_method(cx: &LateContext, args: &[Expr], arg: &Expr, method_name: &str) {
1080 let object = snippet(cx, args[0].span, "_");
1081 let muta = if method_name == "iter_mut" {
1090 "it is more idiomatic to loop over references to containers instead of using explicit \
1092 "to write this more concisely, try",
1093 format!("&{}{}", muta, object),
1097 fn check_for_loop_arg(cx: &LateContext, pat: &Pat, arg: &Expr, expr: &Expr) {
1098 let mut next_loop_linted = false; // whether or not ITER_NEXT_LOOP lint was used
1099 if let ExprMethodCall(ref method, _, ref args) = arg.node {
1100 // just the receiver, no arguments
1101 if args.len() == 1 {
1102 let method_name = &*method.name.as_str();
1103 // check for looping over x.iter() or x.iter_mut(), could use &x or &mut x
1104 if method_name == "iter" || method_name == "iter_mut" {
1105 if is_ref_iterable_type(cx, &args[0]) {
1106 lint_iter_method(cx, args, arg, method_name);
1108 } else if method_name == "into_iter" && match_trait_method(cx, arg, &paths::INTO_ITERATOR) {
1109 let def_id = cx.tables.type_dependent_defs()[arg.hir_id].def_id();
1110 let substs = cx.tables.node_substs(arg.hir_id);
1111 let method_type = cx.tcx.type_of(def_id).subst(cx.tcx, substs);
1113 let fn_arg_tys = method_type.fn_sig(cx.tcx).inputs();
1114 assert_eq!(fn_arg_tys.skip_binder().len(), 1);
1115 if fn_arg_tys.skip_binder()[0].is_region_ptr() {
1116 lint_iter_method(cx, args, arg, method_name);
1118 let object = snippet(cx, args[0].span, "_");
1121 EXPLICIT_INTO_ITER_LOOP,
1123 "it is more idiomatic to loop over containers instead of using explicit \
1124 iteration methods`",
1125 "to write this more concisely, try",
1129 } else if method_name == "next" && match_trait_method(cx, arg, &paths::ITERATOR) {
1134 "you are iterating over `Iterator::next()` which is an Option; this will compile but is \
1135 probably not what you want",
1137 next_loop_linted = true;
1141 if !next_loop_linted {
1142 check_arg_type(cx, pat, arg);
1146 /// Check for `for` loops over `Option`s and `Results`
1147 fn check_arg_type(cx: &LateContext, pat: &Pat, arg: &Expr) {
1148 let ty = cx.tables.expr_ty(arg);
1149 if match_type(cx, ty, &paths::OPTION) {
1152 FOR_LOOP_OVER_OPTION,
1155 "for loop over `{0}`, which is an `Option`. This is more readably written as an \
1156 `if let` statement.",
1157 snippet(cx, arg.span, "_")
1160 "consider replacing `for {0} in {1}` with `if let Some({0}) = {1}`",
1161 snippet(cx, pat.span, "_"),
1162 snippet(cx, arg.span, "_")
1165 } else if match_type(cx, ty, &paths::RESULT) {
1168 FOR_LOOP_OVER_RESULT,
1171 "for loop over `{0}`, which is a `Result`. This is more readably written as an \
1172 `if let` statement.",
1173 snippet(cx, arg.span, "_")
1176 "consider replacing `for {0} in {1}` with `if let Ok({0}) = {1}`",
1177 snippet(cx, pat.span, "_"),
1178 snippet(cx, arg.span, "_")
1184 fn check_for_loop_explicit_counter<'a, 'tcx>(
1185 cx: &LateContext<'a, 'tcx>,
1190 // Look for variables that are incremented once per loop iteration.
1191 let mut visitor = IncrementVisitor {
1193 states: HashMap::new(),
1197 walk_expr(&mut visitor, body);
1199 // For each candidate, check the parent block to see if
1200 // it's initialized to zero at the start of the loop.
1201 let map = &cx.tcx.hir;
1202 let parent_scope = map.get_enclosing_scope(expr.id).and_then(|id| {
1203 map.get_enclosing_scope(id)
1205 if let Some(parent_id) = parent_scope {
1206 if let NodeBlock(block) = map.get(parent_id) {
1207 for (id, _) in visitor.states.iter().filter(
1208 |&(_, v)| *v == VarState::IncrOnce,
1211 let mut visitor2 = InitializeVisitor {
1215 state: VarState::IncrOnce,
1220 walk_block(&mut visitor2, block);
1222 if visitor2.state == VarState::Warn {
1223 if let Some(name) = visitor2.name {
1226 EXPLICIT_COUNTER_LOOP,
1229 "the variable `{0}` is used as a loop counter. Consider using `for ({0}, \
1230 item) in {1}.enumerate()` or similar iterators",
1232 snippet(cx, arg.span, "_")
1242 /// Check for the `FOR_KV_MAP` lint.
1243 fn check_for_loop_over_map_kv<'a, 'tcx>(
1244 cx: &LateContext<'a, 'tcx>,
1250 let pat_span = pat.span;
1252 if let PatKind::Tuple(ref pat, _) = pat.node {
1254 let arg_span = arg.span;
1255 let (new_pat_span, kind, ty, mutbl) = match cx.tables.expr_ty(arg).sty {
1256 ty::TyRef(_, ref tam) => {
1257 match (&pat[0].node, &pat[1].node) {
1258 (key, _) if pat_is_wild(key, body) => (pat[1].span, "value", tam.ty, tam.mutbl),
1259 (_, value) if pat_is_wild(value, body) => (pat[0].span, "key", tam.ty, MutImmutable),
1265 let mutbl = match mutbl {
1267 MutMutable => "_mut",
1269 let arg = match arg.node {
1270 ExprAddrOf(_, ref expr) => &**expr,
1274 if match_type(cx, ty, &paths::HASHMAP) || match_type(cx, ty, &paths::BTREEMAP) {
1279 &format!("you seem to want to iterate on a map's {}s", kind),
1281 let map = sugg::Sugg::hir(cx, arg, "map");
1284 "use the corresponding method".into(),
1286 (pat_span, snippet(cx, new_pat_span, kind).into_owned()),
1287 (arg_span, format!("{}.{}s{}()", map.maybe_par(), kind, mutbl)),
1297 /// Return true if the pattern is a `PatWild` or an ident prefixed with `'_'`.
1298 fn pat_is_wild<'tcx>(pat: &'tcx PatKind, body: &'tcx Expr) -> bool {
1300 PatKind::Wild => true,
1301 PatKind::Binding(_, _, ident, None) if ident.node.as_str().starts_with('_') => {
1302 let mut visitor = UsedVisitor {
1306 walk_expr(&mut visitor, body);
1313 struct UsedVisitor {
1314 var: ast::Name, // var to look for
1315 used: bool, // has the var been used otherwise?
1318 impl<'tcx> Visitor<'tcx> for UsedVisitor {
1319 fn visit_expr(&mut self, expr: &'tcx Expr) {
1320 if match_var(expr, self.var) {
1323 walk_expr(self, expr);
1327 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1328 NestedVisitorMap::None
1332 struct LocalUsedVisitor<'a, 'tcx: 'a> {
1333 cx: &'a LateContext<'a, 'tcx>,
1338 impl<'a, 'tcx: 'a> Visitor<'tcx> for LocalUsedVisitor<'a, 'tcx> {
1339 fn visit_expr(&mut self, expr: &'tcx Expr) {
1340 if same_var(self.cx, expr, self.local) {
1343 walk_expr(self, expr);
1347 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1348 NestedVisitorMap::None
1352 struct VarVisitor<'a, 'tcx: 'a> {
1353 /// context reference
1354 cx: &'a LateContext<'a, 'tcx>,
1355 /// var name to look for as index
1357 /// indexed variables, the extend is `None` for global
1358 indexed: HashMap<Name, Option<region::Scope>>,
1359 /// Any names that are used outside an index operation.
1360 /// Used to detect things like `&mut vec` used together with `vec[i]`
1361 referenced: HashSet<Name>,
1362 /// has the loop variable been used in expressions other than the index of
1367 impl<'a, 'tcx> Visitor<'tcx> for VarVisitor<'a, 'tcx> {
1368 fn visit_expr(&mut self, expr: &'tcx Expr) {
1371 let ExprIndex(ref seqexpr, ref idx) = expr.node,
1372 // the indexed container is referenced by a name
1373 let ExprPath(ref seqpath) = seqexpr.node,
1374 let QPath::Resolved(None, ref seqvar) = *seqpath,
1375 seqvar.segments.len() == 1,
1377 let index_used = same_var(self.cx, idx, self.var) || {
1378 let mut used_visitor = LocalUsedVisitor {
1383 walk_expr(&mut used_visitor, idx);
1388 let def = self.cx.tables.qpath_def(seqpath, seqexpr.hir_id);
1390 Def::Local(node_id) | Def::Upvar(node_id, ..) => {
1391 let hir_id = self.cx.tcx.hir.node_to_hir_id(node_id);
1393 let parent_id = self.cx.tcx.hir.get_parent(expr.id);
1394 let parent_def_id = self.cx.tcx.hir.local_def_id(parent_id);
1395 let extent = self.cx.tcx.region_scope_tree(parent_def_id).var_scope(hir_id.local_id);
1396 self.indexed.insert(seqvar.segments[0].name, Some(extent));
1397 return; // no need to walk further *on the variable*
1399 Def::Static(..) | Def::Const(..) => {
1400 self.indexed.insert(seqvar.segments[0].name, None);
1401 return; // no need to walk further *on the variable*
1409 // directly using a variable
1410 let ExprPath(ref qpath) = expr.node,
1411 let QPath::Resolved(None, ref path) = *qpath,
1412 path.segments.len() == 1,
1413 let Def::Local(local_id) = self.cx.tables.qpath_def(qpath, expr.hir_id),
1415 if local_id == self.var {
1416 // we are not indexing anything, record that
1417 self.nonindex = true;
1419 // not the correct variable, but still a variable
1420 self.referenced.insert(path.segments[0].name);
1424 walk_expr(self, expr);
1426 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1427 NestedVisitorMap::None
1431 fn is_iterator_used_after_while_let<'a, 'tcx: 'a>(cx: &LateContext<'a, 'tcx>, iter_expr: &'tcx Expr) -> bool {
1432 let def_id = match var_def_id(cx, iter_expr) {
1434 None => return false,
1436 let mut visitor = VarUsedAfterLoopVisitor {
1439 iter_expr_id: iter_expr.id,
1440 past_while_let: false,
1441 var_used_after_while_let: false,
1443 if let Some(enclosing_block) = get_enclosing_block(cx, def_id) {
1444 walk_block(&mut visitor, enclosing_block);
1446 visitor.var_used_after_while_let
1449 struct VarUsedAfterLoopVisitor<'a, 'tcx: 'a> {
1450 cx: &'a LateContext<'a, 'tcx>,
1452 iter_expr_id: NodeId,
1453 past_while_let: bool,
1454 var_used_after_while_let: bool,
1457 impl<'a, 'tcx> Visitor<'tcx> for VarUsedAfterLoopVisitor<'a, 'tcx> {
1458 fn visit_expr(&mut self, expr: &'tcx Expr) {
1459 if self.past_while_let {
1460 if Some(self.def_id) == var_def_id(self.cx, expr) {
1461 self.var_used_after_while_let = true;
1463 } else if self.iter_expr_id == expr.id {
1464 self.past_while_let = true;
1466 walk_expr(self, expr);
1468 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1469 NestedVisitorMap::None
1474 /// Return true if the type of expr is one that provides `IntoIterator` impls
1475 /// for `&T` and `&mut T`, such as `Vec`.
1476 #[cfg_attr(rustfmt, rustfmt_skip)]
1477 fn is_ref_iterable_type(cx: &LateContext, e: &Expr) -> bool {
1478 // no walk_ptrs_ty: calling iter() on a reference can make sense because it
1479 // will allow further borrows afterwards
1480 let ty = cx.tables.expr_ty(e);
1481 is_iterable_array(ty) ||
1482 match_type(cx, ty, &paths::VEC) ||
1483 match_type(cx, ty, &paths::LINKED_LIST) ||
1484 match_type(cx, ty, &paths::HASHMAP) ||
1485 match_type(cx, ty, &paths::HASHSET) ||
1486 match_type(cx, ty, &paths::VEC_DEQUE) ||
1487 match_type(cx, ty, &paths::BINARY_HEAP) ||
1488 match_type(cx, ty, &paths::BTREEMAP) ||
1489 match_type(cx, ty, &paths::BTREESET)
1492 fn is_iterable_array(ty: Ty) -> bool {
1493 // IntoIterator is currently only implemented for array sizes <= 32 in rustc
1495 ty::TyArray(_, n) => (0...32).contains(const_to_u64(n)),
1500 /// If a block begins with a statement (possibly a `let` binding) and has an
1501 /// expression, return it.
1502 fn extract_expr_from_first_stmt(block: &Block) -> Option<&Expr> {
1503 if block.stmts.is_empty() {
1506 if let StmtDecl(ref decl, _) = block.stmts[0].node {
1507 if let DeclLocal(ref local) = decl.node {
1508 if let Some(ref expr) = local.init {
1521 /// If a block begins with an expression (with or without semicolon), return it.
1522 fn extract_first_expr(block: &Block) -> Option<&Expr> {
1524 Some(ref expr) if block.stmts.is_empty() => Some(expr),
1525 None if !block.stmts.is_empty() => {
1526 match block.stmts[0].node {
1527 StmtExpr(ref expr, _) |
1528 StmtSemi(ref expr, _) => Some(expr),
1529 StmtDecl(..) => None,
1536 /// Return true if expr contains a single break expr without destination label
1538 /// passed expression. The expression may be within a block.
1539 fn is_simple_break_expr(expr: &Expr) -> bool {
1541 ExprBreak(dest, ref passed_expr) if dest.ident.is_none() && passed_expr.is_none() => true,
1542 ExprBlock(ref b) => {
1543 match extract_first_expr(b) {
1544 Some(subexpr) => is_simple_break_expr(subexpr),
1552 // To trigger the EXPLICIT_COUNTER_LOOP lint, a variable must be
1553 // incremented exactly once in the loop body, and initialized to zero
1554 // at the start of the loop.
1555 #[derive(PartialEq)]
1557 Initial, // Not examined yet
1558 IncrOnce, // Incremented exactly once, may be a loop counter
1559 Declared, // Declared but not (yet) initialized to zero
1564 /// Scan a for loop for variables that are incremented exactly once.
1565 struct IncrementVisitor<'a, 'tcx: 'a> {
1566 cx: &'a LateContext<'a, 'tcx>, // context reference
1567 states: HashMap<NodeId, VarState>, // incremented variables
1568 depth: u32, // depth of conditional expressions
1572 impl<'a, 'tcx> Visitor<'tcx> for IncrementVisitor<'a, 'tcx> {
1573 fn visit_expr(&mut self, expr: &'tcx Expr) {
1578 // If node is a variable
1579 if let Some(def_id) = var_def_id(self.cx, expr) {
1580 if let Some(parent) = get_parent_expr(self.cx, expr) {
1581 let state = self.states.entry(def_id).or_insert(VarState::Initial);
1584 ExprAssignOp(op, ref lhs, ref rhs) => {
1585 if lhs.id == expr.id {
1586 if op.node == BiAdd && is_integer_literal(rhs, 1) {
1587 *state = match *state {
1588 VarState::Initial if self.depth == 0 => VarState::IncrOnce,
1589 _ => VarState::DontWarn,
1592 // Assigned some other value
1593 *state = VarState::DontWarn;
1597 ExprAssign(ref lhs, _) if lhs.id == expr.id => *state = VarState::DontWarn,
1598 ExprAddrOf(mutability, _) if mutability == MutMutable => *state = VarState::DontWarn,
1602 } else if is_loop(expr) {
1603 self.states.clear();
1606 } else if is_conditional(expr) {
1608 walk_expr(self, expr);
1612 walk_expr(self, expr);
1614 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1615 NestedVisitorMap::None
1619 /// Check whether a variable is initialized to zero at the start of a loop.
1620 struct InitializeVisitor<'a, 'tcx: 'a> {
1621 cx: &'a LateContext<'a, 'tcx>, // context reference
1622 end_expr: &'tcx Expr, // the for loop. Stop scanning here.
1626 depth: u32, // depth of conditional expressions
1630 impl<'a, 'tcx> Visitor<'tcx> for InitializeVisitor<'a, 'tcx> {
1631 fn visit_decl(&mut self, decl: &'tcx Decl) {
1632 // Look for declarations of the variable
1633 if let DeclLocal(ref local) = decl.node {
1634 if local.pat.id == self.var_id {
1635 if let PatKind::Binding(_, _, ref ident, _) = local.pat.node {
1636 self.name = Some(ident.node);
1638 self.state = if let Some(ref init) = local.init {
1639 if is_integer_literal(init, 0) {
1650 walk_decl(self, decl);
1653 fn visit_expr(&mut self, expr: &'tcx Expr) {
1654 if self.state == VarState::DontWarn {
1657 if expr == self.end_expr {
1658 self.past_loop = true;
1661 // No need to visit expressions before the variable is
1663 if self.state == VarState::IncrOnce {
1667 // If node is the desired variable, see how it's used
1668 if var_def_id(self.cx, expr) == Some(self.var_id) {
1669 if let Some(parent) = get_parent_expr(self.cx, expr) {
1671 ExprAssignOp(_, ref lhs, _) if lhs.id == expr.id => {
1672 self.state = VarState::DontWarn;
1674 ExprAssign(ref lhs, ref rhs) if lhs.id == expr.id => {
1675 self.state = if is_integer_literal(rhs, 0) && self.depth == 0 {
1681 ExprAddrOf(mutability, _) if mutability == MutMutable => self.state = VarState::DontWarn,
1687 self.state = VarState::DontWarn;
1690 } else if !self.past_loop && is_loop(expr) {
1691 self.state = VarState::DontWarn;
1693 } else if is_conditional(expr) {
1695 walk_expr(self, expr);
1699 walk_expr(self, expr);
1701 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1702 NestedVisitorMap::None
1706 fn var_def_id(cx: &LateContext, expr: &Expr) -> Option<NodeId> {
1707 if let ExprPath(ref qpath) = expr.node {
1708 let path_res = cx.tables.qpath_def(qpath, expr.hir_id);
1709 if let Def::Local(node_id) = path_res {
1710 return Some(node_id);
1716 fn is_loop(expr: &Expr) -> bool {
1718 ExprLoop(..) | ExprWhile(..) => true,
1723 fn is_conditional(expr: &Expr) -> bool {
1725 ExprIf(..) | ExprMatch(..) => true,
1730 fn is_nested(cx: &LateContext, match_expr: &Expr, iter_expr: &Expr) -> bool {
1732 let Some(loop_block) = get_enclosing_block(cx, match_expr.id),
1733 let Some(map::Node::NodeExpr(loop_expr)) = cx.tcx.hir.find(cx.tcx.hir.get_parent_node(loop_block.id)),
1735 return is_loop_nested(cx, loop_expr, iter_expr)
1740 fn is_loop_nested(cx: &LateContext, loop_expr: &Expr, iter_expr: &Expr) -> bool {
1741 let mut id = loop_expr.id;
1742 let iter_name = if let Some(name) = path_name(iter_expr) {
1748 let parent = cx.tcx.hir.get_parent_node(id);
1752 match cx.tcx.hir.find(parent) {
1753 Some(NodeExpr(expr)) => {
1755 ExprLoop(..) | ExprWhile(..) => {
1761 Some(NodeBlock(block)) => {
1762 let mut block_visitor = LoopNestVisitor {
1764 iterator: iter_name,
1767 walk_block(&mut block_visitor, block);
1768 if block_visitor.nesting == RuledOut {
1772 Some(NodeStmt(_)) => (),
1781 #[derive(PartialEq, Eq)]
1783 Unknown, // no nesting detected yet
1784 RuledOut, // the iterator is initialized or assigned within scope
1785 LookFurther, // no nesting detected, no further walk required
1788 use self::Nesting::{LookFurther, RuledOut, Unknown};
1790 struct LoopNestVisitor {
1796 impl<'tcx> Visitor<'tcx> for LoopNestVisitor {
1797 fn visit_stmt(&mut self, stmt: &'tcx Stmt) {
1798 if stmt.node.id() == self.id {
1799 self.nesting = LookFurther;
1800 } else if self.nesting == Unknown {
1801 walk_stmt(self, stmt);
1805 fn visit_expr(&mut self, expr: &'tcx Expr) {
1806 if self.nesting != Unknown {
1809 if expr.id == self.id {
1810 self.nesting = LookFurther;
1814 ExprAssign(ref path, _) |
1815 ExprAssignOp(_, ref path, _) => {
1816 if match_var(path, self.iterator) {
1817 self.nesting = RuledOut;
1820 _ => walk_expr(self, expr),
1824 fn visit_pat(&mut self, pat: &'tcx Pat) {
1825 if self.nesting != Unknown {
1828 if let PatKind::Binding(_, _, span_name, _) = pat.node {
1829 if self.iterator == span_name.node {
1830 self.nesting = RuledOut;
1837 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1838 NestedVisitorMap::None
1842 fn path_name(e: &Expr) -> Option<Name> {
1843 if let ExprPath(QPath::Resolved(_, ref path)) = e.node {
1844 let segments = &path.segments;
1845 if segments.len() == 1 {
1846 return Some(segments[0].name);