3 use rustc::hir::def::Def;
4 use rustc::hir::def_id::DefId;
5 use rustc::hir::intravisit::{Visitor, walk_expr, walk_block, walk_decl, NestedVisitorMap};
6 use rustc::hir::map::Node::NodeBlock;
8 use rustc::middle::const_val::ConstVal;
9 use rustc::middle::region::CodeExtent;
11 use rustc_const_eval::EvalHint::ExprTypeChecked;
12 use rustc_const_eval::ConstContext;
13 use std::collections::HashMap;
17 use utils::{snippet, span_lint, get_parent_expr, match_trait_method, match_type, multispan_sugg, in_external_macro,
18 is_refutable, span_help_and_lint, is_integer_literal, get_enclosing_block, span_lint_and_then, higher,
22 /// **What it does:** Checks for looping over the range of `0..len` of some
23 /// collection just to get the values by index.
25 /// **Why is this bad?** Just iterating the collection itself makes the intent
26 /// more clear and is probably faster.
28 /// **Known problems:** None.
32 /// for i in 0..vec.len() {
33 /// println!("{}", vec[i]);
37 pub NEEDLESS_RANGE_LOOP,
39 "for-looping over a range of indices where an iterator over items would do"
42 /// **What it does:** Checks for loops on `x.iter()` where `&x` will do, and
43 /// suggests the latter.
45 /// **Why is this bad?** Readability.
47 /// **Known problems:** False negatives. We currently only warn on some known
52 /// // with `y` a `Vec` or slice:
53 /// for x in y.iter() { .. }
56 pub EXPLICIT_ITER_LOOP,
58 "for-looping over `_.iter()` or `_.iter_mut()` when `&_` or `&mut _` would do"
61 /// **What it does:** Checks for loops on `y.into_iter()` where `y` will do, and
62 /// suggests the latter.
64 /// **Why is this bad?** Readability.
66 /// **Known problems:** None
70 /// // with `y` a `Vec` or slice:
71 /// for x in y.into_iter() { .. }
74 pub EXPLICIT_INTO_ITER_LOOP,
76 "for-looping over `_.into_iter()` when `_` would do"
79 /// **What it does:** Checks for loops on `x.next()`.
81 /// **Why is this bad?** `next()` returns either `Some(value)` if there was a
82 /// value, or `None` otherwise. The insidious thing is that `Option<_>`
83 /// implements `IntoIterator`, so that possibly one value will be iterated,
84 /// leading to some hard to find bugs. No one will want to write such code
85 /// [except to win an Underhanded Rust
86 /// Contest](https://www.reddit.com/r/rust/comments/3hb0wm/underhanded_rust_contest/cu5yuhr).
88 /// **Known problems:** None.
92 /// for x in y.next() { .. }
97 "for-looping over `_.next()` which is probably not intended"
100 /// **What it does:** Checks for `for` loops over `Option` values.
102 /// **Why is this bad?** Readability. This is more clearly expressed as an `if let`.
104 /// **Known problems:** None.
108 /// for x in option { .. }
113 /// if let Some(x) = option { .. }
116 pub FOR_LOOP_OVER_OPTION,
118 "for-looping over an `Option`, which is more clearly expressed as an `if let`"
121 /// **What it does:** Checks for `for` loops over `Result` values.
123 /// **Why is this bad?** Readability. This is more clearly expressed as an `if let`.
125 /// **Known problems:** None.
129 /// for x in result { .. }
134 /// if let Ok(x) = result { .. }
137 pub FOR_LOOP_OVER_RESULT,
139 "for-looping over a `Result`, which is more clearly expressed as an `if let`"
142 /// **What it does:** Detects `loop + match` combinations that are easier
143 /// written as a `while let` loop.
145 /// **Why is this bad?** The `while let` loop is usually shorter and more readable.
147 /// **Known problems:** Sometimes the wrong binding is displayed (#383).
152 /// let x = match y {
156 /// // .. do something with x
158 /// // is easier written as
159 /// while let Some(x) = y {
160 /// // .. do something with x
166 "`loop { if let { ... } else break }`, which can be written as a `while let` loop"
169 /// **What it does:** Checks for using `collect()` on an iterator without using
172 /// **Why is this bad?** It is more idiomatic to use a `for` loop over the
173 /// iterator instead.
175 /// **Known problems:** None.
179 /// vec.iter().map(|x| /* some operation returning () */).collect::<Vec<_>>();
184 "`collect()`ing an iterator without using the result; this is usually better \
185 written as a for loop"
188 /// **What it does:** Checks for loops over ranges `x..y` where both `x` and `y`
189 /// are constant and `x` is greater or equal to `y`, unless the range is
190 /// reversed or has a negative `.step_by(_)`.
192 /// **Why is it bad?** Such loops will either be skipped or loop until
193 /// wrap-around (in debug code, this may `panic!()`). Both options are probably
196 /// **Known problems:** The lint cannot catch loops over dynamically defined
197 /// ranges. Doing this would require simulating all possible inputs and code
198 /// paths through the program, which would be complex and error-prone.
202 /// for x in 5..10-5 { .. } // oops, stray `-`
205 pub REVERSE_RANGE_LOOP,
207 "iteration over an empty range, such as `10..0` or `5..5`"
210 /// **What it does:** Checks `for` loops over slices with an explicit counter
211 /// and suggests the use of `.enumerate()`.
213 /// **Why is it bad?** Not only is the version using `.enumerate()` more
214 /// readable, the compiler is able to remove bounds checks which can lead to
215 /// faster code in some instances.
217 /// **Known problems:** None.
221 /// for i in 0..v.len() { foo(v[i]);
222 /// for i in 0..v.len() { bar(i, v[i]); }
225 pub EXPLICIT_COUNTER_LOOP,
227 "for-looping with an explicit counter when `_.enumerate()` would do"
230 /// **What it does:** Checks for empty `loop` expressions.
232 /// **Why is this bad?** Those busy loops burn CPU cycles without doing
233 /// anything. Think of the environment and either block on something or at least
234 /// make the thread sleep for some microseconds.
236 /// **Known problems:** None.
245 "empty `loop {}`, which should block or sleep"
248 /// **What it does:** Checks for `while let` expressions on iterators.
250 /// **Why is this bad?** Readability. A simple `for` loop is shorter and conveys
251 /// the intent better.
253 /// **Known problems:** None.
257 /// while let Some(val) = iter() { .. }
260 pub WHILE_LET_ON_ITERATOR,
262 "using a while-let loop instead of a for loop on an iterator"
265 /// **What it does:** Checks for iterating a map (`HashMap` or `BTreeMap`) and
266 /// ignoring either the keys or values.
268 /// **Why is this bad?** Readability. There are `keys` and `values` methods that
269 /// can be used to express that don't need the values or keys.
271 /// **Known problems:** None.
275 /// for (k, _) in &map { .. }
278 /// could be replaced by
281 /// for k in map.keys() { .. }
286 "looping on a map using `iter` when `keys` or `values` would do"
289 #[derive(Copy, Clone)]
292 impl LintPass for Pass {
293 fn get_lints(&self) -> LintArray {
294 lint_array!(NEEDLESS_RANGE_LOOP,
296 EXPLICIT_INTO_ITER_LOOP,
298 FOR_LOOP_OVER_RESULT,
299 FOR_LOOP_OVER_OPTION,
303 EXPLICIT_COUNTER_LOOP,
305 WHILE_LET_ON_ITERATOR,
310 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
311 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
312 if let Some((pat, arg, body)) = higher::for_loop(expr) {
313 check_for_loop(cx, pat, arg, body, expr);
315 // check for `loop { if let {} else break }` that could be `while let`
316 // (also matches an explicit "match" instead of "if let")
317 // (even if the "match" or "if let" is used for declaration)
318 if let ExprLoop(ref block, _, LoopSource::Loop) = expr.node {
319 // also check for empty `loop {}` statements
320 if block.stmts.is_empty() && block.expr.is_none() {
324 "empty `loop {}` detected. You may want to either use `panic!()` or add \
325 `std::thread::sleep(..);` to the loop body.");
328 // extract the expression from the first statement (if any) in a block
329 let inner_stmt_expr = extract_expr_from_first_stmt(block);
330 // or extract the first expression (if any) from the block
331 if let Some(inner) = inner_stmt_expr.or_else(|| extract_first_expr(block)) {
332 if let ExprMatch(ref matchexpr, ref arms, ref source) = inner.node {
333 // ensure "if let" compatible match structure
335 MatchSource::Normal |
336 MatchSource::IfLetDesugar { .. } => {
337 if arms.len() == 2 && arms[0].pats.len() == 1 && arms[0].guard.is_none() &&
338 arms[1].pats.len() == 1 && arms[1].guard.is_none() &&
339 is_break_expr(&arms[1].body) {
340 if in_external_macro(cx, expr.span) {
344 // NOTE: we used to make build a body here instead of using
345 // ellipsis, this was removed because:
346 // 1) it was ugly with big bodies;
347 // 2) it was not indented properly;
348 // 3) it wasn’t very smart (see #675).
349 span_lint_and_then(cx,
352 "this loop could be written as a `while let` loop",
354 let sug = format!("while let {} = {} {{ .. }}",
355 snippet(cx, arms[0].pats[0].span, ".."),
356 snippet(cx, matchexpr.span, ".."));
357 db.span_suggestion(expr.span, "try", sug);
366 if let ExprMatch(ref match_expr, ref arms, MatchSource::WhileLetDesugar) = expr.node {
367 let pat = &arms[0].pats[0].node;
368 if let (&PatKind::TupleStruct(ref qpath, ref pat_args, _),
369 &ExprMethodCall(method_name, _, ref method_args)) = (pat, &match_expr.node) {
370 let iter_expr = &method_args[0];
371 let lhs_constructor = last_path_segment(qpath);
372 if &*method_name.node.as_str() == "next" && match_trait_method(cx, match_expr, &paths::ITERATOR) &&
373 &*lhs_constructor.name.as_str() == "Some" && !is_refutable(cx, &pat_args[0]) &&
374 !is_iterator_used_after_while_let(cx, iter_expr) {
375 let iterator = snippet(cx, method_args[0].span, "_");
376 let loop_var = snippet(cx, pat_args[0].span, "_");
377 span_lint_and_then(cx,
378 WHILE_LET_ON_ITERATOR,
380 "this loop could be written as a `for` loop",
382 db.span_suggestion(expr.span, "try", format!("for {} in {} {{ .. }}", loop_var, iterator));
389 fn check_stmt(&mut self, cx: &LateContext<'a, 'tcx>, stmt: &'tcx Stmt) {
390 if let StmtSemi(ref expr, _) = stmt.node {
391 if let ExprMethodCall(ref method, _, ref args) = expr.node {
392 if args.len() == 1 && &*method.node.as_str() == "collect" &&
393 match_trait_method(cx, expr, &paths::ITERATOR) {
397 "you are collect()ing an iterator and throwing away the result. \
398 Consider using an explicit for loop to exhaust the iterator");
405 fn check_for_loop<'a, 'tcx>(
406 cx: &LateContext<'a, 'tcx>,
412 check_for_loop_range(cx, pat, arg, body, expr);
413 check_for_loop_reverse_range(cx, arg, expr);
414 check_for_loop_arg(cx, pat, arg, expr);
415 check_for_loop_explicit_counter(cx, arg, body, expr);
416 check_for_loop_over_map_kv(cx, pat, arg, body, expr);
419 /// Check for looping over a range and then indexing a sequence with it.
420 /// The iteratee must be a range literal.
421 fn check_for_loop_range<'a, 'tcx>(
422 cx: &LateContext<'a, 'tcx>,
428 if let Some(higher::Range { start: Some(start), ref end, limits }) = higher::range(arg) {
429 // the var must be a single name
430 if let PatKind::Binding(_, def_id, ref ident, _) = pat.node {
431 let mut visitor = VarVisitor {
434 indexed: HashMap::new(),
437 walk_expr(&mut visitor, body);
439 // linting condition: we only indexed one variable
440 if visitor.indexed.len() == 1 {
441 let (indexed, indexed_extent) = visitor.indexed
444 .unwrap_or_else(|| unreachable!() /* len == 1 */);
446 // ensure that the indexed variable was declared before the loop, see #601
447 if let Some(indexed_extent) = indexed_extent {
448 let pat_extent = cx.tcx.region_maps.var_scope(pat.id);
449 if cx.tcx.region_maps.is_subscope_of(indexed_extent, pat_extent) {
454 let starts_at_zero = is_integer_literal(start, 0);
456 let skip = if starts_at_zero {
459 format!(".skip({})", snippet(cx, start.span, ".."))
462 let take = if let Some(end) = *end {
463 if is_len_call(end, &indexed) {
467 ast::RangeLimits::Closed => {
468 let end = sugg::Sugg::hir(cx, end, "<count>");
469 format!(".take({})", end + sugg::ONE)
471 ast::RangeLimits::HalfOpen => format!(".take({})", snippet(cx, end.span, "..")),
478 if visitor.nonindex {
479 span_lint_and_then(cx,
482 &format!("the loop variable `{}` is used to index `{}`", ident.node, indexed),
485 "consider using an iterator".to_string(),
486 &[(pat.span, &format!("({}, <item>)", ident.node)),
487 (arg.span, &format!("{}.iter().enumerate(){}{}", indexed, take, skip))]);
490 let repl = if starts_at_zero && take.is_empty() {
491 format!("&{}", indexed)
493 format!("{}.iter(){}{}", indexed, take, skip)
496 span_lint_and_then(cx,
499 &format!("the loop variable `{}` is only used to index `{}`.",
504 "consider using an iterator".to_string(),
505 &[(pat.span, "<item>"), (arg.span, &repl)]);
513 fn is_len_call(expr: &Expr, var: &Name) -> bool {
515 let ExprMethodCall(method, _, ref len_args) = expr.node,
517 &*method.node.as_str() == "len",
518 let ExprPath(QPath::Resolved(_, ref path)) = len_args[0].node,
519 path.segments.len() == 1,
520 &path.segments[0].name == var
528 fn check_for_loop_reverse_range(cx: &LateContext, arg: &Expr, expr: &Expr) {
529 // if this for loop is iterating over a two-sided range...
530 if let Some(higher::Range { start: Some(start), end: Some(end), limits }) = higher::range(arg) {
531 // ...and both sides are compile-time constant integers...
532 let constcx = ConstContext::with_tables(cx.tcx, cx.tables);
533 if let Ok(start_idx) = constcx.eval(start, ExprTypeChecked) {
534 if let Ok(end_idx) = constcx.eval(end, ExprTypeChecked) {
535 // ...and the start index is greater than the end index,
536 // this loop will never run. This is often confusing for developers
537 // who think that this will iterate from the larger value to the
539 let (sup, eq) = match (start_idx, end_idx) {
540 (ConstVal::Integral(start_idx), ConstVal::Integral(end_idx)) => {
541 (start_idx > end_idx, start_idx == end_idx)
547 let start_snippet = snippet(cx, start.span, "_");
548 let end_snippet = snippet(cx, end.span, "_");
549 let dots = if limits == ast::RangeLimits::Closed {
555 span_lint_and_then(cx,
558 "this range is empty so this for loop will never run",
560 db.span_suggestion(arg.span,
561 "consider using the following if you are attempting to iterate over this \
563 format!("({end}{dots}{start}).rev()",
566 start = start_snippet));
568 } else if eq && limits != ast::RangeLimits::Closed {
569 // if they are equal, it's also problematic - this loop
574 "this range is empty so this for loop will never run");
581 fn check_for_loop_arg(cx: &LateContext, pat: &Pat, arg: &Expr, expr: &Expr) {
582 let mut next_loop_linted = false; // whether or not ITER_NEXT_LOOP lint was used
583 if let ExprMethodCall(ref method, _, ref args) = arg.node {
584 // just the receiver, no arguments
586 let method_name = method.node;
587 // check for looping over x.iter() or x.iter_mut(), could use &x or &mut x
588 if &*method_name.as_str() == "iter" || &*method_name.as_str() == "iter_mut" {
589 if is_ref_iterable_type(cx, &args[0]) {
590 let object = snippet(cx, args[0].span, "_");
591 let suggestion = format!("&{}{}",
592 if &*method_name.as_str() == "iter_mut" {
598 span_lint_and_then(cx,
601 &format!("it is more idiomatic to loop over `{}` instead of `{}.{}()`",
606 db.span_suggestion(arg.span, "to write this more concisely, try looping over", suggestion);
609 } else if &*method_name.as_str() == "into_iter" && match_trait_method(cx, arg, &paths::INTO_ITERATOR) {
610 let object = snippet(cx, args[0].span, "_");
611 span_lint_and_then(cx,
612 EXPLICIT_INTO_ITER_LOOP,
614 &format!("it is more idiomatic to loop over `{}` instead of `{}.{}()`",
619 db.span_suggestion(arg.span,
620 "to write this more concisely, try looping over",
624 } else if &*method_name.as_str() == "next" && match_trait_method(cx, arg, &paths::ITERATOR) {
628 "you are iterating over `Iterator::next()` which is an Option; this will compile but is \
629 probably not what you want");
630 next_loop_linted = true;
634 if !next_loop_linted {
635 check_arg_type(cx, pat, arg);
639 /// Check for `for` loops over `Option`s and `Results`
640 fn check_arg_type(cx: &LateContext, pat: &Pat, arg: &Expr) {
641 let ty = cx.tables.expr_ty(arg);
642 if match_type(cx, ty, &paths::OPTION) {
643 span_help_and_lint(cx,
644 FOR_LOOP_OVER_OPTION,
646 &format!("for loop over `{0}`, which is an `Option`. This is more readably written as an \
647 `if let` statement.",
648 snippet(cx, arg.span, "_")),
649 &format!("consider replacing `for {0} in {1}` with `if let Some({0}) = {1}`",
650 snippet(cx, pat.span, "_"),
651 snippet(cx, arg.span, "_")));
652 } else if match_type(cx, ty, &paths::RESULT) {
653 span_help_and_lint(cx,
654 FOR_LOOP_OVER_RESULT,
656 &format!("for loop over `{0}`, which is a `Result`. This is more readably written as an \
657 `if let` statement.",
658 snippet(cx, arg.span, "_")),
659 &format!("consider replacing `for {0} in {1}` with `if let Ok({0}) = {1}`",
660 snippet(cx, pat.span, "_"),
661 snippet(cx, arg.span, "_")));
665 fn check_for_loop_explicit_counter<'a, 'tcx>(
666 cx: &LateContext<'a, 'tcx>,
671 // Look for variables that are incremented once per loop iteration.
672 let mut visitor = IncrementVisitor {
674 states: HashMap::new(),
678 walk_expr(&mut visitor, body);
680 // For each candidate, check the parent block to see if
681 // it's initialized to zero at the start of the loop.
682 let map = &cx.tcx.map;
683 let parent_scope = map.get_enclosing_scope(expr.id).and_then(|id| map.get_enclosing_scope(id));
684 if let Some(parent_id) = parent_scope {
685 if let NodeBlock(block) = map.get(parent_id) {
686 for (id, _) in visitor.states.iter().filter(|&(_, v)| *v == VarState::IncrOnce) {
687 let mut visitor2 = InitializeVisitor {
691 state: VarState::IncrOnce,
696 walk_block(&mut visitor2, block);
698 if visitor2.state == VarState::Warn {
699 if let Some(name) = visitor2.name {
701 EXPLICIT_COUNTER_LOOP,
703 &format!("the variable `{0}` is used as a loop counter. Consider using `for ({0}, \
704 item) in {1}.enumerate()` or similar iterators",
706 snippet(cx, arg.span, "_")));
714 /// Check for the `FOR_KV_MAP` lint.
715 fn check_for_loop_over_map_kv<'a, 'tcx>(
716 cx: &LateContext<'a, 'tcx>,
722 let pat_span = pat.span;
724 if let PatKind::Tuple(ref pat, _) = pat.node {
726 let arg_span = arg.span;
727 let (new_pat_span, kind, ty, mutbl) = match cx.tables.expr_ty(arg).sty {
728 ty::TyRef(_, ref tam) => {
729 match (&pat[0].node, &pat[1].node) {
730 (key, _) if pat_is_wild(cx, key, body) => (pat[1].span, "value", tam.ty, tam.mutbl),
731 (_, value) if pat_is_wild(cx, value, body) => (pat[0].span, "key", tam.ty, MutImmutable),
737 let mutbl = match mutbl {
739 MutMutable => "_mut",
741 let arg = match arg.node {
742 ExprAddrOf(_, ref expr) => &**expr,
746 if match_type(cx, ty, &paths::HASHMAP) || match_type(cx, ty, &paths::BTREEMAP) {
747 span_lint_and_then(cx,
750 &format!("you seem to want to iterate on a map's {}s", kind),
752 let map = sugg::Sugg::hir(cx, arg, "map");
754 "use the corresponding method".into(),
755 &[(pat_span, &snippet(cx, new_pat_span, kind)),
756 (arg_span, &format!("{}.{}s{}()", map.maybe_par(), kind, mutbl))]);
764 /// Return true if the pattern is a `PatWild` or an ident prefixed with `'_'`.
765 fn pat_is_wild<'a, 'tcx: 'a>(cx: &LateContext<'a, 'tcx>, pat: &'tcx PatKind, body: &'tcx Expr) -> bool {
767 PatKind::Wild => true,
768 PatKind::Binding(_, _, ident, None) if ident.node.as_str().starts_with('_') => {
769 let mut visitor = UsedVisitor {
774 walk_expr(&mut visitor, body);
781 struct UsedVisitor<'a, 'tcx: 'a> {
782 var: ast::Name, // var to look for
783 used: bool, // has the var been used otherwise?
784 cx: &'a LateContext<'a, 'tcx>,
787 impl<'a, 'tcx: 'a> Visitor<'tcx> for UsedVisitor<'a, 'tcx> {
788 fn visit_expr(&mut self, expr: &'tcx Expr) {
789 if let ExprPath(QPath::Resolved(None, ref path)) = expr.node {
790 if path.segments.len() == 1 && path.segments[0].name == self.var {
796 walk_expr(self, expr);
798 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
799 NestedVisitorMap::All(&self.cx.tcx.map)
803 struct VarVisitor<'a, 'tcx: 'a> {
804 cx: &'a LateContext<'a, 'tcx>, // context reference
805 var: DefId, // var name to look for as index
806 indexed: HashMap<Name, Option<CodeExtent>>, // indexed variables, the extent is None for global
807 nonindex: bool, // has the var been used otherwise?
810 impl<'a, 'tcx> Visitor<'tcx> for VarVisitor<'a, 'tcx> {
811 fn visit_expr(&mut self, expr: &'tcx Expr) {
812 if let ExprPath(ref qpath) = expr.node {
813 if let QPath::Resolved(None, ref path) = *qpath {
814 if path.segments.len() == 1 && self.cx.tables.qpath_def(qpath, expr.id).def_id() == self.var {
815 // we are referencing our variable! now check if it's as an index
817 let Some(parexpr) = get_parent_expr(self.cx, expr),
818 let ExprIndex(ref seqexpr, _) = parexpr.node,
819 let ExprPath(ref seqpath) = seqexpr.node,
820 let QPath::Resolved(None, ref seqvar) = *seqpath,
821 seqvar.segments.len() == 1
823 let def = self.cx.tables.qpath_def(seqpath, seqexpr.id);
825 Def::Local(..) | Def::Upvar(..) => {
826 let def_id = def.def_id();
827 let node_id = self.cx.tcx.map.as_local_node_id(def_id).unwrap();
829 let extent = self.cx.tcx.region_maps.var_scope(node_id);
830 self.indexed.insert(seqvar.segments[0].name, Some(extent));
831 return; // no need to walk further
833 Def::Static(..) | Def::Const(..) => {
834 self.indexed.insert(seqvar.segments[0].name, None);
835 return; // no need to walk further
840 // we are not indexing anything, record that
841 self.nonindex = true;
846 walk_expr(self, expr);
848 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
849 NestedVisitorMap::All(&self.cx.tcx.map)
853 fn is_iterator_used_after_while_let<'a, 'tcx: 'a>(cx: &LateContext<'a, 'tcx>, iter_expr: &'tcx Expr) -> bool {
854 let def_id = match var_def_id(cx, iter_expr) {
856 None => return false,
858 let mut visitor = VarUsedAfterLoopVisitor {
861 iter_expr_id: iter_expr.id,
862 past_while_let: false,
863 var_used_after_while_let: false,
865 if let Some(enclosing_block) = get_enclosing_block(cx, def_id) {
866 walk_block(&mut visitor, enclosing_block);
868 visitor.var_used_after_while_let
871 struct VarUsedAfterLoopVisitor<'a, 'tcx: 'a> {
872 cx: &'a LateContext<'a, 'tcx>,
874 iter_expr_id: NodeId,
875 past_while_let: bool,
876 var_used_after_while_let: bool,
879 impl<'a, 'tcx> Visitor<'tcx> for VarUsedAfterLoopVisitor<'a, 'tcx> {
880 fn visit_expr(&mut self, expr: &'tcx Expr) {
881 if self.past_while_let {
882 if Some(self.def_id) == var_def_id(self.cx, expr) {
883 self.var_used_after_while_let = true;
885 } else if self.iter_expr_id == expr.id {
886 self.past_while_let = true;
888 walk_expr(self, expr);
890 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
891 NestedVisitorMap::All(&self.cx.tcx.map)
896 /// Return true if the type of expr is one that provides `IntoIterator` impls
897 /// for `&T` and `&mut T`, such as `Vec`.
898 #[cfg_attr(rustfmt, rustfmt_skip)]
899 fn is_ref_iterable_type(cx: &LateContext, e: &Expr) -> bool {
900 // no walk_ptrs_ty: calling iter() on a reference can make sense because it
901 // will allow further borrows afterwards
902 let ty = cx.tables.expr_ty(e);
903 is_iterable_array(ty) ||
904 match_type(cx, ty, &paths::VEC) ||
905 match_type(cx, ty, &paths::LINKED_LIST) ||
906 match_type(cx, ty, &paths::HASHMAP) ||
907 match_type(cx, ty, &paths::HASHSET) ||
908 match_type(cx, ty, &paths::VEC_DEQUE) ||
909 match_type(cx, ty, &paths::BINARY_HEAP) ||
910 match_type(cx, ty, &paths::BTREEMAP) ||
911 match_type(cx, ty, &paths::BTREESET)
914 fn is_iterable_array(ty: ty::Ty) -> bool {
915 // IntoIterator is currently only implemented for array sizes <= 32 in rustc
917 ty::TyArray(_, 0...32) => true,
922 /// If a block begins with a statement (possibly a `let` binding) and has an expression, return it.
923 fn extract_expr_from_first_stmt(block: &Block) -> Option<&Expr> {
924 if block.stmts.is_empty() {
927 if let StmtDecl(ref decl, _) = block.stmts[0].node {
928 if let DeclLocal(ref local) = decl.node {
929 if let Some(ref expr) = local.init {
942 /// If a block begins with an expression (with or without semicolon), return it.
943 fn extract_first_expr(block: &Block) -> Option<&Expr> {
945 Some(ref expr) if block.stmts.is_empty() => Some(expr),
946 None if !block.stmts.is_empty() => {
947 match block.stmts[0].node {
948 StmtExpr(ref expr, _) |
949 StmtSemi(ref expr, _) => Some(expr),
950 StmtDecl(..) => None,
957 /// Return true if expr contains a single break expr (maybe within a block).
958 fn is_break_expr(expr: &Expr) -> bool {
960 ExprBreak(None, _) => true,
961 ExprBlock(ref b) => {
962 match extract_first_expr(b) {
963 Some(subexpr) => is_break_expr(subexpr),
971 // To trigger the EXPLICIT_COUNTER_LOOP lint, a variable must be
972 // incremented exactly once in the loop body, and initialized to zero
973 // at the start of the loop.
976 Initial, // Not examined yet
977 IncrOnce, // Incremented exactly once, may be a loop counter
978 Declared, // Declared but not (yet) initialized to zero
983 /// Scan a for loop for variables that are incremented exactly once.
984 struct IncrementVisitor<'a, 'tcx: 'a> {
985 cx: &'a LateContext<'a, 'tcx>, // context reference
986 states: HashMap<NodeId, VarState>, // incremented variables
987 depth: u32, // depth of conditional expressions
991 impl<'a, 'tcx> Visitor<'tcx> for IncrementVisitor<'a, 'tcx> {
992 fn visit_expr(&mut self, expr: &'tcx Expr) {
997 // If node is a variable
998 if let Some(def_id) = var_def_id(self.cx, expr) {
999 if let Some(parent) = get_parent_expr(self.cx, expr) {
1000 let state = self.states.entry(def_id).or_insert(VarState::Initial);
1003 ExprAssignOp(op, ref lhs, ref rhs) => {
1004 if lhs.id == expr.id {
1005 if op.node == BiAdd && is_integer_literal(rhs, 1) {
1006 *state = match *state {
1007 VarState::Initial if self.depth == 0 => VarState::IncrOnce,
1008 _ => VarState::DontWarn,
1011 // Assigned some other value
1012 *state = VarState::DontWarn;
1016 ExprAssign(ref lhs, _) if lhs.id == expr.id => *state = VarState::DontWarn,
1017 ExprAddrOf(mutability, _) if mutability == MutMutable => *state = VarState::DontWarn,
1021 } else if is_loop(expr) {
1022 self.states.clear();
1025 } else if is_conditional(expr) {
1027 walk_expr(self, expr);
1031 walk_expr(self, expr);
1033 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1034 NestedVisitorMap::All(&self.cx.tcx.map)
1038 /// Check whether a variable is initialized to zero at the start of a loop.
1039 struct InitializeVisitor<'a, 'tcx: 'a> {
1040 cx: &'a LateContext<'a, 'tcx>, // context reference
1041 end_expr: &'tcx Expr, // the for loop. Stop scanning here.
1045 depth: u32, // depth of conditional expressions
1049 impl<'a, 'tcx> Visitor<'tcx> for InitializeVisitor<'a, 'tcx> {
1050 fn visit_decl(&mut self, decl: &'tcx Decl) {
1051 // Look for declarations of the variable
1052 if let DeclLocal(ref local) = decl.node {
1053 if local.pat.id == self.var_id {
1054 if let PatKind::Binding(_, _, ref ident, _) = local.pat.node {
1055 self.name = Some(ident.node);
1057 self.state = if let Some(ref init) = local.init {
1058 if is_integer_literal(init, 0) {
1069 walk_decl(self, decl);
1072 fn visit_expr(&mut self, expr: &'tcx Expr) {
1073 if self.state == VarState::DontWarn {
1076 if expr == self.end_expr {
1077 self.past_loop = true;
1080 // No need to visit expressions before the variable is
1082 if self.state == VarState::IncrOnce {
1086 // If node is the desired variable, see how it's used
1087 if var_def_id(self.cx, expr) == Some(self.var_id) {
1088 if let Some(parent) = get_parent_expr(self.cx, expr) {
1090 ExprAssignOp(_, ref lhs, _) if lhs.id == expr.id => {
1091 self.state = VarState::DontWarn;
1093 ExprAssign(ref lhs, ref rhs) if lhs.id == expr.id => {
1094 self.state = if is_integer_literal(rhs, 0) && self.depth == 0 {
1100 ExprAddrOf(mutability, _) if mutability == MutMutable => self.state = VarState::DontWarn,
1106 self.state = VarState::DontWarn;
1109 } else if !self.past_loop && is_loop(expr) {
1110 self.state = VarState::DontWarn;
1112 } else if is_conditional(expr) {
1114 walk_expr(self, expr);
1118 walk_expr(self, expr);
1120 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1121 NestedVisitorMap::All(&self.cx.tcx.map)
1125 fn var_def_id(cx: &LateContext, expr: &Expr) -> Option<NodeId> {
1126 if let ExprPath(ref qpath) = expr.node {
1127 let path_res = cx.tables.qpath_def(qpath, expr.id);
1128 if let Def::Local(def_id) = path_res {
1129 let node_id = cx.tcx.map.as_local_node_id(def_id).expect("That DefId should be valid");
1130 return Some(node_id);
1136 fn is_loop(expr: &Expr) -> bool {
1138 ExprLoop(..) | ExprWhile(..) => true,
1143 fn is_conditional(expr: &Expr) -> bool {
1145 ExprIf(..) | ExprMatch(..) => true,