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.
57 /// for x..(y+1) { .. }
59 /// Could be written as
65 "`x..(y+1)` reads better as `x..=y`"
68 declare_clippy_lint! {
69 /// **What it does:** Checks for inclusive ranges where 1 is subtracted from
70 /// the upper bound, e.g., `x..=(y-1)`.
72 /// **Why is this bad?** The code is more readable with an exclusive range
75 /// **Known problems:** None.
79 /// for x..=(y-1) { .. }
81 /// Could be written as
87 "`x..=(y-1)` reads better as `x..y`"
90 declare_clippy_lint! {
91 /// **What it does:** Checks for range expressions `x..y` where both `x` and `y`
92 /// are constant and `x` is greater or equal to `y`.
94 /// **Why is this bad?** Empty ranges yield no values so iterating them is a no-op.
95 /// Moreover, trying to use a reversed range to index a slice will panic at run-time.
97 /// **Known problems:** None.
103 /// (10..=0).for_each(|x| println!("{}", x));
105 /// let arr = [1, 2, 3, 4, 5];
106 /// let sub = &arr[3..1];
112 /// (0..=10).rev().for_each(|x| println!("{}", x));
114 /// let arr = [1, 2, 3, 4, 5];
115 /// let sub = &arr[1..3];
118 pub REVERSED_EMPTY_RANGES,
120 "reversing the limits of range expressions, resulting in empty ranges"
123 declare_lint_pass!(Ranges => [
127 REVERSED_EMPTY_RANGES,
130 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Ranges {
131 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'_>) {
132 if let ExprKind::MethodCall(ref path, _, ref args) = expr.kind {
133 let name = path.ident.as_str();
134 if name == "zip" && args.len() == 2 {
135 let iter = &args[0].kind;
136 let zip_arg = &args[1];
139 if let ExprKind::MethodCall(ref iter_path, _, ref iter_args ) = *iter;
140 if iter_path.ident.name == sym!(iter);
141 // range expression in `.zip()` call: `0..x.len()`
142 if let Some(higher::Range { start: Some(start), end: Some(end), .. }) = higher::range(cx, zip_arg);
143 if is_integer_const(cx, start, 0);
145 if let ExprKind::MethodCall(ref len_path, _, ref len_args) = end.kind;
146 if len_path.ident.name == sym!(len) && len_args.len() == 1;
147 // `.iter()` and `.len()` called on same `Path`
148 if let ExprKind::Path(QPath::Resolved(_, ref iter_path)) = iter_args[0].kind;
149 if let ExprKind::Path(QPath::Resolved(_, ref len_path)) = len_args[0].kind;
150 if SpanlessEq::new(cx).eq_path_segments(&iter_path.segments, &len_path.segments);
155 &format!("It is more idiomatic to use `{}.iter().enumerate()`",
156 snippet(cx, iter_args[0].span, "_")));
162 check_exclusive_range_plus_one(cx, expr);
163 check_inclusive_range_minus_one(cx, expr);
164 check_reversed_empty_range(cx, expr);
168 // exclusive range plus one: `x..(y+1)`
169 fn check_exclusive_range_plus_one(cx: &LateContext<'_, '_>, expr: &Expr<'_>) {
171 if let Some(higher::Range {
174 limits: RangeLimits::HalfOpen
175 }) = higher::range(cx, expr);
176 if let Some(y) = y_plus_one(cx, end);
178 let span = if expr.span.from_expansion() {
190 "an inclusive range would be more readable",
192 let start = start.map_or(String::new(), |x| Sugg::hir(cx, x, "x").to_string());
193 let end = Sugg::hir(cx, y, "y");
194 if let Some(is_wrapped) = &snippet_opt(cx, span) {
195 if is_wrapped.starts_with('(') && is_wrapped.ends_with(')') {
196 diag.span_suggestion(
199 format!("({}..={})", start, end),
200 Applicability::MaybeIncorrect,
203 diag.span_suggestion(
206 format!("{}..={}", start, end),
207 Applicability::MachineApplicable, // snippet
217 // inclusive range minus one: `x..=(y-1)`
218 fn check_inclusive_range_minus_one(cx: &LateContext<'_, '_>, expr: &Expr<'_>) {
220 if let Some(higher::Range { start, end: Some(end), limits: RangeLimits::Closed }) = higher::range(cx, expr);
221 if let Some(y) = y_minus_one(cx, end);
227 "an exclusive range would be more readable",
229 let start = start.map_or(String::new(), |x| Sugg::hir(cx, x, "x").to_string());
230 let end = Sugg::hir(cx, y, "y");
231 diag.span_suggestion(
234 format!("{}..{}", start, end),
235 Applicability::MachineApplicable, // snippet
243 fn check_reversed_empty_range(cx: &LateContext<'_, '_>, expr: &Expr<'_>) {
244 fn inside_indexing_expr<'a>(cx: &'a LateContext<'_, '_>, expr: &Expr<'_>) -> Option<&'a Expr<'a>> {
245 match get_parent_expr(cx, expr) {
246 parent_expr @ Some(Expr {
247 kind: ExprKind::Index(..),
254 fn is_empty_range(limits: RangeLimits, ordering: Ordering) -> bool {
256 RangeLimits::HalfOpen => ordering != Ordering::Less,
257 RangeLimits::Closed => ordering == Ordering::Greater,
262 if let Some(higher::Range { start: Some(start), end: Some(end), limits }) = higher::range(cx, expr);
263 let ty = cx.tables.expr_ty(start);
264 if let ty::Int(_) | ty::Uint(_) = ty.kind;
265 if let Some((start_idx, _)) = constant(cx, cx.tables, start);
266 if let Some((end_idx, _)) = constant(cx, cx.tables, end);
267 if let Some(ordering) = Constant::partial_cmp(cx.tcx, ty, &start_idx, &end_idx);
268 if is_empty_range(limits, ordering);
270 if let Some(parent_expr) = inside_indexing_expr(cx, expr) {
271 let (reason, outcome) = if ordering == Ordering::Equal {
272 ("empty", "always yield an empty slice")
274 ("reversed", "panic at run-time")
279 REVERSED_EMPTY_RANGES,
281 &format!("this range is {} and using it to index a slice will {}", reason, outcome),
284 if ordering == Ordering::Equal;
285 if let ty::Slice(slice_ty) = cx.tables.expr_ty(parent_expr).kind;
287 diag.span_suggestion(
289 "if you want an empty slice, use",
290 format!("[] as &[{}]", slice_ty),
291 Applicability::MaybeIncorrect
300 REVERSED_EMPTY_RANGES,
302 "this range is empty so it will yield no values",
304 if ordering != Ordering::Equal {
305 let start_snippet = snippet(cx, start.span, "_");
306 let end_snippet = snippet(cx, end.span, "_");
307 let dots = match limits {
308 RangeLimits::HalfOpen => "..",
309 RangeLimits::Closed => "..="
312 diag.span_suggestion(
314 "consider using the following if you are attempting to iterate over this \
316 format!("({}{}{}).rev()", end_snippet, dots, start_snippet),
317 Applicability::MaybeIncorrect,
327 fn y_plus_one<'t>(cx: &LateContext<'_, '_>, expr: &'t Expr<'_>) -> Option<&'t Expr<'t>> {
331 node: BinOpKind::Add, ..
336 if is_integer_const(cx, lhs, 1) {
338 } else if is_integer_const(cx, rhs, 1) {
348 fn y_minus_one<'t>(cx: &LateContext<'_, '_>, expr: &'t Expr<'_>) -> Option<&'t Expr<'t>> {
352 node: BinOpKind::Sub, ..
356 ) if is_integer_const(cx, rhs, 1) => Some(lhs),