]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/ranges.rs
Merge remote-tracking branch 'upstream/master' into rustup
[rust.git] / clippy_lints / src / ranges.rs
1 use crate::consts::{constant, Constant};
2 use if_chain::if_chain;
3 use rustc_ast::ast::RangeLimits;
4 use rustc_errors::Applicability;
5 use rustc_hir::{BinOpKind, Expr, ExprKind, PathSegment, QPath};
6 use rustc_lint::{LateContext, LateLintPass};
7 use rustc_middle::ty;
8 use rustc_session::{declare_lint_pass, declare_tool_lint};
9 use rustc_span::source_map::{Span, Spanned};
10 use rustc_span::symbol::Ident;
11 use std::cmp::Ordering;
12
13 use crate::utils::sugg::Sugg;
14 use crate::utils::{
15     get_parent_expr, is_integer_const, single_segment_path, snippet, snippet_opt, snippet_with_applicability,
16     span_lint, span_lint_and_sugg, span_lint_and_then,
17 };
18 use crate::utils::{higher, SpanlessEq};
19
20 declare_clippy_lint! {
21     /// **What it does:** Checks for zipping a collection with the range of
22     /// `0.._.len()`.
23     ///
24     /// **Why is this bad?** The code is better expressed with `.enumerate()`.
25     ///
26     /// **Known problems:** None.
27     ///
28     /// **Example:**
29     /// ```rust
30     /// # let x = vec![1];
31     /// x.iter().zip(0..x.len());
32     /// ```
33     /// Could be written as
34     /// ```rust
35     /// # let x = vec![1];
36     /// x.iter().enumerate();
37     /// ```
38     pub RANGE_ZIP_WITH_LEN,
39     complexity,
40     "zipping iterator with a range when `enumerate()` would do"
41 }
42
43 declare_clippy_lint! {
44     /// **What it does:** Checks for exclusive ranges where 1 is added to the
45     /// upper bound, e.g., `x..(y+1)`.
46     ///
47     /// **Why is this bad?** The code is more readable with an inclusive range
48     /// like `x..=y`.
49     ///
50     /// **Known problems:** Will add unnecessary pair of parentheses when the
51     /// expression is not wrapped in a pair but starts with a opening parenthesis
52     /// and ends with a closing one.
53     /// I.e., `let _ = (f()+1)..(f()+1)` results in `let _ = ((f()+1)..=f())`.
54     ///
55     /// Also in many cases, inclusive ranges are still slower to run than
56     /// exclusive ranges, because they essentially add an extra branch that
57     /// LLVM may fail to hoist out of the loop.
58     ///
59     /// This will cause a warning that cannot be fixed if the consumer of the
60     /// range only accepts a specific range type, instead of the generic
61     /// `RangeBounds` trait
62     /// ([#3307](https://github.com/rust-lang/rust-clippy/issues/3307)).
63     ///
64     /// **Example:**
65     /// ```rust,ignore
66     /// for x..(y+1) { .. }
67     /// ```
68     /// Could be written as
69     /// ```rust,ignore
70     /// for x..=y { .. }
71     /// ```
72     pub RANGE_PLUS_ONE,
73     pedantic,
74     "`x..(y+1)` reads better as `x..=y`"
75 }
76
77 declare_clippy_lint! {
78     /// **What it does:** Checks for inclusive ranges where 1 is subtracted from
79     /// the upper bound, e.g., `x..=(y-1)`.
80     ///
81     /// **Why is this bad?** The code is more readable with an exclusive range
82     /// like `x..y`.
83     ///
84     /// **Known problems:** This will cause a warning that cannot be fixed if
85     /// the consumer of the range only accepts a specific range type, instead of
86     /// the generic `RangeBounds` trait
87     /// ([#3307](https://github.com/rust-lang/rust-clippy/issues/3307)).
88     ///
89     /// **Example:**
90     /// ```rust,ignore
91     /// for x..=(y-1) { .. }
92     /// ```
93     /// Could be written as
94     /// ```rust,ignore
95     /// for x..y { .. }
96     /// ```
97     pub RANGE_MINUS_ONE,
98     pedantic,
99     "`x..=(y-1)` reads better as `x..y`"
100 }
101
102 declare_clippy_lint! {
103     /// **What it does:** Checks for range expressions `x..y` where both `x` and `y`
104     /// are constant and `x` is greater or equal to `y`.
105     ///
106     /// **Why is this bad?** Empty ranges yield no values so iterating them is a no-op.
107     /// Moreover, trying to use a reversed range to index a slice will panic at run-time.
108     ///
109     /// **Known problems:** None.
110     ///
111     /// **Example:**
112     ///
113     /// ```rust,no_run
114     /// fn main() {
115     ///     (10..=0).for_each(|x| println!("{}", x));
116     ///
117     ///     let arr = [1, 2, 3, 4, 5];
118     ///     let sub = &arr[3..1];
119     /// }
120     /// ```
121     /// Use instead:
122     /// ```rust
123     /// fn main() {
124     ///     (0..=10).rev().for_each(|x| println!("{}", x));
125     ///
126     ///     let arr = [1, 2, 3, 4, 5];
127     ///     let sub = &arr[1..3];
128     /// }
129     /// ```
130     pub REVERSED_EMPTY_RANGES,
131     correctness,
132     "reversing the limits of range expressions, resulting in empty ranges"
133 }
134
135 declare_clippy_lint! {
136     /// **What it does:** Checks for expressions like `x >= 3 && x < 8` that could
137     /// be more readably expressed as `(3..8).contains(x)`.
138     ///
139     /// **Why is this bad?** `contains` expresses the intent better and has less
140     /// failure modes (such as fencepost errors or using `||` instead of `&&`).
141     ///
142     /// **Known problems:** None.
143     ///
144     /// **Example:**
145     ///
146     /// ```rust
147     /// // given
148     /// let x = 6;
149     ///
150     /// assert!(x >= 3 && x < 8);
151     /// ```
152     /// Use instead:
153     /// ```rust
154     ///# let x = 6;
155     /// assert!((3..8).contains(&x));
156     /// ```
157     pub MANUAL_RANGE_CONTAINS,
158     style,
159     "manually reimplementing {`Range`, `RangeInclusive`}`::contains`"
160 }
161
162 declare_lint_pass!(Ranges => [
163     RANGE_ZIP_WITH_LEN,
164     RANGE_PLUS_ONE,
165     RANGE_MINUS_ONE,
166     REVERSED_EMPTY_RANGES,
167     MANUAL_RANGE_CONTAINS,
168 ]);
169
170 impl<'tcx> LateLintPass<'tcx> for Ranges {
171     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
172         match expr.kind {
173             ExprKind::MethodCall(ref path, _, ref args, _) => {
174                 check_range_zip_with_len(cx, path, args, expr.span);
175             },
176             ExprKind::Binary(ref op, ref l, ref r) => {
177                 check_possible_range_contains(cx, op.node, l, r, expr.span);
178             },
179             _ => {},
180         }
181
182         check_exclusive_range_plus_one(cx, expr);
183         check_inclusive_range_minus_one(cx, expr);
184         check_reversed_empty_range(cx, expr);
185     }
186 }
187
188 fn check_possible_range_contains(cx: &LateContext<'_>, op: BinOpKind, l: &Expr<'_>, r: &Expr<'_>, span: Span) {
189     let combine_and = match op {
190         BinOpKind::And | BinOpKind::BitAnd => true,
191         BinOpKind::Or | BinOpKind::BitOr => false,
192         _ => return,
193     };
194     // value, name, order (higher/lower), inclusiveness
195     if let (Some((lval, lname, name_span, lval_span, lord, linc)), Some((rval, rname, _, rval_span, rord, rinc))) =
196         (check_range_bounds(cx, l), check_range_bounds(cx, r))
197     {
198         // we only lint comparisons on the same name and with different
199         // direction
200         if lname != rname || lord == rord {
201             return;
202         }
203         let ord = Constant::partial_cmp(cx.tcx, cx.typeck_results().expr_ty(l), &lval, &rval);
204         if combine_and && ord == Some(rord) {
205             // order lower bound and upper bound
206             let (l_span, u_span, l_inc, u_inc) = if rord == Ordering::Less {
207                 (lval_span, rval_span, linc, rinc)
208             } else {
209                 (rval_span, lval_span, rinc, linc)
210             };
211             // we only lint inclusive lower bounds
212             if !l_inc {
213                 return;
214             }
215             let (range_type, range_op) = if u_inc {
216                 ("RangeInclusive", "..=")
217             } else {
218                 ("Range", "..")
219             };
220             let mut applicability = Applicability::MachineApplicable;
221             let name = snippet_with_applicability(cx, name_span, "_", &mut applicability);
222             let lo = snippet_with_applicability(cx, l_span, "_", &mut applicability);
223             let hi = snippet_with_applicability(cx, u_span, "_", &mut applicability);
224             span_lint_and_sugg(
225                 cx,
226                 MANUAL_RANGE_CONTAINS,
227                 span,
228                 &format!("manual `{}::contains` implementation", range_type),
229                 "use",
230                 format!("({}{}{}).contains(&{})", lo, range_op, hi, name),
231                 applicability,
232             );
233         } else if !combine_and && ord == Some(lord) {
234             // `!_.contains(_)`
235             // order lower bound and upper bound
236             let (l_span, u_span, l_inc, u_inc) = if lord == Ordering::Less {
237                 (lval_span, rval_span, linc, rinc)
238             } else {
239                 (rval_span, lval_span, rinc, linc)
240             };
241             if l_inc {
242                 return;
243             }
244             let (range_type, range_op) = if u_inc {
245                 ("Range", "..")
246             } else {
247                 ("RangeInclusive", "..=")
248             };
249             let mut applicability = Applicability::MachineApplicable;
250             let name = snippet_with_applicability(cx, name_span, "_", &mut applicability);
251             let lo = snippet_with_applicability(cx, l_span, "_", &mut applicability);
252             let hi = snippet_with_applicability(cx, u_span, "_", &mut applicability);
253             span_lint_and_sugg(
254                 cx,
255                 MANUAL_RANGE_CONTAINS,
256                 span,
257                 &format!("manual `!{}::contains` implementation", range_type),
258                 "use",
259                 format!("!({}{}{}).contains(&{})", lo, range_op, hi, name),
260                 applicability,
261             );
262         }
263     }
264 }
265
266 fn check_range_bounds(cx: &LateContext<'_>, ex: &Expr<'_>) -> Option<(Constant, Ident, Span, Span, Ordering, bool)> {
267     if let ExprKind::Binary(ref op, ref l, ref r) = ex.kind {
268         let (inclusive, ordering) = match op.node {
269             BinOpKind::Gt => (false, Ordering::Greater),
270             BinOpKind::Ge => (true, Ordering::Greater),
271             BinOpKind::Lt => (false, Ordering::Less),
272             BinOpKind::Le => (true, Ordering::Less),
273             _ => return None,
274         };
275         if let Some(id) = match_ident(l) {
276             if let Some((c, _)) = constant(cx, cx.typeck_results(), r) {
277                 return Some((c, id, l.span, r.span, ordering, inclusive));
278             }
279         } else if let Some(id) = match_ident(r) {
280             if let Some((c, _)) = constant(cx, cx.typeck_results(), l) {
281                 return Some((c, id, r.span, l.span, ordering.reverse(), inclusive));
282             }
283         }
284     }
285     None
286 }
287
288 fn match_ident(e: &Expr<'_>) -> Option<Ident> {
289     if let ExprKind::Path(ref qpath) = e.kind {
290         if let Some(seg) = single_segment_path(qpath) {
291             if seg.args.is_none() {
292                 return Some(seg.ident);
293             }
294         }
295     }
296     None
297 }
298
299 fn check_range_zip_with_len(cx: &LateContext<'_>, path: &PathSegment<'_>, args: &[Expr<'_>], span: Span) {
300     let name = path.ident.as_str();
301     if name == "zip" && args.len() == 2 {
302         let iter = &args[0].kind;
303         let zip_arg = &args[1];
304         if_chain! {
305             // `.iter()` call
306             if let ExprKind::MethodCall(ref iter_path, _, ref iter_args, _) = *iter;
307             if iter_path.ident.name == sym!(iter);
308             // range expression in `.zip()` call: `0..x.len()`
309             if let Some(higher::Range { start: Some(start), end: Some(end), .. }) = higher::range(zip_arg);
310             if is_integer_const(cx, start, 0);
311             // `.len()` call
312             if let ExprKind::MethodCall(ref len_path, _, ref len_args, _) = end.kind;
313             if len_path.ident.name == sym!(len) && len_args.len() == 1;
314             // `.iter()` and `.len()` called on same `Path`
315             if let ExprKind::Path(QPath::Resolved(_, ref iter_path)) = iter_args[0].kind;
316             if let ExprKind::Path(QPath::Resolved(_, ref len_path)) = len_args[0].kind;
317             if SpanlessEq::new(cx).eq_path_segments(&iter_path.segments, &len_path.segments);
318             then {
319                 span_lint(cx,
320                     RANGE_ZIP_WITH_LEN,
321                     span,
322                     &format!("it is more idiomatic to use `{}.iter().enumerate()`",
323                         snippet(cx, iter_args[0].span, "_"))
324                 );
325             }
326         }
327     }
328 }
329
330 // exclusive range plus one: `x..(y+1)`
331 fn check_exclusive_range_plus_one(cx: &LateContext<'_>, expr: &Expr<'_>) {
332     if_chain! {
333         if let Some(higher::Range {
334             start,
335             end: Some(end),
336             limits: RangeLimits::HalfOpen
337         }) = higher::range(expr);
338         if let Some(y) = y_plus_one(cx, end);
339         then {
340             let span = if expr.span.from_expansion() {
341                 expr.span
342                     .ctxt()
343                     .outer_expn_data()
344                     .call_site
345             } else {
346                 expr.span
347             };
348             span_lint_and_then(
349                 cx,
350                 RANGE_PLUS_ONE,
351                 span,
352                 "an inclusive range would be more readable",
353                 |diag| {
354                     let start = start.map_or(String::new(), |x| Sugg::hir(cx, x, "x").to_string());
355                     let end = Sugg::hir(cx, y, "y");
356                     if let Some(is_wrapped) = &snippet_opt(cx, span) {
357                         if is_wrapped.starts_with('(') && is_wrapped.ends_with(')') {
358                             diag.span_suggestion(
359                                 span,
360                                 "use",
361                                 format!("({}..={})", start, end),
362                                 Applicability::MaybeIncorrect,
363                             );
364                         } else {
365                             diag.span_suggestion(
366                                 span,
367                                 "use",
368                                 format!("{}..={}", start, end),
369                                 Applicability::MachineApplicable, // snippet
370                             );
371                         }
372                     }
373                 },
374             );
375         }
376     }
377 }
378
379 // inclusive range minus one: `x..=(y-1)`
380 fn check_inclusive_range_minus_one(cx: &LateContext<'_>, expr: &Expr<'_>) {
381     if_chain! {
382         if let Some(higher::Range { start, end: Some(end), limits: RangeLimits::Closed }) = higher::range(expr);
383         if let Some(y) = y_minus_one(cx, end);
384         then {
385             span_lint_and_then(
386                 cx,
387                 RANGE_MINUS_ONE,
388                 expr.span,
389                 "an exclusive range would be more readable",
390                 |diag| {
391                     let start = start.map_or(String::new(), |x| Sugg::hir(cx, x, "x").to_string());
392                     let end = Sugg::hir(cx, y, "y");
393                     diag.span_suggestion(
394                         expr.span,
395                         "use",
396                         format!("{}..{}", start, end),
397                         Applicability::MachineApplicable, // snippet
398                     );
399                 },
400             );
401         }
402     }
403 }
404
405 fn check_reversed_empty_range(cx: &LateContext<'_>, expr: &Expr<'_>) {
406     fn inside_indexing_expr(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
407         matches!(
408             get_parent_expr(cx, expr),
409             Some(Expr {
410                 kind: ExprKind::Index(..),
411                 ..
412             })
413         )
414     }
415
416     fn is_for_loop_arg(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
417         let mut cur_expr = expr;
418         while let Some(parent_expr) = get_parent_expr(cx, cur_expr) {
419             match higher::for_loop(parent_expr) {
420                 Some((_, args, _)) if args.hir_id == expr.hir_id => return true,
421                 _ => cur_expr = parent_expr,
422             }
423         }
424
425         false
426     }
427
428     fn is_empty_range(limits: RangeLimits, ordering: Ordering) -> bool {
429         match limits {
430             RangeLimits::HalfOpen => ordering != Ordering::Less,
431             RangeLimits::Closed => ordering == Ordering::Greater,
432         }
433     }
434
435     if_chain! {
436         if let Some(higher::Range { start: Some(start), end: Some(end), limits }) = higher::range(expr);
437         let ty = cx.typeck_results().expr_ty(start);
438         if let ty::Int(_) | ty::Uint(_) = ty.kind();
439         if let Some((start_idx, _)) = constant(cx, cx.typeck_results(), start);
440         if let Some((end_idx, _)) = constant(cx, cx.typeck_results(), end);
441         if let Some(ordering) = Constant::partial_cmp(cx.tcx, ty, &start_idx, &end_idx);
442         if is_empty_range(limits, ordering);
443         then {
444             if inside_indexing_expr(cx, expr) {
445                 // Avoid linting `N..N` as it has proven to be useful, see #5689 and #5628 ...
446                 if ordering != Ordering::Equal {
447                     span_lint(
448                         cx,
449                         REVERSED_EMPTY_RANGES,
450                         expr.span,
451                         "this range is reversed and using it to index a slice will panic at run-time",
452                     );
453                 }
454             // ... except in for loop arguments for backwards compatibility with `reverse_range_loop`
455             } else if ordering != Ordering::Equal || is_for_loop_arg(cx, expr) {
456                 span_lint_and_then(
457                     cx,
458                     REVERSED_EMPTY_RANGES,
459                     expr.span,
460                     "this range is empty so it will yield no values",
461                     |diag| {
462                         if ordering != Ordering::Equal {
463                             let start_snippet = snippet(cx, start.span, "_");
464                             let end_snippet = snippet(cx, end.span, "_");
465                             let dots = match limits {
466                                 RangeLimits::HalfOpen => "..",
467                                 RangeLimits::Closed => "..="
468                             };
469
470                             diag.span_suggestion(
471                                 expr.span,
472                                 "consider using the following if you are attempting to iterate over this \
473                                  range in reverse",
474                                 format!("({}{}{}).rev()", end_snippet, dots, start_snippet),
475                                 Applicability::MaybeIncorrect,
476                             );
477                         }
478                     },
479                 );
480             }
481         }
482     }
483 }
484
485 fn y_plus_one<'t>(cx: &LateContext<'_>, expr: &'t Expr<'_>) -> Option<&'t Expr<'t>> {
486     match expr.kind {
487         ExprKind::Binary(
488             Spanned {
489                 node: BinOpKind::Add, ..
490             },
491             ref lhs,
492             ref rhs,
493         ) => {
494             if is_integer_const(cx, lhs, 1) {
495                 Some(rhs)
496             } else if is_integer_const(cx, rhs, 1) {
497                 Some(lhs)
498             } else {
499                 None
500             }
501         },
502         _ => None,
503     }
504 }
505
506 fn y_minus_one<'t>(cx: &LateContext<'_>, expr: &'t Expr<'_>) -> Option<&'t Expr<'t>> {
507     match expr.kind {
508         ExprKind::Binary(
509             Spanned {
510                 node: BinOpKind::Sub, ..
511             },
512             ref lhs,
513             ref rhs,
514         ) if is_integer_const(cx, rhs, 1) => Some(lhs),
515         _ => None,
516     }
517 }