1 use crate::utils::sugg::Sugg;
2 use crate::utils::{get_trait_def_id, higher, implements_trait, SpanlessEq};
3 use crate::utils::{is_integer_literal, paths, snippet, snippet_opt, span_lint, span_lint_and_then};
4 use if_chain::if_chain;
6 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
7 use rustc::{declare_tool_lint, lint_array};
8 use rustc_errors::Applicability;
9 use syntax::ast::RangeLimits;
10 use syntax::source_map::Spanned;
12 /// **What it does:** Checks for calling `.step_by(0)` on iterators,
13 /// which never terminates.
15 /// **Why is this bad?** This very much looks like an oversight, since with
16 /// `loop { .. }` there is an obvious better way to endlessly loop.
18 /// **Known problems:** None.
22 /// for x in (5..5).step_by(0) {
26 declare_clippy_lint! {
27 pub ITERATOR_STEP_BY_ZERO,
29 "using `Iterator::step_by(0)`, which produces an infinite iterator"
32 /// **What it does:** Checks for zipping a collection with the range of
35 /// **Why is this bad?** The code is better expressed with `.enumerate()`.
37 /// **Known problems:** None.
41 /// x.iter().zip(0..x.len())
43 declare_clippy_lint! {
44 pub RANGE_ZIP_WITH_LEN,
46 "zipping iterator with a range when `enumerate()` would do"
49 /// **What it does:** Checks for exclusive ranges where 1 is added to the
50 /// upper bound, e.g. `x..(y+1)`.
52 /// **Why is this bad?** The code is more readable with an inclusive range
55 /// **Known problems:** Will add unnecessary pair of parentheses when the
56 /// expression is not wrapped in a pair but starts with a opening parenthesis
57 /// and ends with a closing one.
58 /// I.e: `let _ = (f()+1)..(f()+1)` results in `let _ = ((f()+1)..=f())`.
62 /// for x..(y+1) { .. }
64 declare_clippy_lint! {
67 "`x..(y+1)` reads better as `x..=y`"
70 /// **What it does:** Checks for inclusive ranges where 1 is subtracted from
71 /// the upper bound, e.g. `x..=(y-1)`.
73 /// **Why is this bad?** The code is more readable with an exclusive range
76 /// **Known problems:** None.
80 /// for x..=(y-1) { .. }
82 declare_clippy_lint! {
85 "`x..=(y-1)` reads better as `x..y`"
88 #[derive(Copy, Clone)]
91 impl LintPass for Pass {
92 fn get_lints(&self) -> LintArray {
94 ITERATOR_STEP_BY_ZERO,
101 fn name(&self) -> &'static str {
106 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
107 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
108 if let ExprKind::MethodCall(ref path, _, ref args) = expr.node {
109 let name = path.ident.as_str();
111 // Range with step_by(0).
112 if name == "step_by" && args.len() == 2 && has_step_by(cx, &args[0]) {
113 use crate::consts::{constant, Constant};
114 if let Some((Constant::Int(0), _)) = constant(cx, cx.tables, &args[1]) {
117 ITERATOR_STEP_BY_ZERO,
119 "Iterator::step_by(0) will panic at runtime",
122 } else if name == "zip" && args.len() == 2 {
123 let iter = &args[0].node;
124 let zip_arg = &args[1];
127 if let ExprKind::MethodCall(ref iter_path, _, ref iter_args ) = *iter;
128 if iter_path.ident.name == "iter";
129 // range expression in .zip() call: 0..x.len()
130 if let Some(higher::Range { start: Some(start), end: Some(end), .. }) = higher::range(cx, zip_arg);
131 if is_integer_literal(start, 0);
133 if let ExprKind::MethodCall(ref len_path, _, ref len_args) = end.node;
134 if len_path.ident.name == "len" && len_args.len() == 1;
135 // .iter() and .len() called on same Path
136 if let ExprKind::Path(QPath::Resolved(_, ref iter_path)) = iter_args[0].node;
137 if let ExprKind::Path(QPath::Resolved(_, ref len_path)) = len_args[0].node;
138 if SpanlessEq::new(cx).eq_path_segments(&iter_path.segments, &len_path.segments);
143 &format!("It is more idiomatic to use {}.iter().enumerate()",
144 snippet(cx, iter_args[0].span, "_")));
150 // exclusive range plus one: x..(y+1)
152 if let Some(higher::Range {
155 limits: RangeLimits::HalfOpen
156 }) = higher::range(cx, expr);
157 if let Some(y) = y_plus_one(end);
163 "an inclusive range would be more readable",
165 let start = start.map_or(String::new(), |x| Sugg::hir(cx, x, "x").to_string());
166 let end = Sugg::hir(cx, y, "y");
167 if let Some(is_wrapped) = &snippet_opt(cx, expr.span) {
168 if is_wrapped.starts_with('(') && is_wrapped.ends_with(')') {
172 format!("({}..={})", start, end),
173 Applicability::MaybeIncorrect,
179 format!("{}..={}", start, end),
180 Applicability::MachineApplicable, // snippet
189 // inclusive range minus one: x..=(y-1)
191 if let Some(higher::Range { start, end: Some(end), limits: RangeLimits::Closed }) = higher::range(cx, expr);
192 if let Some(y) = y_minus_one(end);
198 "an exclusive range would be more readable",
200 let start = start.map_or(String::new(), |x| Sugg::hir(cx, x, "x").to_string());
201 let end = Sugg::hir(cx, y, "y");
205 format!("{}..{}", start, end),
206 Applicability::MachineApplicable, // snippet
215 fn has_step_by(cx: &LateContext<'_, '_>, expr: &Expr) -> bool {
216 // No need for walk_ptrs_ty here because step_by moves self, so it
217 // can't be called on a borrowed range.
218 let ty = cx.tables.expr_ty_adjusted(expr);
220 get_trait_def_id(cx, &paths::ITERATOR).map_or(false, |iterator_trait| implements_trait(cx, ty, iterator_trait, &[]))
223 fn y_plus_one(expr: &Expr) -> Option<&Expr> {
227 node: BinOpKind::Add, ..
232 if is_integer_literal(lhs, 1) {
234 } else if is_integer_literal(rhs, 1) {
244 fn y_minus_one(expr: &Expr) -> Option<&Expr> {
248 node: BinOpKind::Sub, ..
252 ) if is_integer_literal(rhs, 1) => Some(lhs),