1 use itertools::Itertools;
4 use rustc::hir::def::Def;
5 use rustc::hir::def_id::DefId;
6 use rustc::hir::intravisit::{walk_block, walk_decl, walk_expr, walk_pat, walk_stmt, NestedVisitorMap, Visitor};
7 use rustc::hir::map::Node::{NodeBlock, NodeExpr, NodeStmt};
9 use rustc::middle::const_val::ConstVal;
10 use rustc::middle::region;
11 use rustc::ty::{self, Ty};
12 use rustc::ty::subst::{Subst, Substs};
13 use rustc_const_eval::ConstContext;
14 use std::collections::{HashMap, HashSet};
18 use utils::{get_enclosing_block, get_parent_expr, higher, in_external_macro, is_integer_literal, is_refutable,
19 last_path_segment, match_trait_method, match_type, multispan_sugg, snippet, snippet_opt,
20 span_help_and_lint, span_lint, span_lint_and_sugg, span_lint_and_then};
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, _) | ExprLoop(ref block, _, _) => if never_loop(block, &expr.id) {
365 span_lint(cx, NEVER_LOOP, expr.span, "this loop never actually loops");
370 // check for `loop { if let {} else break }` that could be `while let`
371 // (also matches an explicit "match" instead of "if let")
372 // (even if the "match" or "if let" is used for declaration)
373 if let ExprLoop(ref block, _, LoopSource::Loop) = expr.node {
374 // also check for empty `loop {}` statements
375 if block.stmts.is_empty() && block.expr.is_none() {
380 "empty `loop {}` detected. You may want to either use `panic!()` or add \
381 `std::thread::sleep(..);` to the loop body.",
385 // extract the expression from the first statement (if any) in a block
386 let inner_stmt_expr = extract_expr_from_first_stmt(block);
387 // or extract the first expression (if any) from the block
388 if let Some(inner) = inner_stmt_expr.or_else(|| extract_first_expr(block)) {
389 if let ExprMatch(ref matchexpr, ref arms, ref source) = inner.node {
390 // ensure "if let" compatible match structure
392 MatchSource::Normal | MatchSource::IfLetDesugar { .. } => {
393 if arms.len() == 2 && arms[0].pats.len() == 1 && arms[0].guard.is_none() &&
394 arms[1].pats.len() == 1 && arms[1].guard.is_none() &&
395 is_break_expr(&arms[1].body)
397 if in_external_macro(cx, expr.span) {
401 // NOTE: we used to make build a body here instead of using
402 // ellipsis, this was removed because:
403 // 1) it was ugly with big bodies;
404 // 2) it was not indented properly;
405 // 3) it wasn’t very smart (see #675).
410 "this loop could be written as a `while let` loop",
413 "while let {} = {} {{ .. }}",
414 snippet(cx, arms[0].pats[0].span, ".."),
415 snippet(cx, matchexpr.span, "..")
425 if let ExprMatch(ref match_expr, ref arms, MatchSource::WhileLetDesugar) = expr.node {
426 let pat = &arms[0].pats[0].node;
428 &PatKind::TupleStruct(ref qpath, ref pat_args, _),
429 &ExprMethodCall(ref method_path, _, ref method_args),
430 ) = (pat, &match_expr.node)
432 let iter_expr = &method_args[0];
433 let lhs_constructor = last_path_segment(qpath);
434 if method_path.name == "next" && match_trait_method(cx, match_expr, &paths::ITERATOR) &&
435 lhs_constructor.name == "Some" && !is_refutable(cx, &pat_args[0]) &&
436 !is_iterator_used_after_while_let(cx, iter_expr) &&
437 !is_nested(cx, expr, &method_args[0])
439 let iterator = snippet(cx, method_args[0].span, "_");
440 let loop_var = snippet(cx, pat_args[0].span, "_");
443 WHILE_LET_ON_ITERATOR,
445 "this loop could be written as a `for` loop",
447 format!("for {} in {} {{ .. }}", loop_var, iterator),
454 fn check_stmt(&mut self, cx: &LateContext<'a, 'tcx>, stmt: &'tcx Stmt) {
455 if let StmtSemi(ref expr, _) = stmt.node {
456 if let ExprMethodCall(ref method, _, ref args) = expr.node {
457 if args.len() == 1 && method.name == "collect" && match_trait_method(cx, expr, &paths::ITERATOR) {
462 "you are collect()ing an iterator and throwing away the result. \
463 Consider using an explicit for loop to exhaust the iterator",
471 fn never_loop(block: &Block, id: &NodeId) -> bool {
472 !contains_continue_block(block, id) && loop_exit_block(block)
475 fn contains_continue_block(block: &Block, dest: &NodeId) -> bool {
476 block.stmts.iter().any(|e| contains_continue_stmt(e, dest)) ||
480 .map_or(false, |e| contains_continue_expr(e, dest))
483 fn contains_continue_stmt(stmt: &Stmt, dest: &NodeId) -> bool {
485 StmtSemi(ref e, _) | StmtExpr(ref e, _) => contains_continue_expr(e, dest),
486 StmtDecl(ref d, _) => contains_continue_decl(d, dest),
490 fn contains_continue_decl(decl: &Decl, dest: &NodeId) -> bool {
492 DeclLocal(ref local) => local
495 .map_or(false, |e| contains_continue_expr(e, dest)),
500 fn contains_continue_expr(expr: &Expr, dest: &NodeId) -> bool {
502 ExprRet(Some(ref e)) |
504 ExprUnary(_, ref e) |
507 ExprField(ref e, _) |
508 ExprTupField(ref e, _) |
509 ExprAddrOf(_, ref e) |
510 ExprRepeat(ref e, _) => contains_continue_expr(e, dest),
511 ExprArray(ref es) | ExprMethodCall(_, _, ref es) | ExprTup(ref es) => {
512 es.iter().any(|e| contains_continue_expr(e, dest))
514 ExprCall(ref e, ref es) => {
515 contains_continue_expr(e, dest) || es.iter().any(|e| contains_continue_expr(e, dest))
517 ExprBinary(_, ref e1, ref e2) |
518 ExprAssign(ref e1, ref e2) |
519 ExprAssignOp(_, ref e1, ref e2) |
520 ExprIndex(ref e1, ref e2) => [e1, e2].iter().any(|e| contains_continue_expr(e, dest)),
521 ExprIf(ref e, ref e2, ref e3) => [e, e2]
523 .chain(e3.as_ref().iter())
524 .any(|e| contains_continue_expr(e, dest)),
525 ExprWhile(ref e, ref b, _) => contains_continue_expr(e, dest) || contains_continue_block(b, dest),
526 ExprMatch(ref e, ref arms, _) => {
527 contains_continue_expr(e, dest) || arms.iter().any(|a| contains_continue_expr(&a.body, dest))
529 ExprBlock(ref block) => contains_continue_block(block, dest),
530 ExprStruct(_, _, ref base) => base.as_ref()
531 .map_or(false, |e| contains_continue_expr(e, dest)),
532 ExprAgain(d) => d.target_id.opt_id().map_or(false, |id| id == *dest),
537 fn loop_exit_block(block: &Block) -> bool {
538 block.stmts.iter().any(|e| loop_exit_stmt(e)) || block.expr.as_ref().map_or(false, |e| loop_exit_expr(e))
541 fn loop_exit_stmt(stmt: &Stmt) -> bool {
543 StmtSemi(ref e, _) | StmtExpr(ref e, _) => loop_exit_expr(e),
544 StmtDecl(ref d, _) => loop_exit_decl(d),
548 fn loop_exit_decl(decl: &Decl) -> bool {
550 DeclLocal(ref local) => local.init.as_ref().map_or(false, |e| loop_exit_expr(e)),
555 fn loop_exit_expr(expr: &Expr) -> bool {
558 ExprUnary(_, ref e) |
561 ExprField(ref e, _) |
562 ExprTupField(ref e, _) |
563 ExprAddrOf(_, ref e) |
564 ExprRepeat(ref e, _) => loop_exit_expr(e),
565 ExprArray(ref es) | ExprMethodCall(_, _, ref es) | ExprTup(ref es) => es.iter().any(|e| loop_exit_expr(e)),
566 ExprCall(ref e, ref es) => loop_exit_expr(e) || es.iter().any(|e| loop_exit_expr(e)),
567 ExprBinary(_, ref e1, ref e2) |
568 ExprAssign(ref e1, ref e2) |
569 ExprAssignOp(_, ref e1, ref e2) |
570 ExprIndex(ref e1, ref e2) => [e1, e2].iter().any(|e| loop_exit_expr(e)),
571 ExprIf(ref e, ref e2, ref e3) => {
572 loop_exit_expr(e) || e3.as_ref().map_or(false, |e| loop_exit_expr(e)) && loop_exit_expr(e2)
574 ExprWhile(ref e, ref b, _) => loop_exit_expr(e) || loop_exit_block(b),
575 ExprMatch(ref e, ref arms, _) => loop_exit_expr(e) || arms.iter().all(|a| loop_exit_expr(&a.body)),
576 ExprBlock(ref b) => loop_exit_block(b),
577 ExprBreak(_, _) | ExprAgain(_) | ExprRet(_) => true,
582 fn check_for_loop<'a, 'tcx>(
583 cx: &LateContext<'a, 'tcx>,
589 check_for_loop_range(cx, pat, arg, body, expr);
590 check_for_loop_reverse_range(cx, arg, expr);
591 check_for_loop_arg(cx, pat, arg, expr);
592 check_for_loop_explicit_counter(cx, arg, body, expr);
593 check_for_loop_over_map_kv(cx, pat, arg, body, expr);
594 detect_manual_memcpy(cx, pat, arg, body, expr);
597 fn same_var<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &Expr, var: DefId) -> bool {
599 let ExprPath(ref qpath) = expr.node,
600 let QPath::Resolved(None, ref path) = *qpath,
601 path.segments.len() == 1,
603 cx.tables.qpath_def(qpath, expr.hir_id).def_id() == var
617 fn negative(s: String) -> Self {
624 fn positive(s: String) -> Self {
632 struct FixedOffsetVar {
637 fn is_slice_like<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, ty: Ty) -> bool {
638 let is_slice = match ty.sty {
639 ty::TyRef(_, ref subty) => is_slice_like(cx, subty.ty),
640 ty::TySlice(..) | ty::TyArray(..) => true,
644 is_slice || match_type(cx, ty, &paths::VEC) || match_type(cx, ty, &paths::VEC_DEQUE)
647 fn get_fixed_offset_var<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &Expr, var: DefId) -> Option<FixedOffsetVar> {
648 fn extract_offset<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, e: &Expr, var: DefId) -> Option<String> {
650 ExprLit(ref l) => match l.node {
651 ast::LitKind::Int(x, _ty) => Some(x.to_string()),
654 ExprPath(..) if !same_var(cx, e, var) => Some(snippet_opt(cx, e.span).unwrap_or_else(|| "??".into())),
659 if let ExprIndex(ref seqexpr, ref idx) = expr.node {
660 let ty = cx.tables.expr_ty(seqexpr);
661 if !is_slice_like(cx, ty) {
665 let offset = match idx.node {
666 ExprBinary(op, ref lhs, ref rhs) => match op.node {
668 let offset_opt = if same_var(cx, lhs, var) {
669 extract_offset(cx, rhs, var)
670 } else if same_var(cx, rhs, var) {
671 extract_offset(cx, lhs, var)
676 offset_opt.map(Offset::positive)
678 BinOp_::BiSub if same_var(cx, lhs, var) => extract_offset(cx, rhs, var).map(Offset::negative),
681 ExprPath(..) => if same_var(cx, idx, var) {
682 Some(Offset::positive("0".into()))
691 var_name: snippet_opt(cx, seqexpr.span).unwrap_or_else(|| "???".into()),
700 fn get_indexed_assignments<'a, 'tcx>(
701 cx: &LateContext<'a, 'tcx>,
704 ) -> Vec<(FixedOffsetVar, FixedOffsetVar)> {
705 fn get_assignment<'a, 'tcx>(
706 cx: &LateContext<'a, 'tcx>,
709 ) -> Option<(FixedOffsetVar, FixedOffsetVar)> {
710 if let Expr_::ExprAssign(ref lhs, ref rhs) = e.node {
711 match (get_fixed_offset_var(cx, lhs, var), get_fixed_offset_var(cx, rhs, var)) {
712 (Some(offset_left), Some(offset_right)) => Some((offset_left, offset_right)),
720 if let Expr_::ExprBlock(ref b) = body.node {
729 .map(|stmt| match stmt.node {
730 Stmt_::StmtDecl(..) => None,
731 Stmt_::StmtExpr(ref e, _node_id) | Stmt_::StmtSemi(ref e, _node_id) => Some(get_assignment(cx, e, var)),
736 .map(|e| Some(get_assignment(cx, &*e, var))),
739 .collect::<Option<Vec<_>>>()
740 .unwrap_or_else(|| vec![])
742 get_assignment(cx, body, var).into_iter().collect()
746 /// Check for for loops that sequentially copy items from one slice-like
747 /// object to another.
748 fn detect_manual_memcpy<'a, 'tcx>(
749 cx: &LateContext<'a, 'tcx>,
755 if let Some(higher::Range {
759 }) = higher::range(arg)
761 // the var must be a single name
762 if let PatKind::Binding(_, def_id, _, _) = pat.node {
763 let print_sum = |arg1: &Offset, arg2: &Offset| -> String {
764 match (&arg1.value[..], arg1.negate, &arg2.value[..], arg2.negate) {
765 ("0", _, "0", _) => "".into(),
766 ("0", _, x, false) | (x, false, "0", false) => x.into(),
767 ("0", _, x, true) | (x, false, "0", true) => format!("-{}", x),
768 (x, false, y, false) => format!("({} + {})", x, y),
769 (x, false, y, true) => format!("({} - {})", x, y),
770 (x, true, y, false) => format!("({} - {})", y, x),
771 (x, true, y, true) => format!("-({} + {})", x, y),
775 let print_limit = |end: &Option<&Expr>, offset: Offset, var_name: &str| if let Some(end) = *end {
777 let ExprMethodCall(ref method, _, ref len_args) = end.node,
778 method.name == "len",
780 let Some(arg) = len_args.get(0),
781 snippet(cx, arg.span, "??") == var_name,
783 return if offset.negate {
784 format!("({} - {})", snippet(cx, end.span, "<src>.len()"), offset.value)
790 let end_str = match limits {
791 ast::RangeLimits::Closed => {
792 let end = sugg::Sugg::hir(cx, end, "<count>");
793 format!("{}", end + sugg::ONE)
795 ast::RangeLimits::HalfOpen => format!("{}", snippet(cx, end.span, "..")),
798 print_sum(&Offset::positive(end_str), &offset)
803 // The only statements in the for loops can be indexed assignments from
804 // indexed retrievals.
805 let manual_copies = get_indexed_assignments(cx, body, def_id);
807 let big_sugg = manual_copies
809 .map(|(dst_var, src_var)| {
810 let start_str = Offset::positive(snippet_opt(cx, start.span).unwrap_or_else(|| "".into()));
811 let dst_offset = print_sum(&start_str, &dst_var.offset);
812 let dst_limit = print_limit(end, dst_var.offset, &dst_var.var_name);
813 let src_offset = print_sum(&start_str, &src_var.offset);
814 let src_limit = print_limit(end, src_var.offset, &src_var.var_name);
815 let dst = if dst_offset == "" && dst_limit == "" {
818 format!("{}[{}..{}]", dst_var.var_name, dst_offset, dst_limit)
821 format!("{}.clone_from_slice(&{}[{}..{}])", dst, src_var.var_name, src_offset, src_limit)
825 if !big_sugg.is_empty() {
830 "it looks like you're manually copying between slices",
831 "try replacing the loop by",
839 /// Check for looping over a range and then indexing a sequence with it.
840 /// The iteratee must be a range literal.
841 fn check_for_loop_range<'a, 'tcx>(
842 cx: &LateContext<'a, 'tcx>,
848 if let Some(higher::Range {
852 }) = higher::range(arg)
854 // the var must be a single name
855 if let PatKind::Binding(_, def_id, ref ident, _) = pat.node {
856 let mut visitor = VarVisitor {
859 indexed: HashMap::new(),
860 referenced: HashSet::new(),
863 walk_expr(&mut visitor, body);
865 // linting condition: we only indexed one variable
866 if visitor.indexed.len() == 1 {
867 let (indexed, indexed_extent) = visitor
871 .expect("already checked that we have exactly 1 element");
873 // ensure that the indexed variable was declared before the loop, see #601
874 if let Some(indexed_extent) = indexed_extent {
875 let parent_id = cx.tcx.hir.get_parent(expr.id);
876 let parent_def_id = cx.tcx.hir.local_def_id(parent_id);
877 let region_scope_tree = cx.tcx.region_scope_tree(parent_def_id);
878 let pat_extent = region_scope_tree.var_scope(pat.hir_id.local_id);
879 if region_scope_tree.is_subscope_of(indexed_extent, pat_extent) {
884 // don't lint if the container that is indexed into is also used without
886 if visitor.referenced.contains(&indexed) {
890 let starts_at_zero = is_integer_literal(start, 0);
892 let skip = if starts_at_zero {
895 format!(".skip({})", snippet(cx, start.span, ".."))
898 let take = if let Some(end) = *end {
899 if is_len_call(end, &indexed) {
903 ast::RangeLimits::Closed => {
904 let end = sugg::Sugg::hir(cx, end, "<count>");
905 format!(".take({})", end + sugg::ONE)
907 ast::RangeLimits::HalfOpen => format!(".take({})", snippet(cx, end.span, "..")),
914 if visitor.nonindex {
919 &format!("the loop variable `{}` is used to index `{}`", ident.node, indexed),
923 "consider using an iterator".to_string(),
925 (pat.span, format!("({}, <item>)", ident.node)),
926 (arg.span, format!("{}.iter().enumerate(){}{}", indexed, take, skip)),
932 let repl = if starts_at_zero && take.is_empty() {
933 format!("&{}", indexed)
935 format!("{}.iter(){}{}", indexed, take, skip)
942 &format!("the loop variable `{}` is only used to index `{}`.", ident.node, indexed),
946 "consider using an iterator".to_string(),
947 vec![(pat.span, "<item>".to_string()), (arg.span, repl)],
957 fn is_len_call(expr: &Expr, var: &Name) -> bool {
959 let ExprMethodCall(ref method, _, ref len_args) = expr.node,
961 method.name == "len",
962 let ExprPath(QPath::Resolved(_, ref path)) = len_args[0].node,
963 path.segments.len() == 1,
964 path.segments[0].name == *var
972 fn check_for_loop_reverse_range(cx: &LateContext, arg: &Expr, expr: &Expr) {
973 // if this for loop is iterating over a two-sided range...
974 if let Some(higher::Range {
978 }) = higher::range(arg)
980 // ...and both sides are compile-time constant integers...
981 let parent_item = cx.tcx.hir.get_parent(arg.id);
982 let parent_def_id = cx.tcx.hir.local_def_id(parent_item);
983 let substs = Substs::identity_for_item(cx.tcx, parent_def_id);
984 let constcx = ConstContext::new(cx.tcx, cx.param_env.and(substs), cx.tables);
985 if let Ok(start_idx) = constcx.eval(start) {
986 if let Ok(end_idx) = constcx.eval(end) {
987 // ...and the start index is greater than the end index,
988 // this loop will never run. This is often confusing for developers
989 // who think that this will iterate from the larger value to the
991 let (sup, eq) = match (start_idx, end_idx) {
992 (ConstVal::Integral(start_idx), ConstVal::Integral(end_idx)) => {
993 (start_idx > end_idx, start_idx == end_idx)
999 let start_snippet = snippet(cx, start.span, "_");
1000 let end_snippet = snippet(cx, end.span, "_");
1001 let dots = if limits == ast::RangeLimits::Closed {
1011 "this range is empty so this for loop will never run",
1015 "consider using the following if you are attempting to iterate over this \
1018 "({end}{dots}{start}).rev()",
1021 start = start_snippet
1026 } else if eq && limits != ast::RangeLimits::Closed {
1027 // if they are equal, it's also problematic - this loop
1033 "this range is empty so this for loop will never run",
1041 fn lint_iter_method(cx: &LateContext, args: &[Expr], arg: &Expr, method_name: &str) {
1042 let object = snippet(cx, args[0].span, "_");
1043 let muta = if method_name == "iter_mut" {
1052 "it is more idiomatic to loop over references to containers instead of using explicit \
1054 "to write this more concisely, try",
1055 format!("&{}{}", muta, object),
1059 fn check_for_loop_arg(cx: &LateContext, pat: &Pat, arg: &Expr, expr: &Expr) {
1060 let mut next_loop_linted = false; // whether or not ITER_NEXT_LOOP lint was used
1061 if let ExprMethodCall(ref method, _, ref args) = arg.node {
1062 // just the receiver, no arguments
1063 if args.len() == 1 {
1064 let method_name = &*method.name.as_str();
1065 // check for looping over x.iter() or x.iter_mut(), could use &x or &mut x
1066 if method_name == "iter" || method_name == "iter_mut" {
1067 if is_ref_iterable_type(cx, &args[0]) {
1068 lint_iter_method(cx, args, arg, method_name);
1070 } else if method_name == "into_iter" && match_trait_method(cx, arg, &paths::INTO_ITERATOR) {
1071 let def_id = cx.tables.type_dependent_defs()[arg.hir_id].def_id();
1072 let substs = cx.tables.node_substs(arg.hir_id);
1073 let method_type = cx.tcx.type_of(def_id).subst(cx.tcx, substs);
1075 let fn_arg_tys = method_type.fn_sig(cx.tcx).inputs();
1076 assert_eq!(fn_arg_tys.skip_binder().len(), 1);
1077 if fn_arg_tys.skip_binder()[0].is_region_ptr() {
1078 lint_iter_method(cx, args, arg, method_name);
1080 let object = snippet(cx, args[0].span, "_");
1083 EXPLICIT_INTO_ITER_LOOP,
1085 "it is more idiomatic to loop over containers instead of using explicit \
1086 iteration methods`",
1087 "to write this more concisely, try",
1091 } else if method_name == "next" && match_trait_method(cx, arg, &paths::ITERATOR) {
1096 "you are iterating over `Iterator::next()` which is an Option; this will compile but is \
1097 probably not what you want",
1099 next_loop_linted = true;
1103 if !next_loop_linted {
1104 check_arg_type(cx, pat, arg);
1108 /// Check for `for` loops over `Option`s and `Results`
1109 fn check_arg_type(cx: &LateContext, pat: &Pat, arg: &Expr) {
1110 let ty = cx.tables.expr_ty(arg);
1111 if match_type(cx, ty, &paths::OPTION) {
1114 FOR_LOOP_OVER_OPTION,
1117 "for loop over `{0}`, which is an `Option`. This is more readably written as an \
1118 `if let` statement.",
1119 snippet(cx, arg.span, "_")
1122 "consider replacing `for {0} in {1}` with `if let Some({0}) = {1}`",
1123 snippet(cx, pat.span, "_"),
1124 snippet(cx, arg.span, "_")
1127 } else if match_type(cx, ty, &paths::RESULT) {
1130 FOR_LOOP_OVER_RESULT,
1133 "for loop over `{0}`, which is a `Result`. This is more readably written as an \
1134 `if let` statement.",
1135 snippet(cx, arg.span, "_")
1138 "consider replacing `for {0} in {1}` with `if let Ok({0}) = {1}`",
1139 snippet(cx, pat.span, "_"),
1140 snippet(cx, arg.span, "_")
1146 fn check_for_loop_explicit_counter<'a, 'tcx>(
1147 cx: &LateContext<'a, 'tcx>,
1152 // Look for variables that are incremented once per loop iteration.
1153 let mut visitor = IncrementVisitor {
1155 states: HashMap::new(),
1159 walk_expr(&mut visitor, body);
1161 // For each candidate, check the parent block to see if
1162 // it's initialized to zero at the start of the loop.
1163 let map = &cx.tcx.hir;
1164 let parent_scope = map.get_enclosing_scope(expr.id)
1165 .and_then(|id| map.get_enclosing_scope(id));
1166 if let Some(parent_id) = parent_scope {
1167 if let NodeBlock(block) = map.get(parent_id) {
1168 for (id, _) in visitor
1171 .filter(|&(_, v)| *v == VarState::IncrOnce)
1173 let mut visitor2 = InitializeVisitor {
1177 state: VarState::IncrOnce,
1182 walk_block(&mut visitor2, block);
1184 if visitor2.state == VarState::Warn {
1185 if let Some(name) = visitor2.name {
1188 EXPLICIT_COUNTER_LOOP,
1191 "the variable `{0}` is used as a loop counter. Consider using `for ({0}, \
1192 item) in {1}.enumerate()` or similar iterators",
1194 snippet(cx, arg.span, "_")
1204 /// Check for the `FOR_KV_MAP` lint.
1205 fn check_for_loop_over_map_kv<'a, 'tcx>(
1206 cx: &LateContext<'a, 'tcx>,
1212 let pat_span = pat.span;
1214 if let PatKind::Tuple(ref pat, _) = pat.node {
1216 let arg_span = arg.span;
1217 let (new_pat_span, kind, ty, mutbl) = match cx.tables.expr_ty(arg).sty {
1218 ty::TyRef(_, ref tam) => match (&pat[0].node, &pat[1].node) {
1219 (key, _) if pat_is_wild(key, body) => (pat[1].span, "value", tam.ty, tam.mutbl),
1220 (_, value) if pat_is_wild(value, body) => (pat[0].span, "key", tam.ty, MutImmutable),
1225 let mutbl = match mutbl {
1227 MutMutable => "_mut",
1229 let arg = match arg.node {
1230 ExprAddrOf(_, ref expr) => &**expr,
1234 if match_type(cx, ty, &paths::HASHMAP) || match_type(cx, ty, &paths::BTREEMAP) {
1239 &format!("you seem to want to iterate on a map's {}s", kind),
1241 let map = sugg::Sugg::hir(cx, arg, "map");
1244 "use the corresponding method".into(),
1246 (pat_span, snippet(cx, new_pat_span, kind).into_owned()),
1247 (arg_span, format!("{}.{}s{}()", map.maybe_par(), kind, mutbl)),
1257 /// Return true if the pattern is a `PatWild` or an ident prefixed with `'_'`.
1258 fn pat_is_wild<'tcx>(pat: &'tcx PatKind, body: &'tcx Expr) -> bool {
1260 PatKind::Wild => true,
1261 PatKind::Binding(_, _, ident, None) if ident.node.as_str().starts_with('_') => {
1262 let mut visitor = UsedVisitor {
1266 walk_expr(&mut visitor, body);
1273 fn match_var(expr: &Expr, var: Name) -> bool {
1274 if let ExprPath(QPath::Resolved(None, ref path)) = expr.node {
1275 if path.segments.len() == 1 && path.segments[0].name == var {
1282 struct UsedVisitor {
1283 var: ast::Name, // var to look for
1284 used: bool, // has the var been used otherwise?
1287 impl<'tcx> Visitor<'tcx> for UsedVisitor {
1288 fn visit_expr(&mut self, expr: &'tcx Expr) {
1289 if match_var(expr, self.var) {
1292 walk_expr(self, expr);
1296 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1297 NestedVisitorMap::None
1301 struct DefIdUsedVisitor<'a, 'tcx: 'a> {
1302 cx: &'a LateContext<'a, 'tcx>,
1307 impl<'a, 'tcx: 'a> Visitor<'tcx> for DefIdUsedVisitor<'a, 'tcx> {
1308 fn visit_expr(&mut self, expr: &'tcx Expr) {
1309 if same_var(self.cx, expr, self.def_id) {
1312 walk_expr(self, expr);
1316 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1317 NestedVisitorMap::None
1321 struct VarVisitor<'a, 'tcx: 'a> {
1322 /// context reference
1323 cx: &'a LateContext<'a, 'tcx>,
1324 /// var name to look for as index
1326 /// indexed variables, the extend is `None` for global
1327 indexed: HashMap<Name, Option<region::Scope>>,
1328 /// Any names that are used outside an index operation.
1329 /// Used to detect things like `&mut vec` used together with `vec[i]`
1330 referenced: HashSet<Name>,
1331 /// has the loop variable been used in expressions other than the index of
1336 impl<'a, 'tcx> Visitor<'tcx> for VarVisitor<'a, 'tcx> {
1337 fn visit_expr(&mut self, expr: &'tcx Expr) {
1340 let ExprIndex(ref seqexpr, ref idx) = expr.node,
1341 // the indexed container is referenced by a name
1342 let ExprPath(ref seqpath) = seqexpr.node,
1343 let QPath::Resolved(None, ref seqvar) = *seqpath,
1344 seqvar.segments.len() == 1,
1346 let index_used = same_var(self.cx, idx, self.var) || {
1347 let mut used_visitor = DefIdUsedVisitor {
1352 walk_expr(&mut used_visitor, idx);
1357 let def = self.cx.tables.qpath_def(seqpath, seqexpr.hir_id);
1359 Def::Local(..) | Def::Upvar(..) => {
1360 let def_id = def.def_id();
1361 let node_id = self.cx.tcx.hir.as_local_node_id(def_id).expect("local/upvar are local nodes");
1362 let hir_id = self.cx.tcx.hir.node_to_hir_id(node_id);
1364 let parent_id = self.cx.tcx.hir.get_parent(expr.id);
1365 let parent_def_id = self.cx.tcx.hir.local_def_id(parent_id);
1366 let extent = self.cx.tcx.region_scope_tree(parent_def_id).var_scope(hir_id.local_id);
1367 self.indexed.insert(seqvar.segments[0].name, Some(extent));
1368 return; // no need to walk further *on the variable*
1370 Def::Static(..) | Def::Const(..) => {
1371 self.indexed.insert(seqvar.segments[0].name, None);
1372 return; // no need to walk further *on the variable*
1380 // directly using a variable
1381 let ExprPath(ref qpath) = expr.node,
1382 let QPath::Resolved(None, ref path) = *qpath,
1383 path.segments.len() == 1,
1385 if self.cx.tables.qpath_def(qpath, expr.hir_id).def_id() == self.var {
1386 // we are not indexing anything, record that
1387 self.nonindex = true;
1389 // not the correct variable, but still a variable
1390 self.referenced.insert(path.segments[0].name);
1394 walk_expr(self, expr);
1396 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1397 NestedVisitorMap::None
1401 fn is_iterator_used_after_while_let<'a, 'tcx: 'a>(cx: &LateContext<'a, 'tcx>, iter_expr: &'tcx Expr) -> bool {
1402 let def_id = match var_def_id(cx, iter_expr) {
1404 None => return false,
1406 let mut visitor = VarUsedAfterLoopVisitor {
1409 iter_expr_id: iter_expr.id,
1410 past_while_let: false,
1411 var_used_after_while_let: false,
1413 if let Some(enclosing_block) = get_enclosing_block(cx, def_id) {
1414 walk_block(&mut visitor, enclosing_block);
1416 visitor.var_used_after_while_let
1419 struct VarUsedAfterLoopVisitor<'a, 'tcx: 'a> {
1420 cx: &'a LateContext<'a, 'tcx>,
1422 iter_expr_id: NodeId,
1423 past_while_let: bool,
1424 var_used_after_while_let: bool,
1427 impl<'a, 'tcx> Visitor<'tcx> for VarUsedAfterLoopVisitor<'a, 'tcx> {
1428 fn visit_expr(&mut self, expr: &'tcx Expr) {
1429 if self.past_while_let {
1430 if Some(self.def_id) == var_def_id(self.cx, expr) {
1431 self.var_used_after_while_let = true;
1433 } else if self.iter_expr_id == expr.id {
1434 self.past_while_let = true;
1436 walk_expr(self, expr);
1438 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1439 NestedVisitorMap::None
1444 /// Return true if the type of expr is one that provides `IntoIterator` impls
1445 /// for `&T` and `&mut T`, such as `Vec`.
1446 #[cfg_attr(rustfmt, rustfmt_skip)]
1447 fn is_ref_iterable_type(cx: &LateContext, e: &Expr) -> bool {
1448 // no walk_ptrs_ty: calling iter() on a reference can make sense because it
1449 // will allow further borrows afterwards
1450 let ty = cx.tables.expr_ty(e);
1451 is_iterable_array(ty) ||
1452 match_type(cx, ty, &paths::VEC) ||
1453 match_type(cx, ty, &paths::LINKED_LIST) ||
1454 match_type(cx, ty, &paths::HASHMAP) ||
1455 match_type(cx, ty, &paths::HASHSET) ||
1456 match_type(cx, ty, &paths::VEC_DEQUE) ||
1457 match_type(cx, ty, &paths::BINARY_HEAP) ||
1458 match_type(cx, ty, &paths::BTREEMAP) ||
1459 match_type(cx, ty, &paths::BTREESET)
1462 fn is_iterable_array(ty: Ty) -> bool {
1463 // IntoIterator is currently only implemented for array sizes <= 32 in rustc
1465 ty::TyArray(_, 0...32) => true,
1470 /// If a block begins with a statement (possibly a `let` binding) and has an
1471 /// expression, return it.
1472 fn extract_expr_from_first_stmt(block: &Block) -> Option<&Expr> {
1473 if block.stmts.is_empty() {
1476 if let StmtDecl(ref decl, _) = block.stmts[0].node {
1477 if let DeclLocal(ref local) = decl.node {
1478 if let Some(ref expr) = local.init {
1491 /// If a block begins with an expression (with or without semicolon), return it.
1492 fn extract_first_expr(block: &Block) -> Option<&Expr> {
1494 Some(ref expr) if block.stmts.is_empty() => Some(expr),
1495 None if !block.stmts.is_empty() => match block.stmts[0].node {
1496 StmtExpr(ref expr, _) | StmtSemi(ref expr, _) => Some(expr),
1497 StmtDecl(..) => None,
1503 /// Return true if expr contains a single break expr (maybe within a block).
1504 fn is_break_expr(expr: &Expr) -> bool {
1506 ExprBreak(dest, _) if dest.ident.is_none() => true,
1507 ExprBlock(ref b) => match extract_first_expr(b) {
1508 Some(subexpr) => is_break_expr(subexpr),
1515 // To trigger the EXPLICIT_COUNTER_LOOP lint, a variable must be
1516 // incremented exactly once in the loop body, and initialized to zero
1517 // at the start of the loop.
1518 #[derive(PartialEq)]
1520 Initial, // Not examined yet
1521 IncrOnce, // Incremented exactly once, may be a loop counter
1522 Declared, // Declared but not (yet) initialized to zero
1527 /// Scan a for loop for variables that are incremented exactly once.
1528 struct IncrementVisitor<'a, 'tcx: 'a> {
1529 cx: &'a LateContext<'a, 'tcx>, // context reference
1530 states: HashMap<NodeId, VarState>, // incremented variables
1531 depth: u32, // depth of conditional expressions
1535 impl<'a, 'tcx> Visitor<'tcx> for IncrementVisitor<'a, 'tcx> {
1536 fn visit_expr(&mut self, expr: &'tcx Expr) {
1541 // If node is a variable
1542 if let Some(def_id) = var_def_id(self.cx, expr) {
1543 if let Some(parent) = get_parent_expr(self.cx, expr) {
1544 let state = self.states.entry(def_id).or_insert(VarState::Initial);
1547 ExprAssignOp(op, ref lhs, ref rhs) => {
1548 if lhs.id == expr.id {
1549 if op.node == BiAdd && is_integer_literal(rhs, 1) {
1550 *state = match *state {
1551 VarState::Initial if self.depth == 0 => VarState::IncrOnce,
1552 _ => VarState::DontWarn,
1555 // Assigned some other value
1556 *state = VarState::DontWarn;
1560 ExprAssign(ref lhs, _) if lhs.id == expr.id => *state = VarState::DontWarn,
1561 ExprAddrOf(mutability, _) if mutability == MutMutable => *state = VarState::DontWarn,
1565 } else if is_loop(expr) {
1566 self.states.clear();
1569 } else if is_conditional(expr) {
1571 walk_expr(self, expr);
1575 walk_expr(self, expr);
1577 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1578 NestedVisitorMap::None
1582 /// Check whether a variable is initialized to zero at the start of a loop.
1583 struct InitializeVisitor<'a, 'tcx: 'a> {
1584 cx: &'a LateContext<'a, 'tcx>, // context reference
1585 end_expr: &'tcx Expr, // the for loop. Stop scanning here.
1589 depth: u32, // depth of conditional expressions
1593 impl<'a, 'tcx> Visitor<'tcx> for InitializeVisitor<'a, 'tcx> {
1594 fn visit_decl(&mut self, decl: &'tcx Decl) {
1595 // Look for declarations of the variable
1596 if let DeclLocal(ref local) = decl.node {
1597 if local.pat.id == self.var_id {
1598 if let PatKind::Binding(_, _, ref ident, _) = local.pat.node {
1599 self.name = Some(ident.node);
1601 self.state = if let Some(ref init) = local.init {
1602 if is_integer_literal(init, 0) {
1613 walk_decl(self, decl);
1616 fn visit_expr(&mut self, expr: &'tcx Expr) {
1617 if self.state == VarState::DontWarn {
1620 if expr == self.end_expr {
1621 self.past_loop = true;
1624 // No need to visit expressions before the variable is
1626 if self.state == VarState::IncrOnce {
1630 // If node is the desired variable, see how it's used
1631 if var_def_id(self.cx, expr) == Some(self.var_id) {
1632 if let Some(parent) = get_parent_expr(self.cx, expr) {
1634 ExprAssignOp(_, ref lhs, _) if lhs.id == expr.id => {
1635 self.state = VarState::DontWarn;
1637 ExprAssign(ref lhs, ref rhs) if lhs.id == expr.id => {
1638 self.state = if is_integer_literal(rhs, 0) && self.depth == 0 {
1644 ExprAddrOf(mutability, _) if mutability == MutMutable => self.state = VarState::DontWarn,
1650 self.state = VarState::DontWarn;
1653 } else if !self.past_loop && is_loop(expr) {
1654 self.state = VarState::DontWarn;
1656 } else if is_conditional(expr) {
1658 walk_expr(self, expr);
1662 walk_expr(self, expr);
1664 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1665 NestedVisitorMap::None
1669 fn var_def_id(cx: &LateContext, expr: &Expr) -> Option<NodeId> {
1670 if let ExprPath(ref qpath) = expr.node {
1671 let path_res = cx.tables.qpath_def(qpath, expr.hir_id);
1672 if let Def::Local(def_id) = path_res {
1673 let node_id = cx.tcx
1675 .as_local_node_id(def_id)
1676 .expect("That DefId should be valid");
1677 return Some(node_id);
1683 fn is_loop(expr: &Expr) -> bool {
1685 ExprLoop(..) | ExprWhile(..) => true,
1690 fn is_conditional(expr: &Expr) -> bool {
1692 ExprIf(..) | ExprMatch(..) => true,
1697 fn is_nested(cx: &LateContext, match_expr: &Expr, iter_expr: &Expr) -> bool {
1699 let Some(loop_block) = get_enclosing_block(cx, match_expr.id),
1700 let Some(map::Node::NodeExpr(loop_expr)) = cx.tcx.hir.find(cx.tcx.hir.get_parent_node(loop_block.id)),
1702 return is_loop_nested(cx, loop_expr, iter_expr)
1707 fn is_loop_nested(cx: &LateContext, loop_expr: &Expr, iter_expr: &Expr) -> bool {
1708 let mut id = loop_expr.id;
1709 let iter_name = if let Some(name) = path_name(iter_expr) {
1715 let parent = cx.tcx.hir.get_parent_node(id);
1719 match cx.tcx.hir.find(parent) {
1720 Some(NodeExpr(expr)) => match expr.node {
1721 ExprLoop(..) | ExprWhile(..) => {
1726 Some(NodeBlock(block)) => {
1727 let mut block_visitor = LoopNestVisitor {
1729 iterator: iter_name,
1732 walk_block(&mut block_visitor, block);
1733 if block_visitor.nesting == RuledOut {
1737 Some(NodeStmt(_)) => (),
1746 #[derive(PartialEq, Eq)]
1748 Unknown, // no nesting detected yet
1749 RuledOut, // the iterator is initialized or assigned within scope
1750 LookFurther, // no nesting detected, no further walk required
1753 use self::Nesting::{LookFurther, RuledOut, Unknown};
1755 struct LoopNestVisitor {
1761 impl<'tcx> Visitor<'tcx> for LoopNestVisitor {
1762 fn visit_stmt(&mut self, stmt: &'tcx Stmt) {
1763 if stmt.node.id() == self.id {
1764 self.nesting = LookFurther;
1765 } else if self.nesting == Unknown {
1766 walk_stmt(self, stmt);
1770 fn visit_expr(&mut self, expr: &'tcx Expr) {
1771 if self.nesting != Unknown {
1774 if expr.id == self.id {
1775 self.nesting = LookFurther;
1779 ExprAssign(ref path, _) | ExprAssignOp(_, ref path, _) => if match_var(path, self.iterator) {
1780 self.nesting = RuledOut;
1782 _ => walk_expr(self, expr),
1786 fn visit_pat(&mut self, pat: &'tcx Pat) {
1787 if self.nesting != Unknown {
1790 if let PatKind::Binding(_, _, span_name, _) = pat.node {
1791 if self.iterator == span_name.node {
1792 self.nesting = RuledOut;
1799 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1800 NestedVisitorMap::None
1804 fn path_name(e: &Expr) -> Option<Name> {
1805 if let ExprPath(QPath::Resolved(_, ref path)) = e.node {
1806 let segments = &path.segments;
1807 if segments.len() == 1 {
1808 return Some(segments[0].name);