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::eval_const_expr_partial;
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,
19 walk_ptrs_ty, last_path_segment};
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,
384 format!("for {} in {} {{ .. }}", loop_var, iterator));
391 fn check_stmt(&mut self, cx: &LateContext<'a, 'tcx>, stmt: &'tcx Stmt) {
392 if let StmtSemi(ref expr, _) = stmt.node {
393 if let ExprMethodCall(ref method, _, ref args) = expr.node {
394 if args.len() == 1 && &*method.node.as_str() == "collect" &&
395 match_trait_method(cx, expr, &paths::ITERATOR) {
399 "you are collect()ing an iterator and throwing away the result. \
400 Consider using an explicit for loop to exhaust the iterator");
407 fn check_for_loop<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, pat: &'tcx Pat, arg: &'tcx Expr, body: &'tcx Expr,
409 check_for_loop_range(cx, pat, arg, body, expr);
410 check_for_loop_reverse_range(cx, arg, expr);
411 check_for_loop_arg(cx, pat, arg, expr);
412 check_for_loop_explicit_counter(cx, arg, body, expr);
413 check_for_loop_over_map_kv(cx, pat, arg, body, expr);
416 /// Check for looping over a range and then indexing a sequence with it.
417 /// The iteratee must be a range literal.
418 fn check_for_loop_range<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, pat: &'tcx Pat, arg: &'tcx Expr, body: &'tcx Expr,
420 if let Some(higher::Range { start: Some(start), ref end, limits }) = higher::range(arg) {
421 // the var must be a single name
422 if let PatKind::Binding(_, def_id, ref ident, _) = pat.node {
423 let mut visitor = VarVisitor {
426 indexed: HashMap::new(),
429 walk_expr(&mut visitor, body);
431 // linting condition: we only indexed one variable
432 if visitor.indexed.len() == 1 {
433 let (indexed, indexed_extent) = visitor.indexed
436 .unwrap_or_else(|| unreachable!() /* len == 1 */);
438 // ensure that the indexed variable was declared before the loop, see #601
439 if let Some(indexed_extent) = indexed_extent {
440 let pat_extent = cx.tcx.region_maps.var_scope(pat.id);
441 if cx.tcx.region_maps.is_subscope_of(indexed_extent, pat_extent) {
446 let starts_at_zero = is_integer_literal(start, 0);
448 let skip = if starts_at_zero {
451 format!(".skip({})", snippet(cx, start.span, ".."))
454 let take = if let Some(end) = *end {
455 if is_len_call(end, &indexed) {
459 ast::RangeLimits::Closed => {
460 let end = sugg::Sugg::hir(cx, end, "<count>");
461 format!(".take({})", end + sugg::ONE)
463 ast::RangeLimits::HalfOpen => format!(".take({})", snippet(cx, end.span, "..")),
470 if visitor.nonindex {
471 span_lint_and_then(cx,
474 &format!("the loop variable `{}` is used to index `{}`", ident.node, indexed),
477 "consider using an iterator".to_string(),
478 &[(pat.span, &format!("({}, <item>)", ident.node)),
479 (arg.span, &format!("{}.iter().enumerate(){}{}", indexed, take, skip))]);
482 let repl = if starts_at_zero && take.is_empty() {
483 format!("&{}", indexed)
485 format!("{}.iter(){}{}", indexed, take, skip)
488 span_lint_and_then(cx,
491 &format!("the loop variable `{}` is only used to index `{}`.",
496 "consider using an iterator".to_string(),
497 &[(pat.span, "<item>"), (arg.span, &repl)]);
505 fn is_len_call(expr: &Expr, var: &Name) -> bool {
507 let ExprMethodCall(method, _, ref len_args) = expr.node,
509 &*method.node.as_str() == "len",
510 let ExprPath(QPath::Resolved(_, ref path)) = len_args[0].node,
511 path.segments.len() == 1,
512 &path.segments[0].name == var
520 fn check_for_loop_reverse_range(cx: &LateContext, arg: &Expr, expr: &Expr) {
521 // if this for loop is iterating over a two-sided range...
522 if let Some(higher::Range { start: Some(start), end: Some(end), limits }) = higher::range(arg) {
523 // ...and both sides are compile-time constant integers...
524 if let Ok(start_idx) = eval_const_expr_partial(cx.tcx, start, ExprTypeChecked, None) {
525 if let Ok(end_idx) = eval_const_expr_partial(cx.tcx, end, ExprTypeChecked, None) {
526 // ...and the start index is greater than the end index,
527 // this loop will never run. This is often confusing for developers
528 // who think that this will iterate from the larger value to the
530 let (sup, eq) = match (start_idx, end_idx) {
531 (ConstVal::Integral(start_idx), ConstVal::Integral(end_idx)) => {
532 (start_idx > end_idx, start_idx == end_idx)
538 let start_snippet = snippet(cx, start.span, "_");
539 let end_snippet = snippet(cx, end.span, "_");
540 let dots = if limits == ast::RangeLimits::Closed {
546 span_lint_and_then(cx,
549 "this range is empty so this for loop will never run",
551 db.span_suggestion(arg.span,
552 "consider using the following if you are attempting to iterate over this \
554 format!("({end}{dots}{start}).rev()",
557 start = start_snippet));
559 } else if eq && limits != ast::RangeLimits::Closed {
560 // if they are equal, it's also problematic - this loop
565 "this range is empty so this for loop will never run");
572 fn check_for_loop_arg(cx: &LateContext, pat: &Pat, arg: &Expr, expr: &Expr) {
573 let mut next_loop_linted = false; // whether or not ITER_NEXT_LOOP lint was used
574 if let ExprMethodCall(ref method, _, ref args) = arg.node {
575 // just the receiver, no arguments
577 let method_name = method.node;
578 // check for looping over x.iter() or x.iter_mut(), could use &x or &mut x
579 if &*method_name.as_str() == "iter" || &*method_name.as_str() == "iter_mut" {
580 if is_ref_iterable_type(cx, &args[0]) {
581 let object = snippet(cx, args[0].span, "_");
585 &format!("it is more idiomatic to loop over `&{}{}` instead of `{}.{}()`",
586 if &*method_name.as_str() == "iter_mut" {
595 } else if &*method_name.as_str() == "into_iter" && match_trait_method(cx, arg, &paths::INTO_ITERATOR) {
596 let object = snippet(cx, args[0].span, "_");
598 EXPLICIT_INTO_ITER_LOOP,
600 &format!("it is more idiomatic to loop over `{}` instead of `{}.{}()`",
605 } else if &*method_name.as_str() == "next" && match_trait_method(cx, arg, &paths::ITERATOR) {
609 "you are iterating over `Iterator::next()` which is an Option; this will compile but is \
610 probably not what you want");
611 next_loop_linted = true;
615 if !next_loop_linted {
616 check_arg_type(cx, pat, arg);
620 /// Check for `for` loops over `Option`s and `Results`
621 fn check_arg_type(cx: &LateContext, pat: &Pat, arg: &Expr) {
622 let ty = cx.tcx.tables().expr_ty(arg);
623 if match_type(cx, ty, &paths::OPTION) {
624 span_help_and_lint(cx,
625 FOR_LOOP_OVER_OPTION,
627 &format!("for loop over `{0}`, which is an `Option`. This is more readably written as an \
628 `if let` statement.",
629 snippet(cx, arg.span, "_")),
630 &format!("consider replacing `for {0} in {1}` with `if let Some({0}) = {1}`",
631 snippet(cx, pat.span, "_"),
632 snippet(cx, arg.span, "_")));
633 } else if match_type(cx, ty, &paths::RESULT) {
634 span_help_and_lint(cx,
635 FOR_LOOP_OVER_RESULT,
637 &format!("for loop over `{0}`, which is a `Result`. This is more readably written as an \
638 `if let` statement.",
639 snippet(cx, arg.span, "_")),
640 &format!("consider replacing `for {0} in {1}` with `if let Ok({0}) = {1}`",
641 snippet(cx, pat.span, "_"),
642 snippet(cx, arg.span, "_")));
646 fn check_for_loop_explicit_counter<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, arg: &'tcx Expr, body: &'tcx Expr,
648 // Look for variables that are incremented once per loop iteration.
649 let mut visitor = IncrementVisitor {
651 states: HashMap::new(),
655 walk_expr(&mut visitor, body);
657 // For each candidate, check the parent block to see if
658 // it's initialized to zero at the start of the loop.
659 let map = &cx.tcx.map;
660 let parent_scope = map.get_enclosing_scope(expr.id).and_then(|id| map.get_enclosing_scope(id));
661 if let Some(parent_id) = parent_scope {
662 if let NodeBlock(block) = map.get(parent_id) {
663 for (id, _) in visitor.states.iter().filter(|&(_, v)| *v == VarState::IncrOnce) {
664 let mut visitor2 = InitializeVisitor {
668 state: VarState::IncrOnce,
673 walk_block(&mut visitor2, block);
675 if visitor2.state == VarState::Warn {
676 if let Some(name) = visitor2.name {
678 EXPLICIT_COUNTER_LOOP,
680 &format!("the variable `{0}` is used as a loop counter. Consider using `for ({0}, \
681 item) in {1}.enumerate()` or similar iterators",
683 snippet(cx, arg.span, "_")));
691 /// Check for the `FOR_KV_MAP` lint.
692 fn check_for_loop_over_map_kv<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, pat: &'tcx Pat, arg: &'tcx Expr,
693 body: &'tcx Expr, expr: &'tcx Expr) {
694 let pat_span = pat.span;
696 if let PatKind::Tuple(ref pat, _) = pat.node {
698 let (new_pat_span, kind) = match (&pat[0].node, &pat[1].node) {
699 (key, _) if pat_is_wild(cx, key, body) => (pat[1].span, "value"),
700 (_, value) if pat_is_wild(cx, value, body) => (pat[0].span, "key"),
704 let (arg_span, arg) = match arg.node {
705 ExprAddrOf(MutImmutable, ref expr) => (arg.span, &**expr),
706 ExprAddrOf(MutMutable, _) => return, // for _ in &mut _, there is no {values,keys}_mut method
707 _ => (arg.span, arg),
710 let ty = walk_ptrs_ty(cx.tcx.tables().expr_ty(arg));
711 if match_type(cx, ty, &paths::HASHMAP) || match_type(cx, ty, &paths::BTREEMAP) {
712 span_lint_and_then(cx,
715 &format!("you seem to want to iterate on a map's {}s", kind),
717 let map = sugg::Sugg::hir(cx, arg, "map");
719 "use the corresponding method".into(),
720 &[(pat_span, &snippet(cx, new_pat_span, kind)),
721 (arg_span, &format!("{}.{}s()", map.maybe_par(), kind))]);
729 /// Return true if the pattern is a `PatWild` or an ident prefixed with `'_'`.
730 fn pat_is_wild<'a, 'tcx: 'a>(cx: &LateContext<'a, 'tcx>, pat: &'tcx PatKind, body: &'tcx Expr) -> bool {
732 PatKind::Wild => true,
733 PatKind::Binding(_, _, ident, None) if ident.node.as_str().starts_with('_') => {
734 let mut visitor = UsedVisitor {
739 walk_expr(&mut visitor, body);
746 struct UsedVisitor<'a, 'tcx: 'a> {
747 var: ast::Name, // var to look for
748 used: bool, // has the var been used otherwise?
749 cx: &'a LateContext<'a, 'tcx>,
752 impl<'a, 'tcx: 'a> Visitor<'tcx> for UsedVisitor<'a, 'tcx> {
753 fn visit_expr(&mut self, expr: &'tcx Expr) {
754 if let ExprPath(QPath::Resolved(None, ref path)) = expr.node {
755 if path.segments.len() == 1 && path.segments[0].name == self.var {
761 walk_expr(self, expr);
763 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
764 NestedVisitorMap::All(&self.cx.tcx.map)
768 struct VarVisitor<'a, 'tcx: 'a> {
769 cx: &'a LateContext<'a, 'tcx>, // context reference
770 var: DefId, // var name to look for as index
771 indexed: HashMap<Name, Option<CodeExtent>>, // indexed variables, the extent is None for global
772 nonindex: bool, // has the var been used otherwise?
775 impl<'a, 'tcx> Visitor<'tcx> for VarVisitor<'a, 'tcx> {
776 fn visit_expr(&mut self, expr: &'tcx Expr) {
777 if let ExprPath(ref qpath) = expr.node {
778 if let QPath::Resolved(None, ref path) = *qpath {
779 if path.segments.len() == 1 && self.cx.tcx.tables().qpath_def(qpath, expr.id).def_id() == self.var {
780 // we are referencing our variable! now check if it's as an index
782 let Some(parexpr) = get_parent_expr(self.cx, expr),
783 let ExprIndex(ref seqexpr, _) = parexpr.node,
784 let ExprPath(ref seqpath) = seqexpr.node,
785 let QPath::Resolved(None, ref seqvar) = *seqpath,
786 seqvar.segments.len() == 1
788 let def = self.cx.tcx.tables().qpath_def(seqpath, seqexpr.id);
790 Def::Local(..) | Def::Upvar(..) => {
791 let def_id = def.def_id();
792 let node_id = self.cx.tcx.map.as_local_node_id(def_id).unwrap();
794 let extent = self.cx.tcx.region_maps.var_scope(node_id);
795 self.indexed.insert(seqvar.segments[0].name, Some(extent));
796 return; // no need to walk further
798 Def::Static(..) | Def::Const(..) => {
799 self.indexed.insert(seqvar.segments[0].name, None);
800 return; // no need to walk further
805 // we are not indexing anything, record that
806 self.nonindex = true;
811 walk_expr(self, expr);
813 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
814 NestedVisitorMap::All(&self.cx.tcx.map)
818 fn is_iterator_used_after_while_let<'a, 'tcx: 'a>(cx: &LateContext<'a, 'tcx>, iter_expr: &'tcx Expr) -> bool {
819 let def_id = match var_def_id(cx, iter_expr) {
821 None => return false,
823 let mut visitor = VarUsedAfterLoopVisitor {
826 iter_expr_id: iter_expr.id,
827 past_while_let: false,
828 var_used_after_while_let: false,
830 if let Some(enclosing_block) = get_enclosing_block(cx, def_id) {
831 walk_block(&mut visitor, enclosing_block);
833 visitor.var_used_after_while_let
836 struct VarUsedAfterLoopVisitor<'a, 'tcx: 'a> {
837 cx: &'a LateContext<'a, 'tcx>,
839 iter_expr_id: NodeId,
840 past_while_let: bool,
841 var_used_after_while_let: bool,
844 impl<'a, 'tcx> Visitor<'tcx> for VarUsedAfterLoopVisitor<'a, 'tcx> {
845 fn visit_expr(&mut self, expr: &'tcx Expr) {
846 if self.past_while_let {
847 if Some(self.def_id) == var_def_id(self.cx, expr) {
848 self.var_used_after_while_let = true;
850 } else if self.iter_expr_id == expr.id {
851 self.past_while_let = true;
853 walk_expr(self, expr);
855 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
856 NestedVisitorMap::All(&self.cx.tcx.map)
861 /// Return true if the type of expr is one that provides `IntoIterator` impls
862 /// for `&T` and `&mut T`, such as `Vec`.
863 #[cfg_attr(rustfmt, rustfmt_skip)]
864 fn is_ref_iterable_type(cx: &LateContext, e: &Expr) -> bool {
865 // no walk_ptrs_ty: calling iter() on a reference can make sense because it
866 // will allow further borrows afterwards
867 let ty = cx.tcx.tables().expr_ty(e);
868 is_iterable_array(ty) ||
869 match_type(cx, ty, &paths::VEC) ||
870 match_type(cx, ty, &paths::LINKED_LIST) ||
871 match_type(cx, ty, &paths::HASHMAP) ||
872 match_type(cx, ty, &paths::HASHSET) ||
873 match_type(cx, ty, &paths::VEC_DEQUE) ||
874 match_type(cx, ty, &paths::BINARY_HEAP) ||
875 match_type(cx, ty, &paths::BTREEMAP) ||
876 match_type(cx, ty, &paths::BTREESET)
879 fn is_iterable_array(ty: ty::Ty) -> bool {
880 // IntoIterator is currently only implemented for array sizes <= 32 in rustc
882 ty::TyArray(_, 0...32) => true,
887 /// If a block begins with a statement (possibly a `let` binding) and has an expression, return it.
888 fn extract_expr_from_first_stmt(block: &Block) -> Option<&Expr> {
889 if block.stmts.is_empty() {
892 if let StmtDecl(ref decl, _) = block.stmts[0].node {
893 if let DeclLocal(ref local) = decl.node {
894 if let Some(ref expr) = local.init {
907 /// If a block begins with an expression (with or without semicolon), return it.
908 fn extract_first_expr(block: &Block) -> Option<&Expr> {
910 Some(ref expr) if block.stmts.is_empty() => Some(expr),
911 None if !block.stmts.is_empty() => {
912 match block.stmts[0].node {
913 StmtExpr(ref expr, _) |
914 StmtSemi(ref expr, _) => Some(expr),
915 StmtDecl(..) => None,
922 /// Return true if expr contains a single break expr (maybe within a block).
923 fn is_break_expr(expr: &Expr) -> bool {
925 ExprBreak(None, _) => true,
926 ExprBlock(ref b) => {
927 match extract_first_expr(b) {
928 Some(subexpr) => is_break_expr(subexpr),
936 // To trigger the EXPLICIT_COUNTER_LOOP lint, a variable must be
937 // incremented exactly once in the loop body, and initialized to zero
938 // at the start of the loop.
941 Initial, // Not examined yet
942 IncrOnce, // Incremented exactly once, may be a loop counter
943 Declared, // Declared but not (yet) initialized to zero
948 /// Scan a for loop for variables that are incremented exactly once.
949 struct IncrementVisitor<'a, 'tcx: 'a> {
950 cx: &'a LateContext<'a, 'tcx>, // context reference
951 states: HashMap<NodeId, VarState>, // incremented variables
952 depth: u32, // depth of conditional expressions
956 impl<'a, 'tcx> Visitor<'tcx> for IncrementVisitor<'a, 'tcx> {
957 fn visit_expr(&mut self, expr: &'tcx Expr) {
962 // If node is a variable
963 if let Some(def_id) = var_def_id(self.cx, expr) {
964 if let Some(parent) = get_parent_expr(self.cx, expr) {
965 let state = self.states.entry(def_id).or_insert(VarState::Initial);
968 ExprAssignOp(op, ref lhs, ref rhs) => {
969 if lhs.id == expr.id {
970 if op.node == BiAdd && is_integer_literal(rhs, 1) {
971 *state = match *state {
972 VarState::Initial if self.depth == 0 => VarState::IncrOnce,
973 _ => VarState::DontWarn,
976 // Assigned some other value
977 *state = VarState::DontWarn;
981 ExprAssign(ref lhs, _) if lhs.id == expr.id => *state = VarState::DontWarn,
982 ExprAddrOf(mutability, _) if mutability == MutMutable => *state = VarState::DontWarn,
986 } else if is_loop(expr) {
990 } else if is_conditional(expr) {
992 walk_expr(self, expr);
996 walk_expr(self, expr);
998 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
999 NestedVisitorMap::All(&self.cx.tcx.map)
1003 /// Check whether a variable is initialized to zero at the start of a loop.
1004 struct InitializeVisitor<'a, 'tcx: 'a> {
1005 cx: &'a LateContext<'a, 'tcx>, // context reference
1006 end_expr: &'tcx Expr, // the for loop. Stop scanning here.
1010 depth: u32, // depth of conditional expressions
1014 impl<'a, 'tcx> Visitor<'tcx> for InitializeVisitor<'a, 'tcx> {
1015 fn visit_decl(&mut self, decl: &'tcx Decl) {
1016 // Look for declarations of the variable
1017 if let DeclLocal(ref local) = decl.node {
1018 if local.pat.id == self.var_id {
1019 if let PatKind::Binding(_, _, ref ident, _) = local.pat.node {
1020 self.name = Some(ident.node);
1022 self.state = if let Some(ref init) = local.init {
1023 if is_integer_literal(init, 0) {
1034 walk_decl(self, decl);
1037 fn visit_expr(&mut self, expr: &'tcx Expr) {
1038 if self.state == VarState::DontWarn {
1041 if expr == self.end_expr {
1042 self.past_loop = true;
1045 // No need to visit expressions before the variable is
1047 if self.state == VarState::IncrOnce {
1051 // If node is the desired variable, see how it's used
1052 if var_def_id(self.cx, expr) == Some(self.var_id) {
1053 if let Some(parent) = get_parent_expr(self.cx, expr) {
1055 ExprAssignOp(_, ref lhs, _) if lhs.id == expr.id => {
1056 self.state = VarState::DontWarn;
1058 ExprAssign(ref lhs, ref rhs) if lhs.id == expr.id => {
1059 self.state = if is_integer_literal(rhs, 0) && self.depth == 0 {
1065 ExprAddrOf(mutability, _) if mutability == MutMutable => self.state = VarState::DontWarn,
1071 self.state = VarState::DontWarn;
1074 } else if !self.past_loop && is_loop(expr) {
1075 self.state = VarState::DontWarn;
1077 } else if is_conditional(expr) {
1079 walk_expr(self, expr);
1083 walk_expr(self, expr);
1085 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1086 NestedVisitorMap::All(&self.cx.tcx.map)
1090 fn var_def_id(cx: &LateContext, expr: &Expr) -> Option<NodeId> {
1091 if let ExprPath(ref qpath) = expr.node {
1092 let path_res = cx.tcx.tables().qpath_def(qpath, expr.id);
1093 if let Def::Local(def_id) = path_res {
1094 let node_id = cx.tcx.map.as_local_node_id(def_id).expect("That DefId should be valid");
1095 return Some(node_id);
1101 fn is_loop(expr: &Expr) -> bool {
1103 ExprLoop(..) | ExprWhile(..) => true,
1108 fn is_conditional(expr: &Expr) -> bool {
1110 ExprIf(..) | ExprMatch(..) => true,