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};
13 use rustc_semver::RustcVersion;
14 use rustc_session::{declare_tool_lint, impl_lint_pass};
15 use rustc_span::source_map::{Span, Spanned};
17 use std::cmp::Ordering;
19 declare_clippy_lint! {
21 /// Checks for zipping a collection with the range of
24 /// ### Why is this bad?
25 /// The code is better expressed with `.enumerate()`.
29 /// # let x = vec![1];
30 /// x.iter().zip(0..x.len());
32 /// Could be written as
34 /// # let x = vec![1];
35 /// x.iter().enumerate();
37 #[clippy::version = "pre 1.29.0"]
38 pub RANGE_ZIP_WITH_LEN,
40 "zipping iterator with a range when `enumerate()` would do"
43 declare_clippy_lint! {
45 /// Checks for exclusive ranges where 1 is added to the
46 /// upper bound, e.g., `x..(y+1)`.
48 /// ### Why is this bad?
49 /// The code is more readable with an inclusive range
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())`.
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.
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)).
69 /// for x..(y+1) { .. }
71 /// Could be written as
75 #[clippy::version = "pre 1.29.0"]
78 "`x..(y+1)` reads better as `x..=y`"
81 declare_clippy_lint! {
83 /// Checks for inclusive ranges where 1 is subtracted from
84 /// the upper bound, e.g., `x..=(y-1)`.
86 /// ### Why is this bad?
87 /// The code is more readable with an exclusive range
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)).
98 /// for x..=(y-1) { .. }
100 /// Could be written as
104 #[clippy::version = "pre 1.29.0"]
107 "`x..=(y-1)` reads better as `x..y`"
110 declare_clippy_lint! {
112 /// Checks for range expressions `x..y` where both `x` and `y`
113 /// are constant and `x` is greater or equal to `y`.
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.
122 /// (10..=0).for_each(|x| println!("{}", x));
124 /// let arr = [1, 2, 3, 4, 5];
125 /// let sub = &arr[3..1];
131 /// (0..=10).rev().for_each(|x| println!("{}", x));
133 /// let arr = [1, 2, 3, 4, 5];
134 /// let sub = &arr[1..3];
137 #[clippy::version = "1.45.0"]
138 pub REVERSED_EMPTY_RANGES,
140 "reversing the limits of range expressions, resulting in empty ranges"
143 declare_clippy_lint! {
145 /// Checks for expressions like `x >= 3 && x < 8` that could
146 /// be more readably expressed as `(3..8).contains(x)`.
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 `&&`).
157 /// assert!(x >= 3 && x < 8);
162 /// assert!((3..8).contains(&x));
164 #[clippy::version = "1.49.0"]
165 pub MANUAL_RANGE_CONTAINS,
167 "manually reimplementing {`Range`, `RangeInclusive`}`::contains`"
171 msrv: Option<RustcVersion>,
176 pub fn new(msrv: Option<RustcVersion>) -> Self {
181 impl_lint_pass!(Ranges => [
185 REVERSED_EMPTY_RANGES,
186 MANUAL_RANGE_CONTAINS,
189 impl<'tcx> LateLintPass<'tcx> for Ranges {
190 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
192 ExprKind::MethodCall(path, args, _) => {
193 check_range_zip_with_len(cx, path, args, expr.span);
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, expr.span);
203 check_exclusive_range_plus_one(cx, expr);
204 check_inclusive_range_minus_one(cx, expr);
205 check_reversed_empty_range(cx, expr);
207 extract_msrv_attr!(LateContext);
210 fn check_possible_range_contains(
211 cx: &LateContext<'_>,
218 if in_constant(cx, expr.hir_id) {
222 let combine_and = match op {
223 BinOpKind::And | BinOpKind::BitAnd => true,
224 BinOpKind::Or | BinOpKind::BitOr => false,
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
231 if l.id != r.id || l.ord == r.ord {
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)
240 (r.val_span, l.val_span, r.inc, l.inc)
242 // we only lint inclusive lower bounds
246 let (range_type, range_op) = if u_inc {
247 ("RangeInclusive", "..=")
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 { "" };
258 MANUAL_RANGE_CONTAINS,
260 &format!("manual `{}::contains` implementation", range_type),
262 format!("({}{}{}{}).contains(&{})", lo, space, range_op, hi, name),
265 } else if !combine_and && ord == Some(l.ord) {
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)
271 (r.val_span, l.val_span, r.inc, l.inc)
276 let (range_type, range_op) = if u_inc {
279 ("RangeInclusive", "..=")
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 { "" };
288 MANUAL_RANGE_CONTAINS,
290 &format!("manual `!{}::contains` implementation", range_type),
292 format!("!({}{}{}{}).contains(&{})", lo, space, range_op, hi, name),
298 // If the LHS is the same operator, we have to recurse to get the "real" RHS, since they have
299 // the same operator precedence
301 if let ExprKind::Binary(ref lhs_op, _left, new_lhs) = left.kind;
302 if op == lhs_op.node;
303 let new_span = Span::new(new_lhs.span.lo(), right.span.hi(), expr.span.ctxt(), expr.span.parent());
304 if let Some(snip) = &snippet_opt(cx, new_span);
305 // Do not continue if we have mismatched number of parens, otherwise the suggestion is wrong
306 if snip.matches('(').count() == snip.matches(')').count();
308 check_possible_range_contains(cx, op, new_lhs, right, expr, new_span);
313 struct RangeBounds<'a> {
323 // Takes a binary expression such as x <= 2 as input
324 // Breaks apart into various pieces, such as the value of the number,
325 // hir id of the variable, and direction/inclusiveness of the operator
326 fn check_range_bounds<'a>(cx: &'a LateContext<'_>, ex: &'a Expr<'_>) -> Option<RangeBounds<'a>> {
327 if let ExprKind::Binary(ref op, l, r) = ex.kind {
328 let (inclusive, ordering) = match op.node {
329 BinOpKind::Gt => (false, Ordering::Greater),
330 BinOpKind::Ge => (true, Ordering::Greater),
331 BinOpKind::Lt => (false, Ordering::Less),
332 BinOpKind::Le => (true, Ordering::Less),
335 if let Some(id) = path_to_local(l) {
336 if let Some((c, _)) = constant(cx, cx.typeck_results(), r) {
337 return Some(RangeBounds {
347 } else if let Some(id) = path_to_local(r) {
348 if let Some((c, _)) = constant(cx, cx.typeck_results(), l) {
349 return Some(RangeBounds {
355 ord: ordering.reverse(),
364 fn check_range_zip_with_len(cx: &LateContext<'_>, path: &PathSegment<'_>, args: &[Expr<'_>], span: Span) {
366 if path.ident.as_str() == "zip";
367 if let [iter, zip_arg] = args;
369 if let ExprKind::MethodCall(iter_path, iter_args, _) = iter.kind;
370 if iter_path.ident.name == sym::iter;
371 // range expression in `.zip()` call: `0..x.len()`
372 if let Some(higher::Range { start: Some(start), end: Some(end), .. }) = higher::Range::hir(zip_arg);
373 if is_integer_const(cx, start, 0);
375 if let ExprKind::MethodCall(len_path, len_args, _) = end.kind;
376 if len_path.ident.name == sym::len && len_args.len() == 1;
377 // `.iter()` and `.len()` called on same `Path`
378 if let ExprKind::Path(QPath::Resolved(_, iter_path)) = iter_args[0].kind;
379 if let ExprKind::Path(QPath::Resolved(_, len_path)) = len_args[0].kind;
380 if SpanlessEq::new(cx).eq_path_segments(&iter_path.segments, &len_path.segments);
385 &format!("it is more idiomatic to use `{}.iter().enumerate()`",
386 snippet(cx, iter_args[0].span, "_"))
392 // exclusive range plus one: `x..(y+1)`
393 fn check_exclusive_range_plus_one(cx: &LateContext<'_>, expr: &Expr<'_>) {
395 if let Some(higher::Range {
398 limits: RangeLimits::HalfOpen
399 }) = higher::Range::hir(expr);
400 if let Some(y) = y_plus_one(cx, end);
402 let span = if expr.span.from_expansion() {
414 "an inclusive range would be more readable",
416 let start = start.map_or(String::new(), |x| Sugg::hir(cx, x, "x").maybe_par().to_string());
417 let end = Sugg::hir(cx, y, "y").maybe_par();
418 if let Some(is_wrapped) = &snippet_opt(cx, span) {
419 if is_wrapped.starts_with('(') && is_wrapped.ends_with(')') {
420 diag.span_suggestion(
423 format!("({}..={})", start, end),
424 Applicability::MaybeIncorrect,
427 diag.span_suggestion(
430 format!("{}..={}", start, end),
431 Applicability::MachineApplicable, // snippet
441 // inclusive range minus one: `x..=(y-1)`
442 fn check_inclusive_range_minus_one(cx: &LateContext<'_>, expr: &Expr<'_>) {
444 if let Some(higher::Range { start, end: Some(end), limits: RangeLimits::Closed }) = higher::Range::hir(expr);
445 if let Some(y) = y_minus_one(cx, end);
451 "an exclusive range would be more readable",
453 let start = start.map_or(String::new(), |x| Sugg::hir(cx, x, "x").maybe_par().to_string());
454 let end = Sugg::hir(cx, y, "y").maybe_par();
455 diag.span_suggestion(
458 format!("{}..{}", start, end),
459 Applicability::MachineApplicable, // snippet
467 fn check_reversed_empty_range(cx: &LateContext<'_>, expr: &Expr<'_>) {
468 fn inside_indexing_expr(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
470 get_parent_expr(cx, expr),
472 kind: ExprKind::Index(..),
478 fn is_for_loop_arg(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
479 let mut cur_expr = expr;
480 while let Some(parent_expr) = get_parent_expr(cx, cur_expr) {
481 match higher::ForLoop::hir(parent_expr) {
482 Some(higher::ForLoop { arg, .. }) if arg.hir_id == expr.hir_id => return true,
483 _ => cur_expr = parent_expr,
490 fn is_empty_range(limits: RangeLimits, ordering: Ordering) -> bool {
492 RangeLimits::HalfOpen => ordering != Ordering::Less,
493 RangeLimits::Closed => ordering == Ordering::Greater,
498 if let Some(higher::Range { start: Some(start), end: Some(end), limits }) = higher::Range::hir(expr);
499 let ty = cx.typeck_results().expr_ty(start);
500 if let ty::Int(_) | ty::Uint(_) = ty.kind();
501 if let Some((start_idx, _)) = constant(cx, cx.typeck_results(), start);
502 if let Some((end_idx, _)) = constant(cx, cx.typeck_results(), end);
503 if let Some(ordering) = Constant::partial_cmp(cx.tcx, ty, &start_idx, &end_idx);
504 if is_empty_range(limits, ordering);
506 if inside_indexing_expr(cx, expr) {
507 // Avoid linting `N..N` as it has proven to be useful, see #5689 and #5628 ...
508 if ordering != Ordering::Equal {
511 REVERSED_EMPTY_RANGES,
513 "this range is reversed and using it to index a slice will panic at run-time",
516 // ... except in for loop arguments for backwards compatibility with `reverse_range_loop`
517 } else if ordering != Ordering::Equal || is_for_loop_arg(cx, expr) {
520 REVERSED_EMPTY_RANGES,
522 "this range is empty so it will yield no values",
524 if ordering != Ordering::Equal {
525 let start_snippet = snippet(cx, start.span, "_");
526 let end_snippet = snippet(cx, end.span, "_");
527 let dots = match limits {
528 RangeLimits::HalfOpen => "..",
529 RangeLimits::Closed => "..="
532 diag.span_suggestion(
534 "consider using the following if you are attempting to iterate over this \
536 format!("({}{}{}).rev()", end_snippet, dots, start_snippet),
537 Applicability::MaybeIncorrect,
547 fn y_plus_one<'t>(cx: &LateContext<'_>, expr: &'t Expr<'_>) -> Option<&'t Expr<'t>> {
551 node: BinOpKind::Add, ..
556 if is_integer_const(cx, lhs, 1) {
558 } else if is_integer_const(cx, rhs, 1) {
568 fn y_minus_one<'t>(cx: &LateContext<'_>, expr: &'t Expr<'_>) -> Option<&'t Expr<'t>> {
572 node: BinOpKind::Sub, ..
576 ) if is_integer_const(cx, rhs, 1) => Some(lhs),