]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/ranges.rs
change to a struct variant
[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.as_ref(), &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(cx: &LateContext<'_>, op: BinOpKind, l: &Expr<'_>, r: &Expr<'_>, expr: &Expr<'_>) {
211     if in_constant(cx, expr.hir_id) {
212         return;
213     }
214
215     let span = expr.span;
216     let combine_and = match op {
217         BinOpKind::And | BinOpKind::BitAnd => true,
218         BinOpKind::Or | BinOpKind::BitOr => false,
219         _ => return,
220     };
221     // value, name, order (higher/lower), inclusiveness
222     if let (Some((lval, lid, name_span, lval_span, lord, linc)), Some((rval, rid, _, rval_span, rord, rinc))) =
223         (check_range_bounds(cx, l), check_range_bounds(cx, r))
224     {
225         // we only lint comparisons on the same name and with different
226         // direction
227         if lid != rid || lord == rord {
228             return;
229         }
230         let ord = Constant::partial_cmp(cx.tcx, cx.typeck_results().expr_ty(l), &lval, &rval);
231         if combine_and && ord == Some(rord) {
232             // order lower bound and upper bound
233             let (l_span, u_span, l_inc, u_inc) = if rord == Ordering::Less {
234                 (lval_span, rval_span, linc, rinc)
235             } else {
236                 (rval_span, lval_span, rinc, linc)
237             };
238             // we only lint inclusive lower bounds
239             if !l_inc {
240                 return;
241             }
242             let (range_type, range_op) = if u_inc {
243                 ("RangeInclusive", "..=")
244             } else {
245                 ("Range", "..")
246             };
247             let mut applicability = Applicability::MachineApplicable;
248             let name = snippet_with_applicability(cx, name_span, "_", &mut applicability);
249             let lo = snippet_with_applicability(cx, l_span, "_", &mut applicability);
250             let hi = snippet_with_applicability(cx, u_span, "_", &mut applicability);
251             let space = if lo.ends_with('.') { " " } else { "" };
252             span_lint_and_sugg(
253                 cx,
254                 MANUAL_RANGE_CONTAINS,
255                 span,
256                 &format!("manual `{}::contains` implementation", range_type),
257                 "use",
258                 format!("({}{}{}{}).contains(&{})", lo, space, range_op, hi, name),
259                 applicability,
260             );
261         } else if !combine_and && ord == Some(lord) {
262             // `!_.contains(_)`
263             // order lower bound and upper bound
264             let (l_span, u_span, l_inc, u_inc) = if lord == Ordering::Less {
265                 (lval_span, rval_span, linc, rinc)
266             } else {
267                 (rval_span, lval_span, rinc, linc)
268             };
269             if l_inc {
270                 return;
271             }
272             let (range_type, range_op) = if u_inc {
273                 ("Range", "..")
274             } else {
275                 ("RangeInclusive", "..=")
276             };
277             let mut applicability = Applicability::MachineApplicable;
278             let name = snippet_with_applicability(cx, name_span, "_", &mut applicability);
279             let lo = snippet_with_applicability(cx, l_span, "_", &mut applicability);
280             let hi = snippet_with_applicability(cx, u_span, "_", &mut applicability);
281             let space = if lo.ends_with('.') { " " } else { "" };
282             span_lint_and_sugg(
283                 cx,
284                 MANUAL_RANGE_CONTAINS,
285                 span,
286                 &format!("manual `!{}::contains` implementation", range_type),
287                 "use",
288                 format!("!({}{}{}{}).contains(&{})", lo, space, range_op, hi, name),
289                 applicability,
290             );
291         }
292     }
293 }
294
295 fn check_range_bounds(cx: &LateContext<'_>, ex: &Expr<'_>) -> Option<(Constant, HirId, Span, Span, Ordering, bool)> {
296     if let ExprKind::Binary(ref op, l, r) = ex.kind {
297         let (inclusive, ordering) = match op.node {
298             BinOpKind::Gt => (false, Ordering::Greater),
299             BinOpKind::Ge => (true, Ordering::Greater),
300             BinOpKind::Lt => (false, Ordering::Less),
301             BinOpKind::Le => (true, Ordering::Less),
302             _ => return None,
303         };
304         if let Some(id) = path_to_local(l) {
305             if let Some((c, _)) = constant(cx, cx.typeck_results(), r) {
306                 return Some((c, id, l.span, r.span, ordering, inclusive));
307             }
308         } else if let Some(id) = path_to_local(r) {
309             if let Some((c, _)) = constant(cx, cx.typeck_results(), l) {
310                 return Some((c, id, r.span, l.span, ordering.reverse(), inclusive));
311             }
312         }
313     }
314     None
315 }
316
317 fn check_range_zip_with_len(cx: &LateContext<'_>, path: &PathSegment<'_>, args: &[Expr<'_>], span: Span) {
318     if_chain! {
319         if path.ident.as_str() == "zip";
320         if let [iter, zip_arg] = args;
321         // `.iter()` call
322         if let ExprKind::MethodCall(iter_path, iter_args, _) = iter.kind;
323         if iter_path.ident.name == sym::iter;
324         // range expression in `.zip()` call: `0..x.len()`
325         if let Some(higher::Range { start: Some(start), end: Some(end), .. }) = higher::Range::hir(zip_arg);
326         if is_integer_const(cx, start, 0);
327         // `.len()` call
328         if let ExprKind::MethodCall(len_path, len_args, _) = end.kind;
329         if len_path.ident.name == sym::len && len_args.len() == 1;
330         // `.iter()` and `.len()` called on same `Path`
331         if let ExprKind::Path(QPath::Resolved(_, iter_path)) = iter_args[0].kind;
332         if let ExprKind::Path(QPath::Resolved(_, len_path)) = len_args[0].kind;
333         if SpanlessEq::new(cx).eq_path_segments(&iter_path.segments, &len_path.segments);
334         then {
335             span_lint(cx,
336                 RANGE_ZIP_WITH_LEN,
337                 span,
338                 &format!("it is more idiomatic to use `{}.iter().enumerate()`",
339                     snippet(cx, iter_args[0].span, "_"))
340             );
341         }
342     }
343 }
344
345 // exclusive range plus one: `x..(y+1)`
346 fn check_exclusive_range_plus_one(cx: &LateContext<'_>, expr: &Expr<'_>) {
347     if_chain! {
348         if let Some(higher::Range {
349             start,
350             end: Some(end),
351             limits: RangeLimits::HalfOpen
352         }) = higher::Range::hir(expr);
353         if let Some(y) = y_plus_one(cx, end);
354         then {
355             let span = if expr.span.from_expansion() {
356                 expr.span
357                     .ctxt()
358                     .outer_expn_data()
359                     .call_site
360             } else {
361                 expr.span
362             };
363             span_lint_and_then(
364                 cx,
365                 RANGE_PLUS_ONE,
366                 span,
367                 "an inclusive range would be more readable",
368                 |diag| {
369                     let start = start.map_or(String::new(), |x| Sugg::hir(cx, x, "x").maybe_par().to_string());
370                     let end = Sugg::hir(cx, y, "y").maybe_par();
371                     if let Some(is_wrapped) = &snippet_opt(cx, span) {
372                         if is_wrapped.starts_with('(') && is_wrapped.ends_with(')') {
373                             diag.span_suggestion(
374                                 span,
375                                 "use",
376                                 format!("({}..={})", start, end),
377                                 Applicability::MaybeIncorrect,
378                             );
379                         } else {
380                             diag.span_suggestion(
381                                 span,
382                                 "use",
383                                 format!("{}..={}", start, end),
384                                 Applicability::MachineApplicable, // snippet
385                             );
386                         }
387                     }
388                 },
389             );
390         }
391     }
392 }
393
394 // inclusive range minus one: `x..=(y-1)`
395 fn check_inclusive_range_minus_one(cx: &LateContext<'_>, expr: &Expr<'_>) {
396     if_chain! {
397         if let Some(higher::Range { start, end: Some(end), limits: RangeLimits::Closed }) = higher::Range::hir(expr);
398         if let Some(y) = y_minus_one(cx, end);
399         then {
400             span_lint_and_then(
401                 cx,
402                 RANGE_MINUS_ONE,
403                 expr.span,
404                 "an exclusive range would be more readable",
405                 |diag| {
406                     let start = start.map_or(String::new(), |x| Sugg::hir(cx, x, "x").maybe_par().to_string());
407                     let end = Sugg::hir(cx, y, "y").maybe_par();
408                     diag.span_suggestion(
409                         expr.span,
410                         "use",
411                         format!("{}..{}", start, end),
412                         Applicability::MachineApplicable, // snippet
413                     );
414                 },
415             );
416         }
417     }
418 }
419
420 fn check_reversed_empty_range(cx: &LateContext<'_>, expr: &Expr<'_>) {
421     fn inside_indexing_expr(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
422         matches!(
423             get_parent_expr(cx, expr),
424             Some(Expr {
425                 kind: ExprKind::Index(..),
426                 ..
427             })
428         )
429     }
430
431     fn is_for_loop_arg(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
432         let mut cur_expr = expr;
433         while let Some(parent_expr) = get_parent_expr(cx, cur_expr) {
434             match higher::ForLoop::hir(parent_expr) {
435                 Some(higher::ForLoop { arg, .. }) if arg.hir_id == expr.hir_id => return true,
436                 _ => cur_expr = parent_expr,
437             }
438         }
439
440         false
441     }
442
443     fn is_empty_range(limits: RangeLimits, ordering: Ordering) -> bool {
444         match limits {
445             RangeLimits::HalfOpen => ordering != Ordering::Less,
446             RangeLimits::Closed => ordering == Ordering::Greater,
447         }
448     }
449
450     if_chain! {
451         if let Some(higher::Range { start: Some(start), end: Some(end), limits }) = higher::Range::hir(expr);
452         let ty = cx.typeck_results().expr_ty(start);
453         if let ty::Int(_) | ty::Uint(_) = ty.kind();
454         if let Some((start_idx, _)) = constant(cx, cx.typeck_results(), start);
455         if let Some((end_idx, _)) = constant(cx, cx.typeck_results(), end);
456         if let Some(ordering) = Constant::partial_cmp(cx.tcx, ty, &start_idx, &end_idx);
457         if is_empty_range(limits, ordering);
458         then {
459             if inside_indexing_expr(cx, expr) {
460                 // Avoid linting `N..N` as it has proven to be useful, see #5689 and #5628 ...
461                 if ordering != Ordering::Equal {
462                     span_lint(
463                         cx,
464                         REVERSED_EMPTY_RANGES,
465                         expr.span,
466                         "this range is reversed and using it to index a slice will panic at run-time",
467                     );
468                 }
469             // ... except in for loop arguments for backwards compatibility with `reverse_range_loop`
470             } else if ordering != Ordering::Equal || is_for_loop_arg(cx, expr) {
471                 span_lint_and_then(
472                     cx,
473                     REVERSED_EMPTY_RANGES,
474                     expr.span,
475                     "this range is empty so it will yield no values",
476                     |diag| {
477                         if ordering != Ordering::Equal {
478                             let start_snippet = snippet(cx, start.span, "_");
479                             let end_snippet = snippet(cx, end.span, "_");
480                             let dots = match limits {
481                                 RangeLimits::HalfOpen => "..",
482                                 RangeLimits::Closed => "..="
483                             };
484
485                             diag.span_suggestion(
486                                 expr.span,
487                                 "consider using the following if you are attempting to iterate over this \
488                                  range in reverse",
489                                 format!("({}{}{}).rev()", end_snippet, dots, start_snippet),
490                                 Applicability::MaybeIncorrect,
491                             );
492                         }
493                     },
494                 );
495             }
496         }
497     }
498 }
499
500 fn y_plus_one<'t>(cx: &LateContext<'_>, expr: &'t Expr<'_>) -> Option<&'t Expr<'t>> {
501     match expr.kind {
502         ExprKind::Binary(
503             Spanned {
504                 node: BinOpKind::Add, ..
505             },
506             lhs,
507             rhs,
508         ) => {
509             if is_integer_const(cx, lhs, 1) {
510                 Some(rhs)
511             } else if is_integer_const(cx, rhs, 1) {
512                 Some(lhs)
513             } else {
514                 None
515             }
516         },
517         _ => None,
518     }
519 }
520
521 fn y_minus_one<'t>(cx: &LateContext<'_>, expr: &'t Expr<'_>) -> Option<&'t Expr<'t>> {
522     match expr.kind {
523         ExprKind::Binary(
524             Spanned {
525                 node: BinOpKind::Sub, ..
526             },
527             lhs,
528             rhs,
529         ) if is_integer_const(cx, rhs, 1) => Some(lhs),
530         _ => None,
531     }
532 }