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, QPath};
6 use rustc_lint::{LateContext, LateLintPass};
8 use rustc_session::{declare_lint_pass, declare_tool_lint};
9 use rustc_span::source_map::Spanned;
10 use std::cmp::Ordering;
12 use crate::utils::sugg::Sugg;
13 use crate::utils::{get_parent_expr, is_integer_const, snippet, snippet_opt, span_lint, span_lint_and_then};
14 use crate::utils::{higher, SpanlessEq};
16 declare_clippy_lint! {
17 /// **What it does:** Checks for zipping a collection with the range of
20 /// **Why is this bad?** The code is better expressed with `.enumerate()`.
22 /// **Known problems:** None.
26 /// # let x = vec![1];
27 /// x.iter().zip(0..x.len());
29 /// Could be written as
31 /// # let x = vec![1];
32 /// x.iter().enumerate();
34 pub RANGE_ZIP_WITH_LEN,
36 "zipping iterator with a range when `enumerate()` would do"
39 declare_clippy_lint! {
40 /// **What it does:** Checks for exclusive ranges where 1 is added to the
41 /// upper bound, e.g., `x..(y+1)`.
43 /// **Why is this bad?** The code is more readable with an inclusive range
46 /// **Known problems:** Will add unnecessary pair of parentheses when the
47 /// expression is not wrapped in a pair but starts with a opening parenthesis
48 /// and ends with a closing one.
49 /// I.e., `let _ = (f()+1)..(f()+1)` results in `let _ = ((f()+1)..=f())`.
51 /// Also in many cases, inclusive ranges are still slower to run than
52 /// exclusive ranges, because they essentially add an extra branch that
53 /// LLVM may fail to hoist out of the loop.
55 /// This will cause a warning that cannot be fixed if the consumer of the
56 /// range only accepts a specific range type, instead of the generic
57 /// `RangeBounds` trait
58 /// ([#3307](https://github.com/rust-lang/rust-clippy/issues/3307)).
62 /// for x..(y+1) { .. }
64 /// Could be written as
70 "`x..(y+1)` reads better as `x..=y`"
73 declare_clippy_lint! {
74 /// **What it does:** Checks for inclusive ranges where 1 is subtracted from
75 /// the upper bound, e.g., `x..=(y-1)`.
77 /// **Why is this bad?** The code is more readable with an exclusive range
80 /// **Known problems:** This will cause a warning that cannot be fixed if
81 /// the consumer of the range only accepts a specific range type, instead of
82 /// the generic `RangeBounds` trait
83 /// ([#3307](https://github.com/rust-lang/rust-clippy/issues/3307)).
87 /// for x..=(y-1) { .. }
89 /// Could be written as
95 "`x..=(y-1)` reads better as `x..y`"
98 declare_clippy_lint! {
99 /// **What it does:** Checks for range expressions `x..y` where both `x` and `y`
100 /// are constant and `x` is greater or equal to `y`.
102 /// **Why is this bad?** Empty ranges yield no values so iterating them is a no-op.
103 /// Moreover, trying to use a reversed range to index a slice will panic at run-time.
105 /// **Known problems:** None.
111 /// (10..=0).for_each(|x| println!("{}", x));
113 /// let arr = [1, 2, 3, 4, 5];
114 /// let sub = &arr[3..1];
120 /// (0..=10).rev().for_each(|x| println!("{}", x));
122 /// let arr = [1, 2, 3, 4, 5];
123 /// let sub = &arr[1..3];
126 pub REVERSED_EMPTY_RANGES,
128 "reversing the limits of range expressions, resulting in empty ranges"
131 declare_lint_pass!(Ranges => [
135 REVERSED_EMPTY_RANGES,
138 impl<'tcx> LateLintPass<'tcx> for Ranges {
139 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
140 if let ExprKind::MethodCall(ref path, _, ref args, _) = expr.kind {
141 let name = path.ident.as_str();
142 if name == "zip" && args.len() == 2 {
143 let iter = &args[0].kind;
144 let zip_arg = &args[1];
147 if let ExprKind::MethodCall(ref iter_path, _, ref iter_args , _) = *iter;
148 if iter_path.ident.name == sym!(iter);
149 // range expression in `.zip()` call: `0..x.len()`
150 if let Some(higher::Range { start: Some(start), end: Some(end), .. }) = higher::range(cx, zip_arg);
151 if is_integer_const(cx, start, 0);
153 if let ExprKind::MethodCall(ref len_path, _, ref len_args, _) = end.kind;
154 if len_path.ident.name == sym!(len) && len_args.len() == 1;
155 // `.iter()` and `.len()` called on same `Path`
156 if let ExprKind::Path(QPath::Resolved(_, ref iter_path)) = iter_args[0].kind;
157 if let ExprKind::Path(QPath::Resolved(_, ref len_path)) = len_args[0].kind;
158 if SpanlessEq::new(cx).eq_path_segments(&iter_path.segments, &len_path.segments);
163 &format!("It is more idiomatic to use `{}.iter().enumerate()`",
164 snippet(cx, iter_args[0].span, "_")));
170 check_exclusive_range_plus_one(cx, expr);
171 check_inclusive_range_minus_one(cx, expr);
172 check_reversed_empty_range(cx, expr);
176 // exclusive range plus one: `x..(y+1)`
177 fn check_exclusive_range_plus_one(cx: &LateContext<'_>, expr: &Expr<'_>) {
179 if let Some(higher::Range {
182 limits: RangeLimits::HalfOpen
183 }) = higher::range(cx, expr);
184 if let Some(y) = y_plus_one(cx, end);
186 let span = if expr.span.from_expansion() {
198 "an inclusive range would be more readable",
200 let start = start.map_or(String::new(), |x| Sugg::hir(cx, x, "x").to_string());
201 let end = Sugg::hir(cx, y, "y");
202 if let Some(is_wrapped) = &snippet_opt(cx, span) {
203 if is_wrapped.starts_with('(') && is_wrapped.ends_with(')') {
204 diag.span_suggestion(
207 format!("({}..={})", start, end),
208 Applicability::MaybeIncorrect,
211 diag.span_suggestion(
214 format!("{}..={}", start, end),
215 Applicability::MachineApplicable, // snippet
225 // inclusive range minus one: `x..=(y-1)`
226 fn check_inclusive_range_minus_one(cx: &LateContext<'_>, expr: &Expr<'_>) {
228 if let Some(higher::Range { start, end: Some(end), limits: RangeLimits::Closed }) = higher::range(cx, expr);
229 if let Some(y) = y_minus_one(cx, end);
235 "an exclusive range would be more readable",
237 let start = start.map_or(String::new(), |x| Sugg::hir(cx, x, "x").to_string());
238 let end = Sugg::hir(cx, y, "y");
239 diag.span_suggestion(
242 format!("{}..{}", start, end),
243 Applicability::MachineApplicable, // snippet
251 fn check_reversed_empty_range(cx: &LateContext<'_>, expr: &Expr<'_>) {
252 fn inside_indexing_expr(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
254 get_parent_expr(cx, expr),
256 kind: ExprKind::Index(..),
262 fn is_for_loop_arg(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
263 let mut cur_expr = expr;
264 while let Some(parent_expr) = get_parent_expr(cx, cur_expr) {
265 match higher::for_loop(parent_expr) {
266 Some((_, args, _)) if args.hir_id == expr.hir_id => return true,
267 _ => cur_expr = parent_expr,
274 fn is_empty_range(limits: RangeLimits, ordering: Ordering) -> bool {
276 RangeLimits::HalfOpen => ordering != Ordering::Less,
277 RangeLimits::Closed => ordering == Ordering::Greater,
282 if let Some(higher::Range { start: Some(start), end: Some(end), limits }) = higher::range(cx, expr);
283 let ty = cx.typeck_results().expr_ty(start);
284 if let ty::Int(_) | ty::Uint(_) = ty.kind;
285 if let Some((start_idx, _)) = constant(cx, cx.typeck_results(), start);
286 if let Some((end_idx, _)) = constant(cx, cx.typeck_results(), end);
287 if let Some(ordering) = Constant::partial_cmp(cx.tcx, ty, &start_idx, &end_idx);
288 if is_empty_range(limits, ordering);
290 if inside_indexing_expr(cx, expr) {
291 // Avoid linting `N..N` as it has proven to be useful, see #5689 and #5628 ...
292 if ordering != Ordering::Equal {
295 REVERSED_EMPTY_RANGES,
297 "this range is reversed and using it to index a slice will panic at run-time",
300 // ... except in for loop arguments for backwards compatibility with `reverse_range_loop`
301 } else if ordering != Ordering::Equal || is_for_loop_arg(cx, expr) {
304 REVERSED_EMPTY_RANGES,
306 "this range is empty so it will yield no values",
308 if ordering != Ordering::Equal {
309 let start_snippet = snippet(cx, start.span, "_");
310 let end_snippet = snippet(cx, end.span, "_");
311 let dots = match limits {
312 RangeLimits::HalfOpen => "..",
313 RangeLimits::Closed => "..="
316 diag.span_suggestion(
318 "consider using the following if you are attempting to iterate over this \
320 format!("({}{}{}).rev()", end_snippet, dots, start_snippet),
321 Applicability::MaybeIncorrect,
331 fn y_plus_one<'t>(cx: &LateContext<'_>, expr: &'t Expr<'_>) -> Option<&'t Expr<'t>> {
335 node: BinOpKind::Add, ..
340 if is_integer_const(cx, lhs, 1) {
342 } else if is_integer_const(cx, rhs, 1) {
352 fn y_minus_one<'t>(cx: &LateContext<'_>, expr: &'t Expr<'_>) -> Option<&'t Expr<'t>> {
356 node: BinOpKind::Sub, ..
360 ) if is_integer_const(cx, rhs, 1) => Some(lhs),