]> git.lizzy.rs Git - rust.git/blob - src/ranges.rs
Merge pull request #921 from afck/master
[rust.git] / src / ranges.rs
1 use rustc::lint::*;
2 use rustc::hir::*;
3 use syntax::codemap::Spanned;
4 use utils::{is_integer_literal, match_type, paths, snippet, span_lint, unsugar_range, UnsugaredRange};
5
6 /// **What it does:** This lint checks for iterating over ranges with a `.step_by(0)`, which never terminates.
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()`.
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, .. }, _, 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) {
44                 span_lint(cx,
45                           RANGE_STEP_BY_ZERO,
46                           expr.span,
47                           "Range::step_by(0) produces an infinite iterator. Consider using `std::iter::repeat()` \
48                            instead");
49             } else if name.as_str() == "zip" && args.len() == 2 {
50                 let iter = &args[0].node;
51                 let zip_arg = &args[1];
52                 if_let_chain! {
53                     [
54                         // .iter() call
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),
60                         // .len() call
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,
66                         iter_path == len_path
67                      ], {
68                         span_lint(cx,
69                                   RANGE_ZIP_WITH_LEN,
70                                   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 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);
84
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)
89 }