1 use if_chain::if_chain;
2 use rustc::declare_lint_pass;
4 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
5 use rustc_errors::Applicability;
6 use rustc_session::declare_tool_lint;
7 use syntax::ast::RangeLimits;
8 use syntax::source_map::Spanned;
10 use crate::utils::sugg::Sugg;
11 use crate::utils::{higher, SpanlessEq};
12 use crate::utils::{is_integer_const, snippet, snippet_opt, span_lint, span_lint_and_then};
14 declare_clippy_lint! {
15 /// **What it does:** Checks for zipping a collection with the range of
18 /// **Why is this bad?** The code is better expressed with `.enumerate()`.
20 /// **Known problems:** None.
24 /// # let x = vec![1];
25 /// x.iter().zip(0..x.len());
27 /// Could be written as
29 /// # let x = vec![1];
30 /// x.iter().enumerate();
32 pub RANGE_ZIP_WITH_LEN,
34 "zipping iterator with a range when `enumerate()` would do"
37 declare_clippy_lint! {
38 /// **What it does:** Checks for exclusive ranges where 1 is added to the
39 /// upper bound, e.g., `x..(y+1)`.
41 /// **Why is this bad?** The code is more readable with an inclusive range
44 /// **Known problems:** Will add unnecessary pair of parentheses when the
45 /// expression is not wrapped in a pair but starts with a opening parenthesis
46 /// and ends with a closing one.
47 /// I.e., `let _ = (f()+1)..(f()+1)` results in `let _ = ((f()+1)..=f())`.
51 /// for x..(y+1) { .. }
53 /// Could be written as
59 "`x..(y+1)` reads better as `x..=y`"
62 declare_clippy_lint! {
63 /// **What it does:** Checks for inclusive ranges where 1 is subtracted from
64 /// the upper bound, e.g., `x..=(y-1)`.
66 /// **Why is this bad?** The code is more readable with an exclusive range
69 /// **Known problems:** None.
73 /// for x..=(y-1) { .. }
75 /// Could be written as
81 "`x..=(y-1)` reads better as `x..y`"
84 declare_lint_pass!(Ranges => [
90 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Ranges {
91 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
92 if let ExprKind::MethodCall(ref path, _, ref args) = expr.kind {
93 let name = path.ident.as_str();
94 if name == "zip" && args.len() == 2 {
95 let iter = &args[0].kind;
96 let zip_arg = &args[1];
99 if let ExprKind::MethodCall(ref iter_path, _, ref iter_args ) = *iter;
100 if iter_path.ident.name == sym!(iter);
101 // range expression in `.zip()` call: `0..x.len()`
102 if let Some(higher::Range { start: Some(start), end: Some(end), .. }) = higher::range(cx, zip_arg);
103 if is_integer_const(cx, start, 0);
105 if let ExprKind::MethodCall(ref len_path, _, ref len_args) = end.kind;
106 if len_path.ident.name == sym!(len) && len_args.len() == 1;
107 // `.iter()` and `.len()` called on same `Path`
108 if let ExprKind::Path(QPath::Resolved(_, ref iter_path)) = iter_args[0].kind;
109 if let ExprKind::Path(QPath::Resolved(_, ref len_path)) = len_args[0].kind;
110 if SpanlessEq::new(cx).eq_path_segments(&iter_path.segments, &len_path.segments);
115 &format!("It is more idiomatic to use {}.iter().enumerate()",
116 snippet(cx, iter_args[0].span, "_")));
122 check_exclusive_range_plus_one(cx, expr);
123 check_inclusive_range_minus_one(cx, expr);
127 // exclusive range plus one: `x..(y+1)`
128 fn check_exclusive_range_plus_one(cx: &LateContext<'_, '_>, expr: &Expr) {
130 if let Some(higher::Range {
133 limits: RangeLimits::HalfOpen
134 }) = higher::range(cx, expr);
135 if let Some(y) = y_plus_one(cx, end);
137 let span = if expr.span.from_expansion() {
149 "an inclusive range would be more readable",
151 let start = start.map_or(String::new(), |x| Sugg::hir(cx, x, "x").to_string());
152 let end = Sugg::hir(cx, y, "y");
153 if let Some(is_wrapped) = &snippet_opt(cx, span) {
154 if is_wrapped.starts_with('(') && is_wrapped.ends_with(')') {
158 format!("({}..={})", start, end),
159 Applicability::MaybeIncorrect,
165 format!("{}..={}", start, end),
166 Applicability::MachineApplicable, // snippet
176 // inclusive range minus one: `x..=(y-1)`
177 fn check_inclusive_range_minus_one(cx: &LateContext<'_, '_>, expr: &Expr) {
179 if let Some(higher::Range { start, end: Some(end), limits: RangeLimits::Closed }) = higher::range(cx, expr);
180 if let Some(y) = y_minus_one(cx, end);
186 "an exclusive range would be more readable",
188 let start = start.map_or(String::new(), |x| Sugg::hir(cx, x, "x").to_string());
189 let end = Sugg::hir(cx, y, "y");
193 format!("{}..{}", start, end),
194 Applicability::MachineApplicable, // snippet
202 fn y_plus_one<'t>(cx: &LateContext<'_, '_>, expr: &'t Expr) -> Option<&'t Expr> {
206 node: BinOpKind::Add, ..
211 if is_integer_const(cx, lhs, 1) {
213 } else if is_integer_const(cx, rhs, 1) {
223 fn y_minus_one<'t>(cx: &LateContext<'_, '_>, expr: &'t Expr) -> Option<&'t Expr> {
227 node: BinOpKind::Sub, ..
231 ) if is_integer_const(cx, rhs, 1) => Some(lhs),