]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/ranges.rs
Change Hash{Map, Set} to FxHash{Map, Set}
[rust.git] / clippy_lints / src / ranges.rs
1 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
2 use rustc::{declare_tool_lint, lint_array};
3 use if_chain::if_chain;
4 use rustc::hir::*;
5 use syntax::ast::RangeLimits;
6 use syntax::source_map::Spanned;
7 use crate::utils::{is_integer_literal, paths, snippet, span_lint, span_lint_and_then, snippet_opt};
8 use crate::utils::{get_trait_def_id, higher, implements_trait, SpanlessEq};
9 use crate::utils::sugg::Sugg;
10
11 /// **What it does:** Checks for calling `.step_by(0)` on iterators,
12 /// which never terminates.
13 ///
14 /// **Why is this bad?** This very much looks like an oversight, since with
15 /// `loop { .. }` there is an obvious better way to endlessly loop.
16 ///
17 /// **Known problems:** None.
18 ///
19 /// **Example:**
20 /// ```rust
21 /// for x in (5..5).step_by(0) { .. }
22 /// ```
23 declare_clippy_lint! {
24     pub ITERATOR_STEP_BY_ZERO,
25     correctness,
26     "using `Iterator::step_by(0)`, which produces an infinite iterator"
27 }
28
29 /// **What it does:** Checks for zipping a collection with the range of
30 /// `0.._.len()`.
31 ///
32 /// **Why is this bad?** The code is better expressed with `.enumerate()`.
33 ///
34 /// **Known problems:** None.
35 ///
36 /// **Example:**
37 /// ```rust
38 /// x.iter().zip(0..x.len())
39 /// ```
40 declare_clippy_lint! {
41     pub RANGE_ZIP_WITH_LEN,
42     complexity,
43     "zipping iterator with a range when `enumerate()` would do"
44 }
45
46 /// **What it does:** Checks for exclusive ranges where 1 is added to the
47 /// upper bound, e.g. `x..(y+1)`.
48 ///
49 /// **Why is this bad?** The code is more readable with an inclusive range
50 /// like `x..=y`.
51 ///
52 /// **Known problems:** Will add unnecessary pair of parentheses when the
53 /// expression is not wrapped in a pair but starts with a opening parenthesis
54 /// and ends with a closing one.
55 /// I.e: `let _ = (f()+1)..(f()+1)` results in `let _ = ((f()+1)..=f())`.
56 ///
57 /// **Example:**
58 /// ```rust
59 /// for x..(y+1) { .. }
60 /// ```
61 declare_clippy_lint! {
62     pub RANGE_PLUS_ONE,
63     complexity,
64     "`x..(y+1)` reads better as `x..=y`"
65 }
66
67 /// **What it does:** Checks for inclusive ranges where 1 is subtracted from
68 /// the upper bound, e.g. `x..=(y-1)`.
69 ///
70 /// **Why is this bad?** The code is more readable with an exclusive range
71 /// like `x..y`.
72 ///
73 /// **Known problems:** None.
74 ///
75 /// **Example:**
76 /// ```rust
77 /// for x..=(y-1) { .. }
78 /// ```
79 declare_clippy_lint! {
80     pub RANGE_MINUS_ONE,
81     complexity,
82     "`x..=(y-1)` reads better as `x..y`"
83 }
84
85 #[derive(Copy, Clone)]
86 pub struct Pass;
87
88 impl LintPass for Pass {
89     fn get_lints(&self) -> LintArray {
90         lint_array!(ITERATOR_STEP_BY_ZERO, RANGE_ZIP_WITH_LEN, RANGE_PLUS_ONE, RANGE_MINUS_ONE)
91     }
92 }
93
94 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
95     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
96         if let ExprKind::MethodCall(ref path, _, ref args) = expr.node {
97             let name = path.ident.as_str();
98
99             // Range with step_by(0).
100             if name == "step_by" && args.len() == 2 && has_step_by(cx, &args[0]) {
101                 use crate::consts::{constant, Constant};
102                 if let Some((Constant::Int(0), _)) = constant(cx, cx.tables, &args[1]) {
103                     span_lint(
104                         cx,
105                         ITERATOR_STEP_BY_ZERO,
106                         expr.span,
107                         "Iterator::step_by(0) will panic at runtime",
108                     );
109                 }
110             } else if name == "zip" && args.len() == 2 {
111                 let iter = &args[0].node;
112                 let zip_arg = &args[1];
113                 if_chain! {
114                     // .iter() call
115                     if let ExprKind::MethodCall(ref iter_path, _, ref iter_args ) = *iter;
116                     if iter_path.ident.name == "iter";
117                     // range expression in .zip() call: 0..x.len()
118                     if let Some(higher::Range { start: Some(start), end: Some(end), .. }) = higher::range(cx, zip_arg);
119                     if is_integer_literal(start, 0);
120                     // .len() call
121                     if let ExprKind::MethodCall(ref len_path, _, ref len_args) = end.node;
122                     if len_path.ident.name == "len" && len_args.len() == 1;
123                     // .iter() and .len() called on same Path
124                     if let ExprKind::Path(QPath::Resolved(_, ref iter_path)) = iter_args[0].node;
125                     if let ExprKind::Path(QPath::Resolved(_, ref len_path)) = len_args[0].node;
126                     if SpanlessEq::new(cx).eq_path_segments(&iter_path.segments, &len_path.segments);
127                      then {
128                          span_lint(cx,
129                                    RANGE_ZIP_WITH_LEN,
130                                    expr.span,
131                                    &format!("It is more idiomatic to use {}.iter().enumerate()",
132                                             snippet(cx, iter_args[0].span, "_")));
133                     }
134                 }
135             }
136         }
137
138         // exclusive range plus one: x..(y+1)
139         if_chain! {
140             if let Some(higher::Range { start, end: Some(end), limits: RangeLimits::HalfOpen }) = higher::range(cx, expr);
141             if let Some(y) = y_plus_one(end);
142             then {
143                 span_lint_and_then(
144                     cx,
145                     RANGE_PLUS_ONE,
146                     expr.span,
147                     "an inclusive range would be more readable",
148                     |db| {
149                         let start = start.map_or("".to_owned(), |x| Sugg::hir(cx, x, "x").to_string());
150                         let end = Sugg::hir(cx, y, "y");
151                         if let Some(is_wrapped) = &snippet_opt(cx, expr.span) {
152                             if is_wrapped.starts_with('(') && is_wrapped.ends_with(')') {
153                                 db.span_suggestion(expr.span,
154                                            "use",
155                                            format!("({}..={})", start, end));
156                             } else {
157                                 db.span_suggestion(expr.span,
158                                            "use",
159                                            format!("{}..={}", start, end));
160                             }
161                         }
162                     },
163                 );
164             }
165         }
166
167         // inclusive range minus one: x..=(y-1)
168         if_chain! {
169             if let Some(higher::Range { start, end: Some(end), limits: RangeLimits::Closed }) = higher::range(cx, expr);
170             if let Some(y) = y_minus_one(end);
171             then {
172                 span_lint_and_then(
173                     cx,
174                     RANGE_MINUS_ONE,
175                     expr.span,
176                     "an exclusive range would be more readable",
177                     |db| {
178                         let start = start.map_or("".to_owned(), |x| Sugg::hir(cx, x, "x").to_string());
179                         let end = Sugg::hir(cx, y, "y");
180                         db.span_suggestion(expr.span,
181                                            "use",
182                                            format!("{}..{}", start, end));
183                     },
184                 );
185             }
186         }
187     }
188 }
189
190 fn has_step_by(cx: &LateContext<'_, '_>, expr: &Expr) -> bool {
191     // No need for walk_ptrs_ty here because step_by moves self, so it
192     // can't be called on a borrowed range.
193     let ty = cx.tables.expr_ty_adjusted(expr);
194
195     get_trait_def_id(cx, &paths::ITERATOR).map_or(false, |iterator_trait| implements_trait(cx, ty, iterator_trait, &[]))
196 }
197
198 fn y_plus_one(expr: &Expr) -> Option<&Expr> {
199     match expr.node {
200         ExprKind::Binary(Spanned { node: BinOpKind::Add, .. }, ref lhs, ref rhs) => if is_integer_literal(lhs, 1) {
201             Some(rhs)
202         } else if is_integer_literal(rhs, 1) {
203             Some(lhs)
204         } else {
205             None
206         },
207         _ => None,
208     }
209 }
210
211 fn y_minus_one(expr: &Expr) -> Option<&Expr> {
212     match expr.node {
213         ExprKind::Binary(Spanned { node: BinOpKind::Sub, .. }, ref lhs, ref rhs) if is_integer_literal(rhs, 1) => Some(lhs),
214         _ => None,
215     }
216 }