]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/ranges.rs
Merge pull request #3735 from jsgf/setup-toolchain
[rust.git] / clippy_lints / src / ranges.rs
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;
5 use rustc::hir::*;
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;
11
12 /// **What it does:** Checks for calling `.step_by(0)` on iterators,
13 /// which never terminates.
14 ///
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.
17 ///
18 /// **Known problems:** None.
19 ///
20 /// **Example:**
21 /// ```rust
22 /// for x in (5..5).step_by(0) {
23 ///     ..
24 /// }
25 /// ```
26 declare_clippy_lint! {
27     pub ITERATOR_STEP_BY_ZERO,
28     correctness,
29     "using `Iterator::step_by(0)`, which produces an infinite iterator"
30 }
31
32 /// **What it does:** Checks for zipping a collection with the range of
33 /// `0.._.len()`.
34 ///
35 /// **Why is this bad?** The code is better expressed with `.enumerate()`.
36 ///
37 /// **Known problems:** None.
38 ///
39 /// **Example:**
40 /// ```rust
41 /// x.iter().zip(0..x.len())
42 /// ```
43 declare_clippy_lint! {
44     pub RANGE_ZIP_WITH_LEN,
45     complexity,
46     "zipping iterator with a range when `enumerate()` would do"
47 }
48
49 /// **What it does:** Checks for exclusive ranges where 1 is added to the
50 /// upper bound, e.g. `x..(y+1)`.
51 ///
52 /// **Why is this bad?** The code is more readable with an inclusive range
53 /// like `x..=y`.
54 ///
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())`.
59 ///
60 /// **Example:**
61 /// ```rust
62 /// for x..(y+1) { .. }
63 /// ```
64 declare_clippy_lint! {
65     pub RANGE_PLUS_ONE,
66     complexity,
67     "`x..(y+1)` reads better as `x..=y`"
68 }
69
70 /// **What it does:** Checks for inclusive ranges where 1 is subtracted from
71 /// the upper bound, e.g. `x..=(y-1)`.
72 ///
73 /// **Why is this bad?** The code is more readable with an exclusive range
74 /// like `x..y`.
75 ///
76 /// **Known problems:** None.
77 ///
78 /// **Example:**
79 /// ```rust
80 /// for x..=(y-1) { .. }
81 /// ```
82 declare_clippy_lint! {
83     pub RANGE_MINUS_ONE,
84     complexity,
85     "`x..=(y-1)` reads better as `x..y`"
86 }
87
88 #[derive(Copy, Clone)]
89 pub struct Pass;
90
91 impl LintPass for Pass {
92     fn get_lints(&self) -> LintArray {
93         lint_array!(
94             ITERATOR_STEP_BY_ZERO,
95             RANGE_ZIP_WITH_LEN,
96             RANGE_PLUS_ONE,
97             RANGE_MINUS_ONE
98         )
99     }
100
101     fn name(&self) -> &'static str {
102         "Ranges"
103     }
104 }
105
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();
110
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]) {
115                     span_lint(
116                         cx,
117                         ITERATOR_STEP_BY_ZERO,
118                         expr.span,
119                         "Iterator::step_by(0) will panic at runtime",
120                     );
121                 }
122             } else if name == "zip" && args.len() == 2 {
123                 let iter = &args[0].node;
124                 let zip_arg = &args[1];
125                 if_chain! {
126                     // .iter() call
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);
132                     // .len() call
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);
139                      then {
140                          span_lint(cx,
141                                    RANGE_ZIP_WITH_LEN,
142                                    expr.span,
143                                    &format!("It is more idiomatic to use {}.iter().enumerate()",
144                                             snippet(cx, iter_args[0].span, "_")));
145                     }
146                 }
147             }
148         }
149
150         // exclusive range plus one: x..(y+1)
151         if_chain! {
152             if let Some(higher::Range {
153                 start,
154                 end: Some(end),
155                 limits: RangeLimits::HalfOpen
156             }) = higher::range(cx, expr);
157             if let Some(y) = y_plus_one(end);
158             then {
159                 span_lint_and_then(
160                     cx,
161                     RANGE_PLUS_ONE,
162                     expr.span,
163                     "an inclusive range would be more readable",
164                     |db| {
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(')') {
169                                 db.span_suggestion(
170                                     expr.span,
171                                     "use",
172                                     format!("({}..={})", start, end),
173                                     Applicability::MaybeIncorrect,
174                                 );
175                             } else {
176                                 db.span_suggestion(
177                                     expr.span,
178                                     "use",
179                                     format!("{}..={}", start, end),
180                                     Applicability::MachineApplicable, // snippet
181                                 );
182                             }
183                         }
184                     },
185                 );
186             }
187         }
188
189         // inclusive range minus one: x..=(y-1)
190         if_chain! {
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);
193             then {
194                 span_lint_and_then(
195                     cx,
196                     RANGE_MINUS_ONE,
197                     expr.span,
198                     "an exclusive range would be more readable",
199                     |db| {
200                         let start = start.map_or(String::new(), |x| Sugg::hir(cx, x, "x").to_string());
201                         let end = Sugg::hir(cx, y, "y");
202                         db.span_suggestion(
203                             expr.span,
204                             "use",
205                             format!("{}..{}", start, end),
206                             Applicability::MachineApplicable, // snippet
207                         );
208                     },
209                 );
210             }
211         }
212     }
213 }
214
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);
219
220     get_trait_def_id(cx, &paths::ITERATOR).map_or(false, |iterator_trait| implements_trait(cx, ty, iterator_trait, &[]))
221 }
222
223 fn y_plus_one(expr: &Expr) -> Option<&Expr> {
224     match expr.node {
225         ExprKind::Binary(
226             Spanned {
227                 node: BinOpKind::Add, ..
228             },
229             ref lhs,
230             ref rhs,
231         ) => {
232             if is_integer_literal(lhs, 1) {
233                 Some(rhs)
234             } else if is_integer_literal(rhs, 1) {
235                 Some(lhs)
236             } else {
237                 None
238             }
239         },
240         _ => None,
241     }
242 }
243
244 fn y_minus_one(expr: &Expr) -> Option<&Expr> {
245     match expr.node {
246         ExprKind::Binary(
247             Spanned {
248                 node: BinOpKind::Sub, ..
249             },
250             ref lhs,
251             ref rhs,
252         ) if is_integer_literal(rhs, 1) => Some(lhs),
253         _ => None,
254     }
255 }