1 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
2 use rustc::{declare_tool_lint, lint_array};
3 use if_chain::if_chain;
5 use syntax::ast::RangeLimits;
6 use syntax::source_map::Spanned;
7 use crate::utils::{is_integer_literal, paths, snippet, span_lint, span_lint_and_then, snippet_opt};
8 use crate::utils::{get_trait_def_id, higher, implements_trait, SpanlessEq};
9 use crate::utils::sugg::Sugg;
11 /// **What it does:** Checks for calling `.step_by(0)` on iterators,
12 /// which never terminates.
14 /// **Why is this bad?** This very much looks like an oversight, since with
15 /// `loop { .. }` there is an obvious better way to endlessly loop.
17 /// **Known problems:** None.
21 /// for x in (5..5).step_by(0) { .. }
23 declare_clippy_lint! {
24 pub ITERATOR_STEP_BY_ZERO,
26 "using `Iterator::step_by(0)`, which produces an infinite iterator"
29 /// **What it does:** Checks for zipping a collection with the range of
32 /// **Why is this bad?** The code is better expressed with `.enumerate()`.
34 /// **Known problems:** None.
38 /// x.iter().zip(0..x.len())
40 declare_clippy_lint! {
41 pub RANGE_ZIP_WITH_LEN,
43 "zipping iterator with a range when `enumerate()` would do"
46 /// **What it does:** Checks for exclusive ranges where 1 is added to the
47 /// upper bound, e.g. `x..(y+1)`.
49 /// **Why is this bad?** The code is more readable with an inclusive range
52 /// **Known problems:** Will add unnecessary pair of parentheses when the
53 /// expression is not wrapped in a pair but starts with a opening parenthesis
54 /// and ends with a closing one.
55 /// I.e: `let _ = (f()+1)..(f()+1)` results in `let _ = ((f()+1)..=f())`.
59 /// for x..(y+1) { .. }
61 declare_clippy_lint! {
64 "`x..(y+1)` reads better as `x..=y`"
67 /// **What it does:** Checks for inclusive ranges where 1 is subtracted from
68 /// the upper bound, e.g. `x..=(y-1)`.
70 /// **Why is this bad?** The code is more readable with an exclusive range
73 /// **Known problems:** None.
77 /// for x..=(y-1) { .. }
79 declare_clippy_lint! {
82 "`x..=(y-1)` reads better as `x..y`"
85 #[derive(Copy, Clone)]
88 impl LintPass for Pass {
89 fn get_lints(&self) -> LintArray {
90 lint_array!(ITERATOR_STEP_BY_ZERO, RANGE_ZIP_WITH_LEN, RANGE_PLUS_ONE, RANGE_MINUS_ONE)
94 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
95 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
96 if let ExprKind::MethodCall(ref path, _, ref args) = expr.node {
97 let name = path.ident.as_str();
99 // Range with step_by(0).
100 if name == "step_by" && args.len() == 2 && has_step_by(cx, &args[0]) {
101 use crate::consts::{constant, Constant};
102 if let Some((Constant::Int(0), _)) = constant(cx, cx.tables, &args[1]) {
105 ITERATOR_STEP_BY_ZERO,
107 "Iterator::step_by(0) will panic at runtime",
110 } else if name == "zip" && args.len() == 2 {
111 let iter = &args[0].node;
112 let zip_arg = &args[1];
115 if let ExprKind::MethodCall(ref iter_path, _, ref iter_args ) = *iter;
116 if iter_path.ident.name == "iter";
117 // range expression in .zip() call: 0..x.len()
118 if let Some(higher::Range { start: Some(start), end: Some(end), .. }) = higher::range(cx, zip_arg);
119 if is_integer_literal(start, 0);
121 if let ExprKind::MethodCall(ref len_path, _, ref len_args) = end.node;
122 if len_path.ident.name == "len" && len_args.len() == 1;
123 // .iter() and .len() called on same Path
124 if let ExprKind::Path(QPath::Resolved(_, ref iter_path)) = iter_args[0].node;
125 if let ExprKind::Path(QPath::Resolved(_, ref len_path)) = len_args[0].node;
126 if SpanlessEq::new(cx).eq_path_segments(&iter_path.segments, &len_path.segments);
131 &format!("It is more idiomatic to use {}.iter().enumerate()",
132 snippet(cx, iter_args[0].span, "_")));
138 // exclusive range plus one: x..(y+1)
140 if let Some(higher::Range { start, end: Some(end), limits: RangeLimits::HalfOpen }) = higher::range(cx, expr);
141 if let Some(y) = y_plus_one(end);
147 "an inclusive range would be more readable",
149 let start = start.map_or("".to_owned(), |x| Sugg::hir(cx, x, "x").to_string());
150 let end = Sugg::hir(cx, y, "y");
151 if let Some(is_wrapped) = &snippet_opt(cx, expr.span) {
152 if is_wrapped.starts_with('(') && is_wrapped.ends_with(')') {
153 db.span_suggestion(expr.span,
155 format!("({}..={})", start, end));
157 db.span_suggestion(expr.span,
159 format!("{}..={}", start, end));
167 // inclusive range minus one: x..=(y-1)
169 if let Some(higher::Range { start, end: Some(end), limits: RangeLimits::Closed }) = higher::range(cx, expr);
170 if let Some(y) = y_minus_one(end);
176 "an exclusive range would be more readable",
178 let start = start.map_or("".to_owned(), |x| Sugg::hir(cx, x, "x").to_string());
179 let end = Sugg::hir(cx, y, "y");
180 db.span_suggestion(expr.span,
182 format!("{}..{}", start, end));
190 fn has_step_by(cx: &LateContext<'_, '_>, expr: &Expr) -> bool {
191 // No need for walk_ptrs_ty here because step_by moves self, so it
192 // can't be called on a borrowed range.
193 let ty = cx.tables.expr_ty_adjusted(expr);
195 get_trait_def_id(cx, &paths::ITERATOR).map_or(false, |iterator_trait| implements_trait(cx, ty, iterator_trait, &[]))
198 fn y_plus_one(expr: &Expr) -> Option<&Expr> {
200 ExprKind::Binary(Spanned { node: BinOpKind::Add, .. }, ref lhs, ref rhs) => if is_integer_literal(lhs, 1) {
202 } else if is_integer_literal(rhs, 1) {
211 fn y_minus_one(expr: &Expr) -> Option<&Expr> {
213 ExprKind::Binary(Spanned { node: BinOpKind::Sub, .. }, ref lhs, ref rhs) if is_integer_literal(rhs, 1) => Some(lhs),