1 use if_chain::if_chain;
2 use rustc_errors::Applicability;
4 use rustc_lint::{LateContext, LateLintPass};
5 use rustc_session::{declare_lint_pass, declare_tool_lint};
6 use rustc_span::source_map::Spanned;
7 use syntax::ast::RangeLimits;
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())`.
50 /// for x..(y+1) { .. }
52 /// Could be written as
58 "`x..(y+1)` reads better as `x..=y`"
61 declare_clippy_lint! {
62 /// **What it does:** Checks for inclusive ranges where 1 is subtracted from
63 /// the upper bound, e.g., `x..=(y-1)`.
65 /// **Why is this bad?** The code is more readable with an exclusive range
68 /// **Known problems:** None.
72 /// for x..=(y-1) { .. }
74 /// Could be written as
80 "`x..=(y-1)` reads better as `x..y`"
83 declare_lint_pass!(Ranges => [
89 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Ranges {
90 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'_>) {
91 if let ExprKind::MethodCall(ref path, _, ref args) = expr.kind {
92 let name = path.ident.as_str();
93 if name == "zip" && args.len() == 2 {
94 let iter = &args[0].kind;
95 let zip_arg = &args[1];
98 if let ExprKind::MethodCall(ref iter_path, _, ref iter_args ) = *iter;
99 if iter_path.ident.name == sym!(iter);
100 // range expression in `.zip()` call: `0..x.len()`
101 if let Some(higher::Range { start: Some(start), end: Some(end), .. }) = higher::range(cx, zip_arg);
102 if is_integer_const(cx, start, 0);
104 if let ExprKind::MethodCall(ref len_path, _, ref len_args) = end.kind;
105 if len_path.ident.name == sym!(len) && len_args.len() == 1;
106 // `.iter()` and `.len()` called on same `Path`
107 if let ExprKind::Path(QPath::Resolved(_, ref iter_path)) = iter_args[0].kind;
108 if let ExprKind::Path(QPath::Resolved(_, ref len_path)) = len_args[0].kind;
109 if SpanlessEq::new(cx).eq_path_segments(&iter_path.segments, &len_path.segments);
114 &format!("It is more idiomatic to use `{}.iter().enumerate()`",
115 snippet(cx, iter_args[0].span, "_")));
121 check_exclusive_range_plus_one(cx, expr);
122 check_inclusive_range_minus_one(cx, expr);
126 // exclusive range plus one: `x..(y+1)`
127 fn check_exclusive_range_plus_one(cx: &LateContext<'_, '_>, expr: &Expr<'_>) {
129 if let Some(higher::Range {
132 limits: RangeLimits::HalfOpen
133 }) = higher::range(cx, expr);
134 if let Some(y) = y_plus_one(cx, end);
136 let span = if expr.span.from_expansion() {
148 "an inclusive range would be more readable",
150 let start = start.map_or(String::new(), |x| Sugg::hir(cx, x, "x").to_string());
151 let end = Sugg::hir(cx, y, "y");
152 if let Some(is_wrapped) = &snippet_opt(cx, span) {
153 if is_wrapped.starts_with('(') && is_wrapped.ends_with(')') {
157 format!("({}..={})", start, end),
158 Applicability::MaybeIncorrect,
164 format!("{}..={}", start, end),
165 Applicability::MachineApplicable, // snippet
175 // inclusive range minus one: `x..=(y-1)`
176 fn check_inclusive_range_minus_one(cx: &LateContext<'_, '_>, expr: &Expr<'_>) {
178 if let Some(higher::Range { start, end: Some(end), limits: RangeLimits::Closed }) = higher::range(cx, expr);
179 if let Some(y) = y_minus_one(cx, end);
185 "an exclusive range would be more readable",
187 let start = start.map_or(String::new(), |x| Sugg::hir(cx, x, "x").to_string());
188 let end = Sugg::hir(cx, y, "y");
192 format!("{}..{}", start, end),
193 Applicability::MachineApplicable, // snippet
201 fn y_plus_one<'t>(cx: &LateContext<'_, '_>, expr: &'t Expr<'_>) -> Option<&'t Expr<'t>> {
205 node: BinOpKind::Add, ..
210 if is_integer_const(cx, lhs, 1) {
212 } else if is_integer_const(cx, rhs, 1) {
222 fn y_minus_one<'t>(cx: &LateContext<'_, '_>, expr: &'t Expr<'_>) -> Option<&'t Expr<'t>> {
226 node: BinOpKind::Sub, ..
230 ) if is_integer_const(cx, rhs, 1) => Some(lhs),