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