2015-08-12 14:56:27 -05:00
|
|
|
use rustc::lint::*;
|
|
|
|
use syntax::ast::*;
|
|
|
|
use syntax::visit::{Visitor, walk_expr};
|
2015-08-25 11:26:20 -05:00
|
|
|
use rustc::middle::ty;
|
2015-08-12 14:56:27 -05:00
|
|
|
use std::collections::HashSet;
|
|
|
|
|
2015-08-25 11:26:20 -05:00
|
|
|
use utils::{snippet, span_lint, get_parent_expr, match_trait_method, match_type, walk_ptrs_ty};
|
|
|
|
use utils::{VEC_PATH, LL_PATH};
|
2015-08-12 14:56:27 -05:00
|
|
|
|
|
|
|
declare_lint!{ pub NEEDLESS_RANGE_LOOP, Warn,
|
2015-08-13 03:32:35 -05:00
|
|
|
"for-looping over a range of indices where an iterator over items would do" }
|
2015-08-12 14:56:27 -05:00
|
|
|
|
2015-08-13 08:36:31 -05:00
|
|
|
declare_lint!{ pub EXPLICIT_ITER_LOOP, Warn,
|
|
|
|
"for-looping over `_.iter()` or `_.iter_mut()` when `&_` or `&mut _` would do" }
|
|
|
|
|
2015-08-17 00:23:57 -05:00
|
|
|
declare_lint!{ pub ITER_NEXT_LOOP, Warn,
|
|
|
|
"for-looping over `_.next()` which is probably not intended" }
|
|
|
|
|
2015-08-12 14:56:27 -05:00
|
|
|
#[derive(Copy, Clone)]
|
|
|
|
pub struct LoopsPass;
|
|
|
|
|
|
|
|
impl LintPass for LoopsPass {
|
|
|
|
fn get_lints(&self) -> LintArray {
|
2015-08-17 00:23:57 -05:00
|
|
|
lint_array!(NEEDLESS_RANGE_LOOP, EXPLICIT_ITER_LOOP, ITER_NEXT_LOOP)
|
2015-08-12 14:56:27 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
fn check_expr(&mut self, cx: &Context, expr: &Expr) {
|
|
|
|
if let Some((pat, arg, body)) = recover_for_loop(expr) {
|
2015-08-13 08:36:31 -05: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 14:56:27 -05: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-13 09:28:11 -05:00
|
|
|
let indexed = visitor.indexed.into_iter().next().expect("Len was nonzero, but no contents found");
|
2015-08-12 14:56:27 -05: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 00:30:33 -05:00
|
|
|
`for ({}, item) in {}.iter().enumerate()` or similar iterators",
|
2015-08-16 01:33:10 -05:00
|
|
|
ident.node.name, indexed, ident.node.name, indexed));
|
2015-08-12 14:56:27 -05:00
|
|
|
} else {
|
|
|
|
span_lint(cx, NEEDLESS_RANGE_LOOP, expr.span, &format!(
|
|
|
|
"the loop variable `{}` is only used to index `{}`. \
|
2015-08-17 00:30:33 -05:00
|
|
|
Consider using `for item in &{}` or similar iterators",
|
2015-08-16 01:33:10 -05:00
|
|
|
ident.node.name, indexed, indexed));
|
2015-08-12 14:56:27 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2015-08-13 08:36:31 -05:00
|
|
|
|
|
|
|
if let ExprMethodCall(ref method, _, ref args) = arg.node {
|
2015-08-17 00:23:57 -05:00
|
|
|
// just the receiver, no arguments
|
2015-08-13 08:36:31 -05:00
|
|
|
if args.len() == 1 {
|
2015-08-16 01:33:10 -05:00
|
|
|
let method_name = method.node.name;
|
2015-08-17 00:23:57 -05:00
|
|
|
// check for looping over x.iter() or x.iter_mut(), could use &x or &mut x
|
2015-08-25 11:26:20 -05: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 00:23:57 -05:00
|
|
|
// check for looping over Iterator::next() which is not what you want
|
2015-08-25 11:26:20 -05:00
|
|
|
else if method_name == "next" {
|
2015-08-23 09:32:50 -05: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 00:23:57 -05:00
|
|
|
}
|
2015-08-13 08:36:31 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2015-08-12 14:56:27 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Recover the essential nodes of a desugared for loop:
|
|
|
|
/// `for pat in arg { body }` becomes `(pat, arg, body)`.
|
2015-08-13 09:41:51 -05:00
|
|
|
fn recover_for_loop(expr: &Expr) -> Option<(&Pat, &Expr, &Expr)> {
|
2015-08-12 14:56:27 -05:00
|
|
|
if_let_chain! {
|
|
|
|
[
|
|
|
|
let ExprMatch(ref iterexpr, ref arms, _) = expr.node,
|
|
|
|
let ExprCall(_, ref iterargs) = iterexpr.node,
|
2015-08-13 09:41:51 -05:00
|
|
|
iterargs.len() == 1 && arms.len() == 1 && arms[0].guard.is_none(),
|
2015-08-12 14:56:27 -05: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 07:41:35 -05:00
|
|
|
return Some((&somepats[0],
|
|
|
|
&iterargs[0],
|
|
|
|
&innerarms[0].body));
|
2015-08-12 14:56:27 -05: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 11:26:20 -05: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));
|
|
|
|
println!("mt {:?} {:?}", e, ty);
|
|
|
|
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
|
|
|
|
}
|
|
|
|
}
|