3 use syntax::codemap::Spanned;
4 use utils::{is_integer_literal, match_type, paths, snippet, span_lint, unsugar_range, UnsugaredRange};
6 /// **What it does:** This lint checks for iterating over ranges with a `.step_by(0)`, which never terminates.
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()`.
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, .. }, _, ref args) = expr.node {
41 // Range with step_by(0).
42 if name.as_str() == "step_by" && args.len() == 2 && has_step_by(cx, &args[0]) &&
43 is_integer_literal(&args[1], 0) {
47 "Range::step_by(0) produces an infinite iterator. Consider using `std::iter::repeat()` \
49 } else if name.as_str() == "zip" && args.len() == 2 {
50 let iter = &args[0].node;
51 let zip_arg = &args[1];
55 let ExprMethodCall( Spanned { node: ref iter_name, .. }, _, ref iter_args ) = *iter,
56 iter_name.as_str() == "iter",
57 // range expression in .zip() call: 0..x.len()
58 let Some(UnsugaredRange { start: Some(ref start), end: Some(ref end), .. }) = unsugar_range(zip_arg),
59 is_integer_literal(start, 0),
61 let ExprMethodCall(Spanned { node: ref len_name, .. }, _, ref len_args) = end.node,
62 len_name.as_str() == "len" && len_args.len() == 1,
63 // .iter() and .len() called on same Path
64 let ExprPath(_, Path { segments: ref iter_path, .. }) = iter_args[0].node,
65 let ExprPath(_, Path { segments: ref len_path, .. }) = len_args[0].node,
71 &format!("It is more idiomatic to use {}.iter().enumerate()",
72 snippet(cx, iter_args[0].span, "_")));
80 fn has_step_by(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);
85 // Note: `RangeTo`, `RangeToInclusive` and `RangeFull` don't have step_by
86 match_type(cx, ty, &paths::RANGE)
87 || match_type(cx, ty, &paths::RANGE_FROM)
88 || match_type(cx, ty, &paths::RANGE_INCLUSIVE)