2 use rustc_front::hir::*;
3 use syntax::codemap::Spanned;
4 use utils::{is_integer_literal, match_type, snippet};
6 /// **What it does:** This lint checks for iterating over ranges with a `.step_by(0)`, which never terminates. It is `Warn` by default.
8 /// **Why is this bad?** This very much looks like an oversight, since with `loop { .. }` there is an obvious better way to endlessly loop.
10 /// **Known problems:** None
12 /// **Example:** `for x in (5..5).step_by(0) { .. }`
14 pub RANGE_STEP_BY_ZERO, Warn,
15 "using Range::step_by(0), which produces an infinite iterator"
17 /// **What it does:** This lint checks for zipping a collection with the range of `0.._.len()`. It is `Warn` by default.
19 /// **Why is this bad?** The code is better expressed with `.enumerate()`.
21 /// **Known problems:** None
23 /// **Example:** `x.iter().zip(0..x.len())`
25 pub RANGE_ZIP_WITH_LEN, Warn,
26 "zipping iterator with a range when enumerate() would do"
30 pub struct StepByZero;
32 impl LintPass for StepByZero {
33 fn get_lints(&self) -> LintArray {
34 lint_array!(RANGE_STEP_BY_ZERO, RANGE_ZIP_WITH_LEN)
38 impl LateLintPass for StepByZero {
39 fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
40 if let ExprMethodCall(Spanned { node: ref name, .. }, _,
41 ref args) = expr.node {
42 // Range with step_by(0).
43 if name.as_str() == "step_by" && args.len() == 2 &&
44 is_range(cx, &args[0]) && is_integer_literal(&args[1], 0) {
45 cx.span_lint(RANGE_STEP_BY_ZERO, expr.span,
46 "Range::step_by(0) produces an infinite iterator. \
47 Consider using `std::iter::repeat()` instead")
50 // x.iter().zip(0..x.len())
51 else if name.as_str() == "zip" && args.len() == 2 {
52 let iter = &args[0].node;
53 let zip_arg = &args[1].node;
57 let ExprMethodCall( Spanned { node: ref iter_name, .. }, _, ref iter_args ) = *iter,
58 iter_name.as_str() == "iter",
59 // range expression in .zip() call: 0..x.len()
60 let ExprRange(Some(ref from), Some(ref to)) = *zip_arg,
61 is_integer_literal(from, 0),
63 let ExprMethodCall(Spanned { node: ref len_name, .. }, _, ref len_args) = to.node,
64 len_name.as_str() == "len" && len_args.len() == 1,
65 // .iter() and .len() called on same Path
66 let ExprPath(_, Path { segments: ref iter_path, .. }) = iter_args[0].node,
67 let ExprPath(_, Path { segments: ref len_path, .. }) = len_args[0].node,
70 cx.span_lint(RANGE_ZIP_WITH_LEN, expr.span,
71 &format!("It is more idiomatic to use {}.iter().enumerate()",
72 snippet(cx, iter_args[0].span, "_")));
80 fn is_range(cx: &LateContext, expr: &Expr) -> bool {
81 // No need for walk_ptrs_ty here because step_by moves self, so it
82 // can't be called on a borrowed range.
83 let ty = cx.tcx.expr_ty(expr);
84 // Note: RangeTo and RangeFull don't have step_by
85 match_type(cx, ty, &["core", "ops", "Range"]) || match_type(cx, ty, &["core", "ops", "RangeFrom"])