2 use rustc_front::hir::*;
4 use rustc_front::intravisit::{Visitor, walk_expr, walk_block, walk_decl};
6 use rustc::middle::def::DefLocal;
7 use consts::{constant_simple, Constant};
8 use rustc::front::map::Node::{NodeBlock};
10 use std::collections::{HashSet,HashMap};
11 use syntax::ast::Lit_::*;
13 use utils::{snippet, span_lint, get_parent_expr, match_trait_method, match_type,
14 in_external_macro, expr_block, span_help_and_lint, is_integer_literal,
16 use utils::{VEC_PATH, LL_PATH};
18 /// **What it does:** This lint checks for looping over the range of `0..len` of some collection just to get the values by index. It is `Warn` by default.
20 /// **Why is this bad?** Just iterating the collection itself makes the intent more clear and is probably faster.
22 /// **Known problems:** None
26 /// for i in 0..vec.len() {
27 /// println!("{}", vec[i]);
30 declare_lint!{ pub NEEDLESS_RANGE_LOOP, Warn,
31 "for-looping over a range of indices where an iterator over items would do" }
33 /// **What it does:** This lint checks for loops on `x.iter()` where `&x` will do, and suggest the latter. It is `Warn` by default.
35 /// **Why is this bad?** Readability.
37 /// **Known problems:** False negatives. We currently only warn on some known types.
39 /// **Example:** `for x in y.iter() { .. }` (where y is a `Vec` or slice)
40 declare_lint!{ pub EXPLICIT_ITER_LOOP, Warn,
41 "for-looping over `_.iter()` or `_.iter_mut()` when `&_` or `&mut _` would do" }
43 /// **What it does:** This lint checks for loops on `x.next()`. It is `Warn` by default.
45 /// **Why is this bad?** `next()` returns either `Some(value)` if there was a value, or `None` otherwise. The insidious thing is that `Option<_>` implements `IntoIterator`, so that possibly one value will be iterated, leading to some hard to find bugs. No one will want to write such code [except to win an Underhanded Rust Contest](https://www.reddit.com/r/rust/comments/3hb0wm/underhanded_rust_contest/cu5yuhr).
47 /// **Known problems:** None
49 /// **Example:** `for x in y.next() { .. }`
50 declare_lint!{ pub ITER_NEXT_LOOP, Warn,
51 "for-looping over `_.next()` which is probably not intended" }
53 /// **What it does:** This lint detects `loop + match` combinations that are easier written as a `while let` loop.
55 /// **Why is this bad?** The `while let` loop is usually shorter and more readable
57 /// **Known problems:** Sometimes the wrong binding is displayed (#383)
67 /// // .. do something with x
69 /// // is easier written as
70 /// while let Some(x) = y {
71 /// // .. do something with x
74 declare_lint!{ pub WHILE_LET_LOOP, Warn,
75 "`loop { if let { ... } else break }` can be written as a `while let` loop" }
77 /// **What it does:** This lint checks for using `collect()` on an iterator without using the result. It is `Warn` by default.
79 /// **Why is this bad?** It is more idiomatic to use a `for` loop over the iterator instead.
81 /// **Known problems:** None
83 /// **Example:** `vec.iter().map(|x| /* some operation returning () */).collect::<Vec<_>>();`
84 declare_lint!{ pub UNUSED_COLLECT, Warn,
85 "`collect()`ing an iterator without using the result; this is usually better \
86 written as a for loop" }
88 /// **What it does:** This lint checks for loops over ranges `x..y` where both `x` and `y` are constant and `x` is greater or equal to `y`, unless the range is reversed or has a negative `.step_by(_)`.
90 /// **Why is it bad?** Such loops will either be skipped or loop until wrap-around (in debug code, this may `panic!()`). Both options are probably not intended.
92 /// **Known problems:** The lint cannot catch loops over dynamically defined ranges. Doing this would require simulating all possible inputs and code paths through the program, which would be complex and error-prone.
94 /// **Examples**: `for x in 5..10-5 { .. }` (oops, stray `-`)
95 declare_lint!{ pub REVERSE_RANGE_LOOP, Warn,
96 "Iterating over an empty range, such as `10..0` or `5..5`" }
98 /// **What it does:** This lint checks `for` loops over slices with an explicit counter and suggests the use of `.enumerate()`. It is `Warn` by default.
100 /// **Why is it bad?** Not only is the version using `.enumerate()` more readable, the compiler is able to remove bounds checks which can lead to faster code in some instances.
102 /// **Known problems:** None.
104 /// **Example:** `for i in 0..v.len() { foo(v[i]); }` or `for i in 0..v.len() { bar(i, v[i]); }`
105 declare_lint!{ pub EXPLICIT_COUNTER_LOOP, Warn,
106 "for-looping with an explicit counter when `_.enumerate()` would do" }
108 /// **What it does:** This lint checks for empty `loop` expressions. It is `Warn` by default.
110 /// **Why is this bad?** Those busy loops burn CPU cycles without doing anything. Think of the environment and either block on something or at least make the thread sleep for some microseconds.
112 /// **Known problems:** None
114 /// **Example:** `loop {}`
115 declare_lint!{ pub EMPTY_LOOP, Warn, "empty `loop {}` detected" }
117 declare_lint!{ pub WHILE_LET_ON_ITERATOR, Warn, "using a while-let loop instead of a for loop on an iterator" }
119 #[derive(Copy, Clone)]
120 pub struct LoopsPass;
122 impl LintPass for LoopsPass {
123 fn get_lints(&self) -> LintArray {
124 lint_array!(NEEDLESS_RANGE_LOOP, EXPLICIT_ITER_LOOP, ITER_NEXT_LOOP,
125 WHILE_LET_LOOP, UNUSED_COLLECT, REVERSE_RANGE_LOOP,
126 EXPLICIT_COUNTER_LOOP, EMPTY_LOOP,
127 WHILE_LET_ON_ITERATOR)
131 impl LateLintPass for LoopsPass {
132 fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
133 if let Some((pat, arg, body)) = recover_for_loop(expr) {
134 check_for_loop(cx, pat, arg, body, expr);
136 // check for `loop { if let {} else break }` that could be `while let`
137 // (also matches an explicit "match" instead of "if let")
138 // (even if the "match" or "if let" is used for declaration)
139 if let ExprLoop(ref block, _) = expr.node {
140 // also check for empty `loop {}` statements
141 if block.stmts.is_empty() && block.expr.is_none() {
142 span_lint(cx, EMPTY_LOOP, expr.span,
143 "empty `loop {}` detected. You may want to either \
144 use `panic!()` or add `std::thread::sleep(..);` to \
148 // extract the expression from the first statement (if any) in a block
149 let inner_stmt_expr = extract_expr_from_first_stmt(block);
150 // extract the first expression (if any) from the block
151 let inner_expr = extract_first_expr(block);
152 let (extracted, collect_expr) = match inner_stmt_expr {
153 Some(_) => (inner_stmt_expr, true), // check if an expression exists in the first statement
154 None => (inner_expr, false), // if not, let's go for the first expression in the block
157 if let Some(inner) = extracted {
158 if let ExprMatch(ref matchexpr, ref arms, ref source) = inner.node {
159 // collect the remaining statements below the match
160 let mut other_stuff = block.stmts
164 format!("{}", snippet(cx, stmt.span, ".."))
165 }).collect::<Vec<String>>();
166 if collect_expr { // if we have a statement which has a match,
167 match block.expr { // then collect the expression (without semicolon) below it
168 Some(ref expr) => other_stuff.push(format!("{}", snippet(cx, expr.span, ".."))),
173 // ensure "if let" compatible match structure
175 MatchSource::Normal | MatchSource::IfLetDesugar{..} => if
177 arms[0].pats.len() == 1 && arms[0].guard.is_none() &&
178 arms[1].pats.len() == 1 && arms[1].guard.is_none() &&
179 // finally, check for "break" in the second clause
180 is_break_expr(&arms[1].body)
182 if in_external_macro(cx, expr.span) { return; }
183 let loop_body = match inner_stmt_expr {
184 // FIXME: should probably be an ellipsis
185 // tabbing and newline is probably a bad idea, especially for large blocks
186 Some(_) => Cow::Owned(format!("{{\n {}\n}}", other_stuff.join("\n "))),
187 None => expr_block(cx, &arms[0].body,
188 Some(other_stuff.join("\n ")), ".."),
190 span_help_and_lint(cx, WHILE_LET_LOOP, expr.span,
191 "this loop could be written as a `while let` loop",
192 &format!("try\nwhile let {} = {} {}",
193 snippet(cx, arms[0].pats[0].span, ".."),
194 snippet(cx, matchexpr.span, ".."),
202 if let ExprMatch(ref match_expr, ref arms, MatchSource::WhileLetDesugar) = expr.node {
203 let pat = &arms[0].pats[0].node;
204 if let (&PatEnum(ref path, Some(ref pat_args)),
205 &ExprMethodCall(method_name, _, ref method_args)) =
206 (pat, &match_expr.node) {
207 let iter_expr = &method_args[0];
208 if let Some(lhs_constructor) = path.segments.last() {
209 if method_name.node.as_str() == "next" &&
210 match_trait_method(cx, match_expr, &["core", "iter", "Iterator"]) &&
211 lhs_constructor.identifier.name.as_str() == "Some" &&
212 !is_iterator_used_after_while_let(cx, iter_expr) {
213 let iterator = snippet(cx, method_args[0].span, "_");
214 let loop_var = snippet(cx, pat_args[0].span, "_");
215 span_help_and_lint(cx, WHILE_LET_ON_ITERATOR, expr.span,
216 "this loop could be written as a `for` loop",
217 &format!("try\nfor {} in {} {{...}}",
226 fn check_stmt(&mut self, cx: &LateContext, stmt: &Stmt) {
227 if let StmtSemi(ref expr, _) = stmt.node {
228 if let ExprMethodCall(ref method, _, ref args) = expr.node {
229 if args.len() == 1 && method.node.as_str() == "collect" &&
230 match_trait_method(cx, expr, &["core", "iter", "Iterator"]) {
231 span_lint(cx, UNUSED_COLLECT, expr.span, &format!(
232 "you are collect()ing an iterator and throwing away the result. \
233 Consider using an explicit for loop to exhaust the iterator"));
240 fn check_for_loop(cx: &LateContext, pat: &Pat, arg: &Expr, body: &Expr, expr: &Expr) {
241 // check for looping over a range and then indexing a sequence with it
242 // -> the iteratee must be a range literal
243 if let ExprRange(Some(ref l), _) = arg.node {
244 // Range should start with `0`
245 if let ExprLit(ref lit) = l.node {
246 if let LitInt(0, _) = lit.node {
248 // the var must be a single name
249 if let PatIdent(_, ref ident, _) = pat.node {
250 let mut visitor = VarVisitor { cx: cx, var: ident.node.name,
251 indexed: HashSet::new(), nonindex: false };
252 walk_expr(&mut visitor, body);
253 // linting condition: we only indexed one variable
254 if visitor.indexed.len() == 1 {
255 let indexed = visitor.indexed.into_iter().next().expect(
256 "Len was nonzero, but no contents found");
257 if visitor.nonindex {
258 span_lint(cx, NEEDLESS_RANGE_LOOP, expr.span, &format!(
259 "the loop variable `{}` is used to index `{}`. Consider using \
260 `for ({}, item) in {}.iter().enumerate()` or similar iterators",
261 ident.node.name, indexed, ident.node.name, indexed));
263 span_lint(cx, NEEDLESS_RANGE_LOOP, expr.span, &format!(
264 "the loop variable `{}` is only used to index `{}`. \
265 Consider using `for item in &{}` or similar iterators",
266 ident.node.name, indexed, indexed));
274 // if this for loop is iterating over a two-sided range...
275 if let ExprRange(Some(ref start_expr), Some(ref stop_expr)) = arg.node {
276 // ...and both sides are compile-time constant integers...
277 if let Some(start_idx @ Constant::ConstantInt(..)) = constant_simple(start_expr) {
278 if let Some(stop_idx @ Constant::ConstantInt(..)) = constant_simple(stop_expr) {
279 // ...and the start index is greater than the stop index,
280 // this loop will never run. This is often confusing for developers
281 // who think that this will iterate from the larger value to the
283 if start_idx > stop_idx {
284 span_help_and_lint(cx, REVERSE_RANGE_LOOP, expr.span,
285 "this range is empty so this for loop will never run",
286 &format!("Consider using `({}..{}).rev()` if you are attempting to \
287 iterate over this range in reverse", stop_idx, start_idx));
288 } else if start_idx == stop_idx {
289 // if they are equal, it's also problematic - this loop
291 span_lint(cx, REVERSE_RANGE_LOOP, expr.span,
292 "this range is empty so this for loop will never run");
298 if let ExprMethodCall(ref method, _, ref args) = arg.node {
299 // just the receiver, no arguments
301 let method_name = method.node;
302 // check for looping over x.iter() or x.iter_mut(), could use &x or &mut x
303 if method_name.as_str() == "iter" || method_name.as_str() == "iter_mut" {
304 if is_ref_iterable_type(cx, &args[0]) {
305 let object = snippet(cx, args[0].span, "_");
306 span_lint(cx, EXPLICIT_ITER_LOOP, expr.span, &format!(
307 "it is more idiomatic to loop over `&{}{}` instead of `{}.{}()`",
308 if method_name.as_str() == "iter_mut" { "mut " } else { "" },
309 object, object, method_name));
312 // check for looping over Iterator::next() which is not what you want
313 else if method_name.as_str() == "next" &&
314 match_trait_method(cx, arg, &["core", "iter", "Iterator"]) {
315 span_lint(cx, ITER_NEXT_LOOP, expr.span,
316 "you are iterating over `Iterator::next()` which is an Option; \
317 this will compile but is probably not what you want");
322 // Look for variables that are incremented once per loop iteration.
323 let mut visitor = IncrementVisitor { cx: cx, states: HashMap::new(), depth: 0, done: false };
324 walk_expr(&mut visitor, body);
326 // For each candidate, check the parent block to see if
327 // it's initialized to zero at the start of the loop.
328 let map = &cx.tcx.map;
329 let parent_scope = map.get_enclosing_scope(expr.id).and_then(|id| map.get_enclosing_scope(id) );
330 if let Some(parent_id) = parent_scope {
331 if let NodeBlock(block) = map.get(parent_id) {
332 for (id, _) in visitor.states.iter().filter( |&(_,v)| *v == VarState::IncrOnce) {
333 let mut visitor2 = InitializeVisitor { cx: cx, end_expr: expr, var_id: id.clone(),
334 state: VarState::IncrOnce, name: None,
337 walk_block(&mut visitor2, block);
339 if visitor2.state == VarState::Warn {
340 if let Some(name) = visitor2.name {
341 span_lint(cx, EXPLICIT_COUNTER_LOOP, expr.span,
342 &format!("the variable `{0}` is used as a loop counter. Consider \
343 using `for ({0}, item) in {1}.enumerate()` \
344 or similar iterators",
345 name, snippet(cx, arg.span, "_")));
353 /// Recover the essential nodes of a desugared for loop:
354 /// `for pat in arg { body }` becomes `(pat, arg, body)`.
355 fn recover_for_loop(expr: &Expr) -> Option<(&Pat, &Expr, &Expr)> {
358 let ExprMatch(ref iterexpr, ref arms, _) = expr.node,
359 let ExprCall(_, ref iterargs) = iterexpr.node,
360 iterargs.len() == 1 && arms.len() == 1 && arms[0].guard.is_none(),
361 let ExprLoop(ref block, _) = arms[0].body.node,
362 block.stmts.is_empty(),
363 let Some(ref loopexpr) = block.expr,
364 let ExprMatch(_, ref innerarms, MatchSource::ForLoopDesugar) = loopexpr.node,
365 innerarms.len() == 2 && innerarms[0].pats.len() == 1,
366 let PatEnum(_, Some(ref somepats)) = innerarms[0].pats[0].node,
369 return Some((&somepats[0],
371 &innerarms[0].body));
377 struct VarVisitor<'v, 't: 'v> {
378 cx: &'v LateContext<'v, 't>, // context reference
379 var: Name, // var name to look for as index
380 indexed: HashSet<Name>, // indexed variables
381 nonindex: bool, // has the var been used otherwise?
384 impl<'v, 't> Visitor<'v> for VarVisitor<'v, 't> {
385 fn visit_expr(&mut self, expr: &'v Expr) {
386 if let ExprPath(None, ref path) = expr.node {
387 if path.segments.len() == 1 && path.segments[0].identifier.name == self.var {
388 // we are referencing our variable! now check if it's as an index
391 let Some(parexpr) = get_parent_expr(self.cx, expr),
392 let ExprIndex(ref seqexpr, _) = parexpr.node,
393 let ExprPath(None, ref seqvar) = seqexpr.node,
394 seqvar.segments.len() == 1
396 self.indexed.insert(seqvar.segments[0].identifier.name);
397 return; // no need to walk further
400 // we are not indexing anything, record that
401 self.nonindex = true;
405 walk_expr(self, expr);
409 fn is_iterator_used_after_while_let(cx: &LateContext, iter_expr: &Expr) -> bool {
410 let def_id = match var_def_id(cx, iter_expr) {
414 let mut visitor = VarUsedAfterLoopVisitor {
417 iter_expr_id: iter_expr.id,
418 past_while_let: false,
419 var_used_after_while_let: false
421 if let Some(enclosing_block) = get_enclosing_block(cx, def_id) {
422 walk_block(&mut visitor, enclosing_block);
424 visitor.var_used_after_while_let
427 struct VarUsedAfterLoopVisitor<'v, 't: 'v> {
428 cx: &'v LateContext<'v, 't>,
430 iter_expr_id: NodeId,
431 past_while_let: bool,
432 var_used_after_while_let: bool
435 impl <'v, 't> Visitor<'v> for VarUsedAfterLoopVisitor<'v, 't> {
436 fn visit_expr(&mut self, expr: &'v Expr) {
437 if self.past_while_let {
438 if Some(self.def_id) == var_def_id(self.cx, expr) {
439 self.var_used_after_while_let = true;
441 } else if self.iter_expr_id == expr.id {
442 self.past_while_let = true;
444 walk_expr(self, expr);
449 /// Return true if the type of expr is one that provides IntoIterator impls
450 /// for &T and &mut T, such as Vec.
451 fn is_ref_iterable_type(cx: &LateContext, e: &Expr) -> bool {
452 // no walk_ptrs_ty: calling iter() on a reference can make sense because it
453 // will allow further borrows afterwards
454 let ty = cx.tcx.expr_ty(e);
455 is_iterable_array(ty) ||
456 match_type(cx, ty, &VEC_PATH) ||
457 match_type(cx, ty, &LL_PATH) ||
458 match_type(cx, ty, &["std", "collections", "hash", "map", "HashMap"]) ||
459 match_type(cx, ty, &["std", "collections", "hash", "set", "HashSet"]) ||
460 match_type(cx, ty, &["collections", "vec_deque", "VecDeque"]) ||
461 match_type(cx, ty, &["collections", "binary_heap", "BinaryHeap"]) ||
462 match_type(cx, ty, &["collections", "btree", "map", "BTreeMap"]) ||
463 match_type(cx, ty, &["collections", "btree", "set", "BTreeSet"])
466 fn is_iterable_array(ty: ty::Ty) -> bool {
467 // IntoIterator is currently only implemented for array sizes <= 32 in rustc
469 ty::TyArray(_, 0...32) => true,
474 /// If a block begins with a statement (possibly a `let` binding) and has an expression, return it.
475 fn extract_expr_from_first_stmt(block: &Block) -> Option<&Expr> {
476 if block.stmts.is_empty() { return None; }
477 if let StmtDecl(ref decl, _) = block.stmts[0].node {
478 if let DeclLocal(ref local) = decl.node {
479 if let Some(ref expr) = local.init { Some(expr) } else { None }
484 /// If a block begins with an expression (with or without semicolon), return it.
485 fn extract_first_expr(block: &Block) -> Option<&Expr> {
487 Some(ref expr) => Some(expr),
488 None if !block.stmts.is_empty() => match block.stmts[0].node {
489 StmtExpr(ref expr, _) | StmtSemi(ref expr, _) => Some(expr),
496 /// Return true if expr contains a single break expr (maybe within a block).
497 fn is_break_expr(expr: &Expr) -> bool {
499 ExprBreak(None) => true,
500 // there won't be a `let <pat> = break` and so we can safely ignore the StmtDecl case
501 ExprBlock(ref b) => match extract_first_expr(b) {
502 Some(ref subexpr) => is_break_expr(subexpr),
509 // To trigger the EXPLICIT_COUNTER_LOOP lint, a variable must be
510 // incremented exactly once in the loop body, and initialized to zero
511 // at the start of the loop.
514 Initial, // Not examined yet
515 IncrOnce, // Incremented exactly once, may be a loop counter
516 Declared, // Declared but not (yet) initialized to zero
521 // Scan a for loop for variables that are incremented exactly once.
522 struct IncrementVisitor<'v, 't: 'v> {
523 cx: &'v LateContext<'v, 't>, // context reference
524 states: HashMap<NodeId, VarState>, // incremented variables
525 depth: u32, // depth of conditional expressions
529 impl<'v, 't> Visitor<'v> for IncrementVisitor<'v, 't> {
530 fn visit_expr(&mut self, expr: &'v Expr) {
535 // If node is a variable
536 if let Some(def_id) = var_def_id(self.cx, expr) {
537 if let Some(parent) = get_parent_expr(self.cx, expr) {
538 let state = self.states.entry(def_id).or_insert(VarState::Initial);
541 ExprAssignOp(op, ref lhs, ref rhs) =>
542 if lhs.id == expr.id {
543 if op.node == BiAdd && is_integer_literal(rhs, 1) {
544 *state = match *state {
545 VarState::Initial if self.depth == 0 => VarState::IncrOnce,
546 _ => VarState::DontWarn
550 // Assigned some other value
551 *state = VarState::DontWarn;
554 ExprAssign(ref lhs, _) if lhs.id == expr.id => *state = VarState::DontWarn,
555 ExprAddrOf(mutability,_) if mutability == MutMutable => *state = VarState::DontWarn,
560 // Give up if there are nested loops
561 else if is_loop(expr) {
566 // Keep track of whether we're inside a conditional expression
567 else if is_conditional(expr) {
569 walk_expr(self, expr);
573 walk_expr(self, expr);
577 // Check whether a variable is initialized to zero at the start of a loop.
578 struct InitializeVisitor<'v, 't: 'v> {
579 cx: &'v LateContext<'v, 't>, // context reference
580 end_expr: &'v Expr, // the for loop. Stop scanning here.
584 depth: u32, // depth of conditional expressions
588 impl<'v, 't> Visitor<'v> for InitializeVisitor<'v, 't> {
589 fn visit_decl(&mut self, decl: &'v Decl) {
590 // Look for declarations of the variable
591 if let DeclLocal(ref local) = decl.node {
592 if local.pat.id == self.var_id {
593 if let PatIdent(_, ref ident, _) = local.pat.node {
594 self.name = Some(ident.node.name);
596 self.state = if let Some(ref init) = local.init {
597 if is_integer_literal(init, 0) {
609 walk_decl(self, decl);
612 fn visit_expr(&mut self, expr: &'v Expr) {
613 if self.state == VarState::DontWarn {
616 if expr == self.end_expr {
617 self.past_loop = true;
620 // No need to visit expressions before the variable is
622 if self.state == VarState::IncrOnce {
626 // If node is the desired variable, see how it's used
627 if var_def_id(self.cx, expr) == Some(self.var_id) {
628 if let Some(parent) = get_parent_expr(self.cx, expr) {
630 ExprAssignOp(_, ref lhs, _) if lhs.id == expr.id => {
631 self.state = VarState::DontWarn;
633 ExprAssign(ref lhs, ref rhs) if lhs.id == expr.id => {
634 self.state = if is_integer_literal(rhs, 0) && self.depth == 0 {
639 ExprAddrOf(mutability,_) if mutability == MutMutable => self.state = VarState::DontWarn,
645 self.state = VarState::DontWarn;
649 // If there are other loops between the declaration and the target loop, give up
650 else if !self.past_loop && is_loop(expr) {
651 self.state = VarState::DontWarn;
654 // Keep track of whether we're inside a conditional expression
655 else if is_conditional(expr) {
657 walk_expr(self, expr);
661 walk_expr(self, expr);
665 fn var_def_id(cx: &LateContext, expr: &Expr) -> Option<NodeId> {
666 if let Some(path_res) = cx.tcx.def_map.borrow().get(&expr.id) {
667 if let DefLocal(_, node_id) = path_res.base_def {
674 fn is_loop(expr: &Expr) -> bool {
676 ExprLoop(..) | ExprWhile(..) => true,
681 fn is_conditional(expr: &Expr) -> bool {
683 ExprIf(..) | ExprMatch(..) => true,