1 use if_chain::if_chain;
2 use rustc_ast::ast::RangeLimits;
3 use rustc_errors::Applicability;
4 use rustc_hir::{BinOpKind, Expr, ExprKind, QPath};
5 use rustc_lint::{LateContext, LateLintPass};
6 use rustc_session::{declare_lint_pass, declare_tool_lint};
7 use rustc_span::source_map::Spanned;
9 use crate::utils::sugg::Sugg;
10 use crate::utils::{higher, SpanlessEq};
11 use crate::utils::{is_integer_const, snippet, snippet_opt, span_lint, span_lint_and_then};
13 declare_clippy_lint! {
14 /// **What it does:** Checks for zipping a collection with the range of
17 /// **Why is this bad?** The code is better expressed with `.enumerate()`.
19 /// **Known problems:** None.
23 /// # let x = vec![1];
24 /// x.iter().zip(0..x.len());
26 /// Could be written as
28 /// # let x = vec![1];
29 /// x.iter().enumerate();
31 pub RANGE_ZIP_WITH_LEN,
33 "zipping iterator with a range when `enumerate()` would do"
36 declare_clippy_lint! {
37 /// **What it does:** Checks for exclusive ranges where 1 is added to the
38 /// upper bound, e.g., `x..(y+1)`.
40 /// **Why is this bad?** The code is more readable with an inclusive range
43 /// **Known problems:** Will add unnecessary pair of parentheses when the
44 /// expression is not wrapped in a pair but starts with a opening parenthesis
45 /// and ends with a closing one.
46 /// I.e., `let _ = (f()+1)..(f()+1)` results in `let _ = ((f()+1)..=f())`.
48 /// Also in many cases, inclusive ranges are still slower to run than
49 /// exclusive ranges, because they essentially add an extra branch that
50 /// LLVM may fail to hoist out of the loop.
54 /// for x..(y+1) { .. }
56 /// Could be written as
62 "`x..(y+1)` reads better as `x..=y`"
65 declare_clippy_lint! {
66 /// **What it does:** Checks for inclusive ranges where 1 is subtracted from
67 /// the upper bound, e.g., `x..=(y-1)`.
69 /// **Why is this bad?** The code is more readable with an exclusive range
72 /// **Known problems:** None.
76 /// for x..=(y-1) { .. }
78 /// Could be written as
84 "`x..=(y-1)` reads better as `x..y`"
87 declare_lint_pass!(Ranges => [
93 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Ranges {
94 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'_>) {
95 if let ExprKind::MethodCall(ref path, _, ref args) = expr.kind {
96 let name = path.ident.as_str();
97 if name == "zip" && args.len() == 2 {
98 let iter = &args[0].kind;
99 let zip_arg = &args[1];
102 if let ExprKind::MethodCall(ref iter_path, _, ref iter_args ) = *iter;
103 if iter_path.ident.name == sym!(iter);
104 // range expression in `.zip()` call: `0..x.len()`
105 if let Some(higher::Range { start: Some(start), end: Some(end), .. }) = higher::range(cx, zip_arg);
106 if is_integer_const(cx, start, 0);
108 if let ExprKind::MethodCall(ref len_path, _, ref len_args) = end.kind;
109 if len_path.ident.name == sym!(len) && len_args.len() == 1;
110 // `.iter()` and `.len()` called on same `Path`
111 if let ExprKind::Path(QPath::Resolved(_, ref iter_path)) = iter_args[0].kind;
112 if let ExprKind::Path(QPath::Resolved(_, ref len_path)) = len_args[0].kind;
113 if SpanlessEq::new(cx).eq_path_segments(&iter_path.segments, &len_path.segments);
118 &format!("It is more idiomatic to use `{}.iter().enumerate()`",
119 snippet(cx, iter_args[0].span, "_")));
125 check_exclusive_range_plus_one(cx, expr);
126 check_inclusive_range_minus_one(cx, expr);
130 // exclusive range plus one: `x..(y+1)`
131 fn check_exclusive_range_plus_one(cx: &LateContext<'_, '_>, expr: &Expr<'_>) {
133 if let Some(higher::Range {
136 limits: RangeLimits::HalfOpen
137 }) = higher::range(cx, expr);
138 if let Some(y) = y_plus_one(cx, end);
140 let span = if expr.span.from_expansion() {
152 "an inclusive range would be more readable",
154 let start = start.map_or(String::new(), |x| Sugg::hir(cx, x, "x").to_string());
155 let end = Sugg::hir(cx, y, "y");
156 if let Some(is_wrapped) = &snippet_opt(cx, span) {
157 if is_wrapped.starts_with('(') && is_wrapped.ends_with(')') {
158 diag.span_suggestion(
161 format!("({}..={})", start, end),
162 Applicability::MaybeIncorrect,
165 diag.span_suggestion(
168 format!("{}..={}", start, end),
169 Applicability::MachineApplicable, // snippet
179 // inclusive range minus one: `x..=(y-1)`
180 fn check_inclusive_range_minus_one(cx: &LateContext<'_, '_>, expr: &Expr<'_>) {
182 if let Some(higher::Range { start, end: Some(end), limits: RangeLimits::Closed }) = higher::range(cx, expr);
183 if let Some(y) = y_minus_one(cx, end);
189 "an exclusive range would be more readable",
191 let start = start.map_or(String::new(), |x| Sugg::hir(cx, x, "x").to_string());
192 let end = Sugg::hir(cx, y, "y");
193 diag.span_suggestion(
196 format!("{}..{}", start, end),
197 Applicability::MachineApplicable, // snippet
205 fn y_plus_one<'t>(cx: &LateContext<'_, '_>, expr: &'t Expr<'_>) -> Option<&'t Expr<'t>> {
209 node: BinOpKind::Add, ..
214 if is_integer_const(cx, lhs, 1) {
216 } else if is_integer_const(cx, rhs, 1) {
226 fn y_minus_one<'t>(cx: &LateContext<'_, '_>, expr: &'t Expr<'_>) -> Option<&'t Expr<'t>> {
230 node: BinOpKind::Sub, ..
234 ) if is_integer_const(cx, rhs, 1) => Some(lhs),