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