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, LintContext};
8 use rustc_semver::RustcVersion;
9 use rustc_session::{declare_tool_lint, impl_lint_pass};
10 use rustc_span::source_map::{Span, Spanned};
12 use rustc_span::symbol::Ident;
13 use std::cmp::Ordering;
15 use crate::utils::sugg::Sugg;
17 get_parent_expr, in_constant, is_integer_const, meets_msrv, single_segment_path, snippet, snippet_opt,
18 snippet_with_applicability, span_lint, span_lint_and_sugg, span_lint_and_then,
20 use crate::utils::{higher, SpanlessEq};
22 declare_clippy_lint! {
23 /// **What it does:** Checks for zipping a collection with the range of
26 /// **Why is this bad?** The code is better expressed with `.enumerate()`.
28 /// **Known problems:** None.
32 /// # let x = vec![1];
33 /// x.iter().zip(0..x.len());
35 /// Could be written as
37 /// # let x = vec![1];
38 /// x.iter().enumerate();
40 pub RANGE_ZIP_WITH_LEN,
42 "zipping iterator with a range when `enumerate()` would do"
45 declare_clippy_lint! {
46 /// **What it does:** Checks for exclusive ranges where 1 is added to the
47 /// upper bound, e.g., `x..(y+1)`.
49 /// **Why is this bad?** The code is more readable with an inclusive range
52 /// **Known problems:** Will add unnecessary pair of parentheses when the
53 /// expression is not wrapped in a pair but starts with a opening parenthesis
54 /// and ends with a closing one.
55 /// I.e., `let _ = (f()+1)..(f()+1)` results in `let _ = ((f()+1)..=f())`.
57 /// Also in many cases, inclusive ranges are still slower to run than
58 /// exclusive ranges, because they essentially add an extra branch that
59 /// LLVM may fail to hoist out of the loop.
61 /// This will cause a warning that cannot be fixed if the consumer of the
62 /// range only accepts a specific range type, instead of the generic
63 /// `RangeBounds` trait
64 /// ([#3307](https://github.com/rust-lang/rust-clippy/issues/3307)).
68 /// for x..(y+1) { .. }
70 /// Could be written as
76 "`x..(y+1)` reads better as `x..=y`"
79 declare_clippy_lint! {
80 /// **What it does:** Checks for inclusive ranges where 1 is subtracted from
81 /// the upper bound, e.g., `x..=(y-1)`.
83 /// **Why is this bad?** The code is more readable with an exclusive range
86 /// **Known problems:** This will cause a warning that cannot be fixed if
87 /// the consumer of the range only accepts a specific range type, instead of
88 /// the generic `RangeBounds` trait
89 /// ([#3307](https://github.com/rust-lang/rust-clippy/issues/3307)).
93 /// for x..=(y-1) { .. }
95 /// Could be written as
101 "`x..=(y-1)` reads better as `x..y`"
104 declare_clippy_lint! {
105 /// **What it does:** 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?** Empty ranges yield no values so iterating them is a no-op.
109 /// Moreover, trying to use a reversed range to index a slice will panic at run-time.
111 /// **Known problems:** None.
117 /// (10..=0).for_each(|x| println!("{}", x));
119 /// let arr = [1, 2, 3, 4, 5];
120 /// let sub = &arr[3..1];
126 /// (0..=10).rev().for_each(|x| println!("{}", x));
128 /// let arr = [1, 2, 3, 4, 5];
129 /// let sub = &arr[1..3];
132 pub REVERSED_EMPTY_RANGES,
134 "reversing the limits of range expressions, resulting in empty ranges"
137 declare_clippy_lint! {
138 /// **What it does:** 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?** `contains` expresses the intent better and has less
142 /// failure modes (such as fencepost errors or using `||` instead of `&&`).
144 /// **Known problems:** None.
152 /// assert!(x >= 3 && x < 8);
157 /// assert!((3..8).contains(&x));
159 pub MANUAL_RANGE_CONTAINS,
161 "manually reimplementing {`Range`, `RangeInclusive`}`::contains`"
164 const MANUAL_RANGE_CONTAINS_MSRV: RustcVersion = RustcVersion::new(1, 35, 0);
167 msrv: Option<RustcVersion>,
172 pub fn new(msrv: Option<RustcVersion>) -> Self {
177 impl_lint_pass!(Ranges => [
181 REVERSED_EMPTY_RANGES,
182 MANUAL_RANGE_CONTAINS,
185 impl<'tcx> LateLintPass<'tcx> for Ranges {
186 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
188 ExprKind::MethodCall(ref path, _, ref args, _) => {
189 check_range_zip_with_len(cx, path, args, expr.span);
191 ExprKind::Binary(ref op, ref l, ref r) => {
192 if meets_msrv(self.msrv.as_ref(), &MANUAL_RANGE_CONTAINS_MSRV) {
193 check_possible_range_contains(cx, op.node, l, r, expr);
199 check_exclusive_range_plus_one(cx, expr);
200 check_inclusive_range_minus_one(cx, expr);
201 check_reversed_empty_range(cx, expr);
203 extract_msrv_attr!(LateContext);
206 fn check_possible_range_contains(cx: &LateContext<'_>, op: BinOpKind, l: &Expr<'_>, r: &Expr<'_>, expr: &Expr<'_>) {
207 if in_constant(cx, expr.hir_id) {
211 let span = expr.span;
212 let combine_and = match op {
213 BinOpKind::And | BinOpKind::BitAnd => true,
214 BinOpKind::Or | BinOpKind::BitOr => false,
217 // value, name, order (higher/lower), inclusiveness
218 if let (Some((lval, lname, name_span, lval_span, lord, linc)), Some((rval, rname, _, rval_span, rord, rinc))) =
219 (check_range_bounds(cx, l), check_range_bounds(cx, r))
221 // we only lint comparisons on the same name and with different
223 if lname != rname || lord == rord {
226 let ord = Constant::partial_cmp(cx.tcx, cx.typeck_results().expr_ty(l), &lval, &rval);
227 if combine_and && ord == Some(rord) {
228 // order lower bound and upper bound
229 let (l_span, u_span, l_inc, u_inc) = if rord == Ordering::Less {
230 (lval_span, rval_span, linc, rinc)
232 (rval_span, lval_span, rinc, linc)
234 // we only lint inclusive lower bounds
238 let (range_type, range_op) = if u_inc {
239 ("RangeInclusive", "..=")
243 let mut applicability = Applicability::MachineApplicable;
244 let name = snippet_with_applicability(cx, name_span, "_", &mut applicability);
245 let lo = snippet_with_applicability(cx, l_span, "_", &mut applicability);
246 let hi = snippet_with_applicability(cx, u_span, "_", &mut applicability);
247 let space = if lo.ends_with('.') { " " } else { "" };
250 MANUAL_RANGE_CONTAINS,
252 &format!("manual `{}::contains` implementation", range_type),
254 format!("({}{}{}{}).contains(&{})", lo, space, range_op, hi, name),
257 } else if !combine_and && ord == Some(lord) {
259 // order lower bound and upper bound
260 let (l_span, u_span, l_inc, u_inc) = if lord == Ordering::Less {
261 (lval_span, rval_span, linc, rinc)
263 (rval_span, lval_span, rinc, linc)
268 let (range_type, range_op) = if u_inc {
271 ("RangeInclusive", "..=")
273 let mut applicability = Applicability::MachineApplicable;
274 let name = snippet_with_applicability(cx, name_span, "_", &mut applicability);
275 let lo = snippet_with_applicability(cx, l_span, "_", &mut applicability);
276 let hi = snippet_with_applicability(cx, u_span, "_", &mut applicability);
277 let space = if lo.ends_with('.') { " " } else { "" };
280 MANUAL_RANGE_CONTAINS,
282 &format!("manual `!{}::contains` implementation", range_type),
284 format!("!({}{}{}{}).contains(&{})", lo, space, range_op, hi, name),
291 fn check_range_bounds(cx: &LateContext<'_>, ex: &Expr<'_>) -> Option<(Constant, Ident, Span, Span, Ordering, bool)> {
292 if let ExprKind::Binary(ref op, ref l, ref r) = ex.kind {
293 let (inclusive, ordering) = match op.node {
294 BinOpKind::Gt => (false, Ordering::Greater),
295 BinOpKind::Ge => (true, Ordering::Greater),
296 BinOpKind::Lt => (false, Ordering::Less),
297 BinOpKind::Le => (true, Ordering::Less),
300 if let Some(id) = match_ident(l) {
301 if let Some((c, _)) = constant(cx, cx.typeck_results(), r) {
302 return Some((c, id, l.span, r.span, ordering, inclusive));
304 } else if let Some(id) = match_ident(r) {
305 if let Some((c, _)) = constant(cx, cx.typeck_results(), l) {
306 return Some((c, id, r.span, l.span, ordering.reverse(), inclusive));
313 fn match_ident(e: &Expr<'_>) -> Option<Ident> {
314 if let ExprKind::Path(ref qpath) = e.kind {
315 if let Some(seg) = single_segment_path(qpath) {
316 if seg.args.is_none() {
317 return Some(seg.ident);
324 fn check_range_zip_with_len(cx: &LateContext<'_>, path: &PathSegment<'_>, args: &[Expr<'_>], span: Span) {
325 let name = path.ident.as_str();
326 if name == "zip" && args.len() == 2 {
327 let iter = &args[0].kind;
328 let zip_arg = &args[1];
331 if let ExprKind::MethodCall(ref iter_path, _, ref iter_args, _) = *iter;
332 if iter_path.ident.name == sym::iter;
333 // range expression in `.zip()` call: `0..x.len()`
334 if let Some(higher::Range { start: Some(start), end: Some(end), .. }) = higher::range(zip_arg);
335 if is_integer_const(cx, start, 0);
337 if let ExprKind::MethodCall(ref len_path, _, ref len_args, _) = end.kind;
338 if len_path.ident.name == sym!(len) && len_args.len() == 1;
339 // `.iter()` and `.len()` called on same `Path`
340 if let ExprKind::Path(QPath::Resolved(_, ref iter_path)) = iter_args[0].kind;
341 if let ExprKind::Path(QPath::Resolved(_, ref len_path)) = len_args[0].kind;
342 if SpanlessEq::new(cx).eq_path_segments(&iter_path.segments, &len_path.segments);
347 &format!("it is more idiomatic to use `{}.iter().enumerate()`",
348 snippet(cx, iter_args[0].span, "_"))
355 // exclusive range plus one: `x..(y+1)`
356 fn check_exclusive_range_plus_one(cx: &LateContext<'_>, expr: &Expr<'_>) {
358 if let Some(higher::Range {
361 limits: RangeLimits::HalfOpen
362 }) = higher::range(expr);
363 if let Some(y) = y_plus_one(cx, end);
365 let span = if expr.span.from_expansion() {
377 "an inclusive range would be more readable",
379 let start = start.map_or(String::new(), |x| Sugg::hir(cx, x, "x").to_string());
380 let end = Sugg::hir(cx, y, "y");
381 if let Some(is_wrapped) = &snippet_opt(cx, span) {
382 if is_wrapped.starts_with('(') && is_wrapped.ends_with(')') {
383 diag.span_suggestion(
386 format!("({}..={})", start, end),
387 Applicability::MaybeIncorrect,
390 diag.span_suggestion(
393 format!("{}..={}", start, end),
394 Applicability::MachineApplicable, // snippet
404 // inclusive range minus one: `x..=(y-1)`
405 fn check_inclusive_range_minus_one(cx: &LateContext<'_>, expr: &Expr<'_>) {
407 if let Some(higher::Range { start, end: Some(end), limits: RangeLimits::Closed }) = higher::range(expr);
408 if let Some(y) = y_minus_one(cx, end);
414 "an exclusive range would be more readable",
416 let start = start.map_or(String::new(), |x| Sugg::hir(cx, x, "x").to_string());
417 let end = Sugg::hir(cx, y, "y");
418 diag.span_suggestion(
421 format!("{}..{}", start, end),
422 Applicability::MachineApplicable, // snippet
430 fn check_reversed_empty_range(cx: &LateContext<'_>, expr: &Expr<'_>) {
431 fn inside_indexing_expr(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
433 get_parent_expr(cx, expr),
435 kind: ExprKind::Index(..),
441 fn is_for_loop_arg(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
442 let mut cur_expr = expr;
443 while let Some(parent_expr) = get_parent_expr(cx, cur_expr) {
444 match higher::for_loop(parent_expr) {
445 Some((_, args, _, _)) if args.hir_id == expr.hir_id => return true,
446 _ => cur_expr = parent_expr,
453 fn is_empty_range(limits: RangeLimits, ordering: Ordering) -> bool {
455 RangeLimits::HalfOpen => ordering != Ordering::Less,
456 RangeLimits::Closed => ordering == Ordering::Greater,
461 if let Some(higher::Range { start: Some(start), end: Some(end), limits }) = higher::range(expr);
462 let ty = cx.typeck_results().expr_ty(start);
463 if let ty::Int(_) | ty::Uint(_) = ty.kind();
464 if let Some((start_idx, _)) = constant(cx, cx.typeck_results(), start);
465 if let Some((end_idx, _)) = constant(cx, cx.typeck_results(), end);
466 if let Some(ordering) = Constant::partial_cmp(cx.tcx, ty, &start_idx, &end_idx);
467 if is_empty_range(limits, ordering);
469 if inside_indexing_expr(cx, expr) {
470 // Avoid linting `N..N` as it has proven to be useful, see #5689 and #5628 ...
471 if ordering != Ordering::Equal {
474 REVERSED_EMPTY_RANGES,
476 "this range is reversed and using it to index a slice will panic at run-time",
479 // ... except in for loop arguments for backwards compatibility with `reverse_range_loop`
480 } else if ordering != Ordering::Equal || is_for_loop_arg(cx, expr) {
483 REVERSED_EMPTY_RANGES,
485 "this range is empty so it will yield no values",
487 if ordering != Ordering::Equal {
488 let start_snippet = snippet(cx, start.span, "_");
489 let end_snippet = snippet(cx, end.span, "_");
490 let dots = match limits {
491 RangeLimits::HalfOpen => "..",
492 RangeLimits::Closed => "..="
495 diag.span_suggestion(
497 "consider using the following if you are attempting to iterate over this \
499 format!("({}{}{}).rev()", end_snippet, dots, start_snippet),
500 Applicability::MaybeIncorrect,
510 fn y_plus_one<'t>(cx: &LateContext<'_>, expr: &'t Expr<'_>) -> Option<&'t Expr<'t>> {
514 node: BinOpKind::Add, ..
519 if is_integer_const(cx, lhs, 1) {
521 } else if is_integer_const(cx, rhs, 1) {
531 fn y_minus_one<'t>(cx: &LateContext<'_>, expr: &'t Expr<'_>) -> Option<&'t Expr<'t>> {
535 node: BinOpKind::Sub, ..
539 ) if is_integer_const(cx, rhs, 1) => Some(lhs),