]> git.lizzy.rs Git - rust.git/blob - src/ranges.rs
added wiki comments + wiki-generating python script
[rust.git] / src / ranges.rs
1 use rustc::lint::*;
2 use rustc_front::hir::*;
3 use syntax::codemap::Spanned;
4 use utils::{is_integer_literal, match_type, snippet};
5
6 /// **What it does:** This lint checks for iterating over ranges with a `.step_by(0)`, which never terminates. It is `Warn` by default.
7 ///
8 /// **Why is this bad?** This very much looks like an oversight, since with `loop { .. }` there is an obvious better way to endlessly loop.
9 ///
10 /// **Known problems:** None
11 ///
12 /// **Example:** `for x in (5..5).step_by(0) { .. }`
13 declare_lint! {
14     pub RANGE_STEP_BY_ZERO, Warn,
15     "using Range::step_by(0), which produces an infinite iterator"
16 }
17 /// **What it does:** This lint checks for zipping a collection with the range of `0.._.len()`. It is `Warn` by default.
18 ///
19 /// **Why is this bad?** The code is better expressed with `.enumerate()`.
20 ///
21 /// **Known problems:** None
22 ///
23 /// **Example:** `x.iter().zip(0..x.len())`
24 declare_lint! {
25     pub RANGE_ZIP_WITH_LEN, Warn,
26     "zipping iterator with a range when enumerate() would do"
27 }
28
29 #[derive(Copy,Clone)]
30 pub struct StepByZero;
31
32 impl LintPass for StepByZero {
33     fn get_lints(&self) -> LintArray {
34         lint_array!(RANGE_STEP_BY_ZERO, RANGE_ZIP_WITH_LEN)
35     }
36 }
37
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")
48             }
49
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;
54                 if_let_chain! {
55                     [
56                         // .iter() call
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),
62                         // .len() call
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,
68                         iter_path == len_path
69                      ], {
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, "_")));
73                     }
74                 }
75             }
76         }
77     }
78 }
79
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"])
86 }