2015-08-12 19:56:27 +00:00
|
|
|
use rustc::lint::*;
|
|
|
|
use syntax::ast::*;
|
|
|
|
use syntax::visit::{Visitor, walk_expr};
|
2015-08-25 16:26:20 +00:00
|
|
|
use rustc::middle::ty;
|
2015-08-12 19:56:27 +00:00
|
|
|
use std::collections::HashSet;
|
|
|
|
|
2015-08-29 09:41:06 +00:00
|
|
|
use utils::{snippet, span_lint, get_parent_expr, match_trait_method, match_type, walk_ptrs_ty,
|
|
|
|
in_external_macro, expr_block, span_help_and_lint};
|
2015-08-25 16:26:20 +00:00
|
|
|
use utils::{VEC_PATH, LL_PATH};
|
2015-08-12 19:56:27 +00:00
|
|
|
|
|
|
|
declare_lint!{ pub NEEDLESS_RANGE_LOOP, Warn,
|
2015-08-13 08:32:35 +00:00
|
|
|
"for-looping over a range of indices where an iterator over items would do" }
|
2015-08-12 19:56:27 +00:00
|
|
|
|
2015-08-13 13:36:31 +00:00
|
|
|
declare_lint!{ pub EXPLICIT_ITER_LOOP, Warn,
|
|
|
|
"for-looping over `_.iter()` or `_.iter_mut()` when `&_` or `&mut _` would do" }
|
|
|
|
|
2015-08-17 05:23:57 +00:00
|
|
|
declare_lint!{ pub ITER_NEXT_LOOP, Warn,
|
|
|
|
"for-looping over `_.next()` which is probably not intended" }
|
|
|
|
|
2015-08-29 09:41:06 +00:00
|
|
|
declare_lint!{ pub WHILE_LET_LOOP, Warn,
|
|
|
|
"`loop { if let { ... } else break }` can be written as a `while let` loop" }
|
|
|
|
|
2015-08-30 11:10:59 +00:00
|
|
|
declare_lint!{ pub UNUSED_COLLECT, Warn,
|
|
|
|
"`collect()`ing an iterator without using the result; this is usually better \
|
|
|
|
written as a for loop" }
|
|
|
|
|
2015-08-12 19:56:27 +00:00
|
|
|
#[derive(Copy, Clone)]
|
|
|
|
pub struct LoopsPass;
|
|
|
|
|
|
|
|
impl LintPass for LoopsPass {
|
|
|
|
fn get_lints(&self) -> LintArray {
|
2015-08-29 09:41:06 +00:00
|
|
|
lint_array!(NEEDLESS_RANGE_LOOP, EXPLICIT_ITER_LOOP, ITER_NEXT_LOOP,
|
2015-08-30 11:10:59 +00:00
|
|
|
WHILE_LET_LOOP, UNUSED_COLLECT)
|
2015-08-12 19:56:27 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
fn check_expr(&mut self, cx: &Context, expr: &Expr) {
|
|
|
|
if let Some((pat, arg, body)) = recover_for_loop(expr) {
|
2015-08-13 13:36:31 +00:00
|
|
|
// check for looping over a range and then indexing a sequence with it
|
|
|
|
// -> the iteratee must be a range literal
|
|
|
|
if let ExprRange(_, _) = arg.node {
|
|
|
|
// the var must be a single name
|
|
|
|
if let PatIdent(_, ref ident, _) = pat.node {
|
2015-08-12 19:56:27 +00:00
|
|
|
let mut visitor = VarVisitor { cx: cx, var: ident.node.name,
|
|
|
|
indexed: HashSet::new(), nonindex: false };
|
|
|
|
walk_expr(&mut visitor, body);
|
|
|
|
// linting condition: we only indexed one variable
|
|
|
|
if visitor.indexed.len() == 1 {
|
2015-08-29 09:41:06 +00:00
|
|
|
let indexed = visitor.indexed.into_iter().next().expect(
|
|
|
|
"Len was nonzero, but no contents found");
|
2015-08-12 19:56:27 +00:00
|
|
|
if visitor.nonindex {
|
|
|
|
span_lint(cx, NEEDLESS_RANGE_LOOP, expr.span, &format!(
|
|
|
|
"the loop variable `{}` is used to index `{}`. Consider using \
|
2015-08-17 05:30:33 +00:00
|
|
|
`for ({}, item) in {}.iter().enumerate()` or similar iterators",
|
2015-08-16 06:33:10 +00:00
|
|
|
ident.node.name, indexed, ident.node.name, indexed));
|
2015-08-12 19:56:27 +00:00
|
|
|
} else {
|
|
|
|
span_lint(cx, NEEDLESS_RANGE_LOOP, expr.span, &format!(
|
|
|
|
"the loop variable `{}` is only used to index `{}`. \
|
2015-08-17 05:30:33 +00:00
|
|
|
Consider using `for item in &{}` or similar iterators",
|
2015-08-16 06:33:10 +00:00
|
|
|
ident.node.name, indexed, indexed));
|
2015-08-12 19:56:27 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2015-08-13 13:36:31 +00:00
|
|
|
|
|
|
|
if let ExprMethodCall(ref method, _, ref args) = arg.node {
|
2015-08-17 05:23:57 +00:00
|
|
|
// just the receiver, no arguments
|
2015-08-13 13:36:31 +00:00
|
|
|
if args.len() == 1 {
|
2015-08-16 06:33:10 +00:00
|
|
|
let method_name = method.node.name;
|
2015-08-17 05:23:57 +00:00
|
|
|
// check for looping over x.iter() or x.iter_mut(), could use &x or &mut x
|
2015-08-25 16:26:20 +00:00
|
|
|
if method_name == "iter" || method_name == "iter_mut" {
|
|
|
|
if is_ref_iterable_type(cx, &args[0]) {
|
|
|
|
let object = snippet(cx, args[0].span, "_");
|
|
|
|
span_lint(cx, EXPLICIT_ITER_LOOP, expr.span, &format!(
|
|
|
|
"it is more idiomatic to loop over `&{}{}` instead of `{}.{}()`",
|
|
|
|
if method_name == "iter_mut" { "mut " } else { "" },
|
|
|
|
object, object, method_name));
|
|
|
|
}
|
|
|
|
}
|
2015-08-17 05:23:57 +00:00
|
|
|
// check for looping over Iterator::next() which is not what you want
|
2015-08-25 16:26:20 +00:00
|
|
|
else if method_name == "next" {
|
2015-08-23 14:32:50 +00:00
|
|
|
if match_trait_method(cx, arg, &["core", "iter", "Iterator"]) {
|
|
|
|
span_lint(cx, ITER_NEXT_LOOP, expr.span,
|
|
|
|
"you are iterating over `Iterator::next()` which is an Option; \
|
|
|
|
this will compile but is probably not what you want");
|
2015-08-17 05:23:57 +00:00
|
|
|
}
|
2015-08-13 13:36:31 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2015-08-12 19:56:27 +00:00
|
|
|
}
|
2015-08-29 09:41:06 +00:00
|
|
|
// check for `loop { if let {} else break }` that could be `while let`
|
|
|
|
// (also matches explicit "match" instead of "if let")
|
|
|
|
if let ExprLoop(ref block, _) = expr.node {
|
|
|
|
// extract a single expression
|
|
|
|
if let Some(inner) = extract_single_expr(block) {
|
|
|
|
if let ExprMatch(ref matchexpr, ref arms, ref source) = inner.node {
|
|
|
|
// ensure "if let" compatible match structure
|
|
|
|
match *source {
|
|
|
|
MatchSource::Normal | MatchSource::IfLetDesugar{..} => if
|
|
|
|
arms.len() == 2 &&
|
|
|
|
arms[0].pats.len() == 1 && arms[0].guard.is_none() &&
|
|
|
|
arms[1].pats.len() == 1 && arms[1].guard.is_none() &&
|
|
|
|
// finally, check for "break" in the second clause
|
|
|
|
is_break_expr(&arms[1].body)
|
|
|
|
{
|
|
|
|
if in_external_macro(cx, expr.span) { return; }
|
|
|
|
span_help_and_lint(cx, WHILE_LET_LOOP, expr.span,
|
|
|
|
"this loop could be written as a `while let` loop",
|
|
|
|
&format!("try\nwhile let {} = {} {}",
|
|
|
|
snippet(cx, arms[0].pats[0].span, ".."),
|
|
|
|
snippet(cx, matchexpr.span, ".."),
|
|
|
|
expr_block(cx, &arms[0].body, "..")));
|
|
|
|
},
|
|
|
|
_ => ()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2015-08-12 19:56:27 +00:00
|
|
|
}
|
2015-08-30 11:10:59 +00:00
|
|
|
|
|
|
|
fn check_stmt(&mut self, cx: &Context, stmt: &Stmt) {
|
|
|
|
if let StmtSemi(ref expr, _) = stmt.node {
|
|
|
|
if let ExprMethodCall(ref method, _, ref args) = expr.node {
|
|
|
|
if args.len() == 1 && method.node.name == "collect" {
|
|
|
|
if match_trait_method(cx, expr, &["core", "iter", "Iterator"]) {
|
|
|
|
span_lint(cx, UNUSED_COLLECT, expr.span, &format!(
|
|
|
|
"you are collect()ing an iterator and throwing away the result. \
|
|
|
|
Consider using an explicit for loop to exhaust the iterator"));
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2015-08-12 19:56:27 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Recover the essential nodes of a desugared for loop:
|
|
|
|
/// `for pat in arg { body }` becomes `(pat, arg, body)`.
|
2015-08-13 14:41:51 +00:00
|
|
|
fn recover_for_loop(expr: &Expr) -> Option<(&Pat, &Expr, &Expr)> {
|
2015-08-12 19:56:27 +00:00
|
|
|
if_let_chain! {
|
|
|
|
[
|
|
|
|
let ExprMatch(ref iterexpr, ref arms, _) = expr.node,
|
|
|
|
let ExprCall(_, ref iterargs) = iterexpr.node,
|
2015-08-13 14:41:51 +00:00
|
|
|
iterargs.len() == 1 && arms.len() == 1 && arms[0].guard.is_none(),
|
2015-08-12 19:56:27 +00:00
|
|
|
let ExprLoop(ref block, _) = arms[0].body.node,
|
|
|
|
block.stmts.is_empty(),
|
|
|
|
let Some(ref loopexpr) = block.expr,
|
|
|
|
let ExprMatch(_, ref innerarms, MatchSource::ForLoopDesugar) = loopexpr.node,
|
|
|
|
innerarms.len() == 2 && innerarms[0].pats.len() == 1,
|
|
|
|
let PatEnum(_, Some(ref somepats)) = innerarms[0].pats[0].node,
|
|
|
|
somepats.len() == 1
|
|
|
|
], {
|
2015-08-25 12:41:35 +00:00
|
|
|
return Some((&somepats[0],
|
|
|
|
&iterargs[0],
|
|
|
|
&innerarms[0].body));
|
2015-08-12 19:56:27 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
None
|
|
|
|
}
|
|
|
|
|
|
|
|
struct VarVisitor<'v, 't: 'v> {
|
|
|
|
cx: &'v Context<'v, 't>, // context reference
|
|
|
|
var: Name, // var name to look for as index
|
|
|
|
indexed: HashSet<Name>, // indexed variables
|
|
|
|
nonindex: bool, // has the var been used otherwise?
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<'v, 't> Visitor<'v> for VarVisitor<'v, 't> {
|
|
|
|
fn visit_expr(&mut self, expr: &'v Expr) {
|
|
|
|
if let ExprPath(None, ref path) = expr.node {
|
|
|
|
if path.segments.len() == 1 && path.segments[0].identifier.name == self.var {
|
|
|
|
// we are referencing our variable! now check if it's as an index
|
|
|
|
if_let_chain! {
|
|
|
|
[
|
|
|
|
let Some(parexpr) = get_parent_expr(self.cx, expr),
|
|
|
|
let ExprIndex(ref seqexpr, _) = parexpr.node,
|
|
|
|
let ExprPath(None, ref seqvar) = seqexpr.node,
|
|
|
|
seqvar.segments.len() == 1
|
|
|
|
], {
|
|
|
|
self.indexed.insert(seqvar.segments[0].identifier.name);
|
|
|
|
return; // no need to walk further
|
|
|
|
}
|
|
|
|
}
|
|
|
|
// we are not indexing anything, record that
|
|
|
|
self.nonindex = true;
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
walk_expr(self, expr);
|
|
|
|
}
|
|
|
|
}
|
2015-08-25 16:26:20 +00:00
|
|
|
|
|
|
|
/// Return true if the type of expr is one that provides IntoIterator impls
|
|
|
|
/// for &T and &mut T, such as Vec.
|
|
|
|
fn is_ref_iterable_type(cx: &Context, e: &Expr) -> bool {
|
|
|
|
let ty = walk_ptrs_ty(cx.tcx.expr_ty(e));
|
|
|
|
is_array(ty) ||
|
|
|
|
match_type(cx, ty, &VEC_PATH) ||
|
|
|
|
match_type(cx, ty, &LL_PATH) ||
|
|
|
|
match_type(cx, ty, &["std", "collections", "hash", "map", "HashMap"]) ||
|
|
|
|
match_type(cx, ty, &["std", "collections", "hash", "set", "HashSet"]) ||
|
|
|
|
match_type(cx, ty, &["collections", "vec_deque", "VecDeque"]) ||
|
|
|
|
match_type(cx, ty, &["collections", "binary_heap", "BinaryHeap"]) ||
|
|
|
|
match_type(cx, ty, &["collections", "btree", "map", "BTreeMap"]) ||
|
|
|
|
match_type(cx, ty, &["collections", "btree", "set", "BTreeSet"])
|
|
|
|
}
|
|
|
|
|
|
|
|
fn is_array(ty: ty::Ty) -> bool {
|
|
|
|
match ty.sty {
|
|
|
|
ty::TyArray(..) => true,
|
|
|
|
_ => false
|
|
|
|
}
|
|
|
|
}
|
2015-08-29 09:41:06 +00:00
|
|
|
|
|
|
|
/// If block consists of a single expression (with or without semicolon), return it.
|
|
|
|
fn extract_single_expr(block: &Block) -> Option<&Expr> {
|
|
|
|
match (&block.stmts.len(), &block.expr) {
|
|
|
|
(&1, &None) => match block.stmts[0].node {
|
|
|
|
StmtExpr(ref expr, _) |
|
|
|
|
StmtSemi(ref expr, _) => Some(expr),
|
|
|
|
_ => None,
|
|
|
|
},
|
|
|
|
(&0, &Some(ref expr)) => Some(expr),
|
|
|
|
_ => None
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Return true if expr contains a single break expr (maybe within a block).
|
|
|
|
fn is_break_expr(expr: &Expr) -> bool {
|
|
|
|
match expr.node {
|
|
|
|
ExprBreak(None) => true,
|
|
|
|
ExprBlock(ref b) => match extract_single_expr(b) {
|
|
|
|
Some(ref subexpr) => is_break_expr(subexpr),
|
|
|
|
None => false,
|
|
|
|
},
|
|
|
|
_ => false,
|
|
|
|
}
|
|
|
|
}
|