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