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::higher;
4 use clippy_utils::source::{snippet, snippet_opt, snippet_with_applicability};
5 use clippy_utils::sugg::Sugg;
6 use clippy_utils::{get_parent_expr, in_constant, is_integer_const, meets_msrv, msrvs, path_to_local};
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};
11 use rustc_lint::{LateContext, LateLintPass};
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 std::cmp::Ordering;
18 declare_clippy_lint! {
20 /// Checks for exclusive ranges where 1 is added to the
21 /// upper bound, e.g., `x..(y+1)`.
23 /// ### Why is this bad?
24 /// The code is more readable with an inclusive range
27 /// ### Known problems
28 /// Will add unnecessary pair of parentheses when the
29 /// expression is not wrapped in a pair but starts with an opening parenthesis
30 /// and ends with a closing one.
31 /// I.e., `let _ = (f()+1)..(f()+1)` results in `let _ = ((f()+1)..=f())`.
33 /// Also in many cases, inclusive ranges are still slower to run than
34 /// exclusive ranges, because they essentially add an extra branch that
35 /// LLVM may fail to hoist out of the loop.
37 /// This will cause a warning that cannot be fixed if the consumer of the
38 /// range only accepts a specific range type, instead of the generic
39 /// `RangeBounds` trait
40 /// ([#3307](https://github.com/rust-lang/rust-clippy/issues/3307)).
46 /// for i in x..(y+1) {
59 #[clippy::version = "pre 1.29.0"]
62 "`x..(y+1)` reads better as `x..=y`"
65 declare_clippy_lint! {
67 /// Checks for inclusive ranges where 1 is subtracted from
68 /// the upper bound, e.g., `x..=(y-1)`.
70 /// ### Why is this bad?
71 /// The code is more readable with an exclusive range
74 /// ### Known problems
75 /// This will cause a warning that cannot be fixed if
76 /// the consumer of the range only accepts a specific range type, instead of
77 /// the generic `RangeBounds` trait
78 /// ([#3307](https://github.com/rust-lang/rust-clippy/issues/3307)).
84 /// for i in x..=(y-1) {
97 #[clippy::version = "pre 1.29.0"]
100 "`x..=(y-1)` reads better as `x..y`"
103 declare_clippy_lint! {
105 /// Checks for range expressions `x..y` where both `x` and `y`
106 /// are constant and `x` is greater or equal to `y`.
108 /// ### Why is this bad?
109 /// Empty ranges yield no values so iterating them is a no-op.
110 /// Moreover, trying to use a reversed range to index a slice will panic at run-time.
115 /// (10..=0).for_each(|x| println!("{}", x));
117 /// let arr = [1, 2, 3, 4, 5];
118 /// let sub = &arr[3..1];
124 /// (0..=10).rev().for_each(|x| println!("{}", x));
126 /// let arr = [1, 2, 3, 4, 5];
127 /// let sub = &arr[1..3];
130 #[clippy::version = "1.45.0"]
131 pub REVERSED_EMPTY_RANGES,
133 "reversing the limits of range expressions, resulting in empty ranges"
136 declare_clippy_lint! {
138 /// Checks for expressions like `x >= 3 && x < 8` that could
139 /// be more readably expressed as `(3..8).contains(x)`.
141 /// ### Why is this bad?
142 /// `contains` expresses the intent better and has less
143 /// failure modes (such as fencepost errors or using `||` instead of `&&`).
150 /// assert!(x >= 3 && x < 8);
155 /// assert!((3..8).contains(&x));
157 #[clippy::version = "1.49.0"]
158 pub MANUAL_RANGE_CONTAINS,
160 "manually reimplementing {`Range`, `RangeInclusive`}`::contains`"
164 msrv: Option<RustcVersion>,
169 pub fn new(msrv: Option<RustcVersion>) -> Self {
174 impl_lint_pass!(Ranges => [
177 REVERSED_EMPTY_RANGES,
178 MANUAL_RANGE_CONTAINS,
181 impl<'tcx> LateLintPass<'tcx> for Ranges {
182 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
183 if let ExprKind::Binary(ref op, l, r) = expr.kind {
184 if meets_msrv(self.msrv, msrvs::RANGE_CONTAINS) {
185 check_possible_range_contains(cx, op.node, l, r, expr, expr.span);
189 check_exclusive_range_plus_one(cx, expr);
190 check_inclusive_range_minus_one(cx, expr);
191 check_reversed_empty_range(cx, expr);
193 extract_msrv_attr!(LateContext);
196 fn check_possible_range_contains(
197 cx: &LateContext<'_>,
204 if in_constant(cx, expr.hir_id) {
208 let combine_and = match op {
209 BinOpKind::And | BinOpKind::BitAnd => true,
210 BinOpKind::Or | BinOpKind::BitOr => false,
213 // value, name, order (higher/lower), inclusiveness
214 if let (Some(l), Some(r)) = (check_range_bounds(cx, left), check_range_bounds(cx, right)) {
215 // we only lint comparisons on the same name and with different
217 if l.id != r.id || l.ord == r.ord {
220 let ord = Constant::partial_cmp(cx.tcx, cx.typeck_results().expr_ty(l.expr), &l.val, &r.val);
221 if combine_and && ord == Some(r.ord) {
222 // order lower bound and upper bound
223 let (l_span, u_span, l_inc, u_inc) = if r.ord == Ordering::Less {
224 (l.val_span, r.val_span, l.inc, r.inc)
226 (r.val_span, l.val_span, r.inc, l.inc)
228 // we only lint inclusive lower bounds
232 let (range_type, range_op) = if u_inc {
233 ("RangeInclusive", "..=")
237 let mut applicability = Applicability::MachineApplicable;
238 let name = snippet_with_applicability(cx, l.name_span, "_", &mut applicability);
239 let lo = snippet_with_applicability(cx, l_span, "_", &mut applicability);
240 let hi = snippet_with_applicability(cx, u_span, "_", &mut applicability);
241 let space = if lo.ends_with('.') { " " } else { "" };
244 MANUAL_RANGE_CONTAINS,
246 &format!("manual `{}::contains` implementation", range_type),
248 format!("({}{}{}{}).contains(&{})", lo, space, range_op, hi, name),
251 } else if !combine_and && ord == Some(l.ord) {
253 // order lower bound and upper bound
254 let (l_span, u_span, l_inc, u_inc) = if l.ord == Ordering::Less {
255 (l.val_span, r.val_span, l.inc, r.inc)
257 (r.val_span, l.val_span, r.inc, l.inc)
262 let (range_type, range_op) = if u_inc {
265 ("RangeInclusive", "..=")
267 let mut applicability = Applicability::MachineApplicable;
268 let name = snippet_with_applicability(cx, l.name_span, "_", &mut applicability);
269 let lo = snippet_with_applicability(cx, l_span, "_", &mut applicability);
270 let hi = snippet_with_applicability(cx, u_span, "_", &mut applicability);
271 let space = if lo.ends_with('.') { " " } else { "" };
274 MANUAL_RANGE_CONTAINS,
276 &format!("manual `!{}::contains` implementation", range_type),
278 format!("!({}{}{}{}).contains(&{})", lo, space, range_op, hi, name),
284 // If the LHS is the same operator, we have to recurse to get the "real" RHS, since they have
285 // the same operator precedence
287 if let ExprKind::Binary(ref lhs_op, _left, new_lhs) = left.kind;
288 if op == lhs_op.node;
289 let new_span = Span::new(new_lhs.span.lo(), right.span.hi(), expr.span.ctxt(), expr.span.parent());
290 if let Some(snip) = &snippet_opt(cx, new_span);
291 // Do not continue if we have mismatched number of parens, otherwise the suggestion is wrong
292 if snip.matches('(').count() == snip.matches(')').count();
294 check_possible_range_contains(cx, op, new_lhs, right, expr, new_span);
299 struct RangeBounds<'a> {
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),
321 if let Some(id) = path_to_local(l) {
322 if let Some((c, _)) = constant(cx, cx.typeck_results(), r) {
323 return Some(RangeBounds {
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 {
341 ord: ordering.reverse(),
350 // exclusive range plus one: `x..(y+1)`
351 fn check_exclusive_range_plus_one(cx: &LateContext<'_>, expr: &Expr<'_>) {
353 if expr.span.can_be_used_for_suggestions();
354 if let Some(higher::Range {
357 limits: RangeLimits::HalfOpen
358 }) = higher::Range::hir(expr);
359 if let Some(y) = y_plus_one(cx, end);
361 let span = expr.span;
366 "an inclusive range would be more readable",
368 let start = start.map_or(String::new(), |x| Sugg::hir(cx, x, "x").maybe_par().to_string());
369 let end = Sugg::hir(cx, y, "y").maybe_par();
370 if let Some(is_wrapped) = &snippet_opt(cx, span) {
371 if is_wrapped.starts_with('(') && is_wrapped.ends_with(')') {
372 diag.span_suggestion(
375 format!("({}..={})", start, end),
376 Applicability::MaybeIncorrect,
379 diag.span_suggestion(
382 format!("{}..={}", start, end),
383 Applicability::MachineApplicable, // snippet
393 // inclusive range minus one: `x..=(y-1)`
394 fn check_inclusive_range_minus_one(cx: &LateContext<'_>, expr: &Expr<'_>) {
396 if expr.span.can_be_used_for_suggestions();
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);
404 "an exclusive range would be more readable",
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(
411 format!("{}..{}", start, end),
412 Applicability::MachineApplicable, // snippet
420 fn check_reversed_empty_range(cx: &LateContext<'_>, expr: &Expr<'_>) {
421 fn inside_indexing_expr(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
423 get_parent_expr(cx, expr),
425 kind: ExprKind::Index(..),
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,
443 fn is_empty_range(limits: RangeLimits, ordering: Ordering) -> bool {
445 RangeLimits::HalfOpen => ordering != Ordering::Less,
446 RangeLimits::Closed => ordering == Ordering::Greater,
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);
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 {
464 REVERSED_EMPTY_RANGES,
466 "this range is reversed and using it to index a slice will panic at run-time",
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) {
473 REVERSED_EMPTY_RANGES,
475 "this range is empty so it will yield no values",
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 => "..="
485 diag.span_suggestion(
487 "consider using the following if you are attempting to iterate over this \
489 format!("({}{}{}).rev()", end_snippet, dots, start_snippet),
490 Applicability::MaybeIncorrect,
500 fn y_plus_one<'t>(cx: &LateContext<'_>, expr: &'t Expr<'_>) -> Option<&'t Expr<'t>> {
504 node: BinOpKind::Add, ..
509 if is_integer_const(cx, lhs, 1) {
511 } else if is_integer_const(cx, rhs, 1) {
521 fn y_minus_one<'t>(cx: &LateContext<'_>, expr: &'t Expr<'_>) -> Option<&'t Expr<'t>> {
525 node: BinOpKind::Sub, ..
529 ) if is_integer_const(cx, rhs, 1) => Some(lhs),