3 use syntax::codemap::Spanned;
4 use utils::{is_integer_literal, match_type, paths, snippet, span_lint};
7 /// **What it does:** Checks for iterating over ranges with a `.step_by(0)`,
8 /// which never terminates.
10 /// **Why is this bad?** This very much looks like an oversight, since with
11 /// `loop { .. }` there is an obvious better way to endlessly loop.
13 /// **Known problems:** None.
17 /// for x in (5..5).step_by(0) { .. }
20 pub RANGE_STEP_BY_ZERO,
22 "using `Range::step_by(0)`, which produces an infinite iterator"
24 /// **What it does:** Checks for zipping a collection with the range of `0.._.len()`.
26 /// **Why is this bad?** The code is better expressed with `.enumerate()`.
28 /// **Known problems:** None.
32 /// x.iter().zip(0..x.len())
35 pub RANGE_ZIP_WITH_LEN,
37 "zipping iterator with a range when `enumerate()` would do"
41 pub struct StepByZero;
43 impl LintPass for StepByZero {
44 fn get_lints(&self) -> LintArray {
45 lint_array!(RANGE_STEP_BY_ZERO, RANGE_ZIP_WITH_LEN)
49 impl LateLintPass for StepByZero {
50 fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
51 if let ExprMethodCall(Spanned { node: ref name, .. }, _, ref args) = expr.node {
52 let name = &*name.as_str();
54 // Range with step_by(0).
55 if name == "step_by" && args.len() == 2 && has_step_by(cx, &args[0]) &&
56 is_integer_literal(&args[1], 0) {
60 "Range::step_by(0) produces an infinite iterator. Consider using `std::iter::repeat()` \
62 } else if name == "zip" && args.len() == 2 {
63 let iter = &args[0].node;
64 let zip_arg = &args[1];
67 let ExprMethodCall( Spanned { node: ref iter_name, .. }, _, ref iter_args ) = *iter,
68 &*iter_name.as_str() == "iter",
69 // range expression in .zip() call: 0..x.len()
70 let Some(higher::Range { start: Some(ref start), end: Some(ref end), .. }) = higher::range(zip_arg),
71 is_integer_literal(start, 0),
73 let ExprMethodCall(Spanned { node: ref len_name, .. }, _, ref len_args) = end.node,
74 &*len_name.as_str() == "len" && len_args.len() == 1,
75 // .iter() and .len() called on same Path
76 let ExprPath(QPath::Resolved(_, ref iter_path)) = iter_args[0].node,
77 let ExprPath(QPath::Resolved(_, ref len_path)) = len_args[0].node,
80 let Path { segments: ref iter_path, .. } = **iter_path;
81 let Path { segments: ref len_path, .. } = **len_path;
82 if iter_path == len_path {
86 &format!("It is more idiomatic to use {}.iter().enumerate()",
87 snippet(cx, iter_args[0].span, "_")));
95 fn has_step_by(cx: &LateContext, expr: &Expr) -> bool {
96 // No need for walk_ptrs_ty here because step_by moves self, so it
97 // can't be called on a borrowed range.
98 let ty = cx.tcx.tables().expr_ty(expr);
100 // Note: `RangeTo`, `RangeToInclusive` and `RangeFull` don't have step_by
101 match_type(cx, ty, &paths::RANGE)
102 || match_type(cx, ty, &paths::RANGE_FROM)
103 || match_type(cx, ty, &paths::RANGE_INCLUSIVE)