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