]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/len_zero.rs
Only check the assignment found at last
[rust.git] / clippy_lints / src / len_zero.rs
1 // Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution.
3 //
4 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
7 // option. This file may not be copied, modified, or distributed
8 // except according to those terms.
9
10 use crate::rustc::hir::def_id::DefId;
11 use crate::rustc::hir::*;
12 use crate::rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
13 use crate::rustc::ty;
14 use crate::rustc::{declare_tool_lint, lint_array};
15 use crate::rustc_data_structures::fx::FxHashSet;
16 use crate::rustc_errors::Applicability;
17 use crate::syntax::ast::{Lit, LitKind, Name};
18 use crate::syntax::source_map::{Span, Spanned};
19 use crate::utils::{get_item_name, in_macro, snippet_with_applicability, span_lint, span_lint_and_sugg, walk_ptrs_ty};
20
21 /// **What it does:** Checks for getting the length of something via `.len()`
22 /// just to compare to zero, and suggests using `.is_empty()` where applicable.
23 ///
24 /// **Why is this bad?** Some structures can answer `.is_empty()` much faster
25 /// than calculating their length. Notably, for slices, getting the length
26 /// requires a subtraction whereas `.is_empty()` is just a comparison. So it is
27 /// good to get into the habit of using `.is_empty()`, and having it is cheap.
28 /// Besides, it makes the intent clearer than a manual comparison.
29 ///
30 /// **Known problems:** None.
31 ///
32 /// **Example:**
33 /// ```rust
34 /// if x.len() == 0 {
35 ///     ..
36 /// }
37 /// if y.len() != 0 {
38 ///     ..
39 /// }
40 /// ```
41 /// instead use
42 /// ```rust
43 /// if x.len().is_empty() {
44 ///     ..
45 /// }
46 /// if !y.len().is_empty() {
47 ///     ..
48 /// }
49 /// ```
50 declare_clippy_lint! {
51 pub LEN_ZERO,
52 style,
53 "checking `.len() == 0` or `.len() > 0` (or similar) when `.is_empty()` \
54  could be used instead"
55 }
56
57 /// **What it does:** Checks for items that implement `.len()` but not
58 /// `.is_empty()`.
59 ///
60 /// **Why is this bad?** It is good custom to have both methods, because for
61 /// some data structures, asking about the length will be a costly operation,
62 /// whereas `.is_empty()` can usually answer in constant time. Also it used to
63 /// lead to false positives on the [`len_zero`](#len_zero) lint – currently that
64 /// lint will ignore such entities.
65 ///
66 /// **Known problems:** None.
67 ///
68 /// **Example:**
69 /// ```rust
70 /// impl X {
71 ///     pub fn len(&self) -> usize {
72 ///         ..
73 ///     }
74 /// }
75 /// ```
76 declare_clippy_lint! {
77     pub LEN_WITHOUT_IS_EMPTY,
78     style,
79     "traits or impls with a public `len` method but no corresponding `is_empty` method"
80 }
81
82 #[derive(Copy, Clone)]
83 pub struct LenZero;
84
85 impl LintPass for LenZero {
86     fn get_lints(&self) -> LintArray {
87         lint_array!(LEN_ZERO, LEN_WITHOUT_IS_EMPTY)
88     }
89 }
90
91 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for LenZero {
92     fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item) {
93         if in_macro(item.span) {
94             return;
95         }
96
97         match item.node {
98             ItemKind::Trait(_, _, _, _, ref trait_items) => check_trait_items(cx, item, trait_items),
99             ItemKind::Impl(_, _, _, _, None, _, ref impl_items) => check_impl_items(cx, item, impl_items),
100             _ => (),
101         }
102     }
103
104     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
105         if in_macro(expr.span) {
106             return;
107         }
108
109         if let ExprKind::Binary(Spanned { node: cmp, .. }, ref left, ref right) = expr.node {
110             match cmp {
111                 BinOpKind::Eq => {
112                     check_cmp(cx, expr.span, left, right, "", 0); // len == 0
113                     check_cmp(cx, expr.span, right, left, "", 0); // 0 == len
114                 },
115                 BinOpKind::Ne => {
116                     check_cmp(cx, expr.span, left, right, "!", 0); // len != 0
117                     check_cmp(cx, expr.span, right, left, "!", 0); // 0 != len
118                 },
119                 BinOpKind::Gt => {
120                     check_cmp(cx, expr.span, left, right, "!", 0); // len > 0
121                     check_cmp(cx, expr.span, right, left, "", 1); // 1 > len
122                 },
123                 BinOpKind::Lt => {
124                     check_cmp(cx, expr.span, left, right, "", 1); // len < 1
125                     check_cmp(cx, expr.span, right, left, "!", 0); // 0 < len
126                 },
127                 BinOpKind::Ge => check_cmp(cx, expr.span, left, right, "!", 1), // len <= 1
128                 BinOpKind::Le => check_cmp(cx, expr.span, right, left, "!", 1), // 1 >= len
129                 _ => (),
130             }
131         }
132     }
133 }
134
135 fn check_trait_items(cx: &LateContext<'_, '_>, visited_trait: &Item, trait_items: &[TraitItemRef]) {
136     fn is_named_self(cx: &LateContext<'_, '_>, item: &TraitItemRef, name: &str) -> bool {
137         item.ident.name == name
138             && if let AssociatedItemKind::Method { has_self } = item.kind {
139                 has_self && {
140                     let did = cx.tcx.hir().local_def_id(item.id.node_id);
141                     cx.tcx.fn_sig(did).inputs().skip_binder().len() == 1
142                 }
143             } else {
144                 false
145             }
146     }
147
148     // fill the set with current and super traits
149     fn fill_trait_set(traitt: DefId, set: &mut FxHashSet<DefId>, cx: &LateContext<'_, '_>) {
150         if set.insert(traitt) {
151             for supertrait in crate::rustc::traits::supertrait_def_ids(cx.tcx, traitt) {
152                 fill_trait_set(supertrait, set, cx);
153             }
154         }
155     }
156
157     if cx.access_levels.is_exported(visited_trait.id) && trait_items.iter().any(|i| is_named_self(cx, i, "len")) {
158         let mut current_and_super_traits = FxHashSet::default();
159         let visited_trait_def_id = cx.tcx.hir().local_def_id(visited_trait.id);
160         fill_trait_set(visited_trait_def_id, &mut current_and_super_traits, cx);
161
162         let is_empty_method_found = current_and_super_traits
163             .iter()
164             .flat_map(|&i| cx.tcx.associated_items(i))
165             .any(|i| {
166                 i.kind == ty::AssociatedKind::Method
167                     && i.method_has_self_argument
168                     && i.ident.name == "is_empty"
169                     && cx.tcx.fn_sig(i.def_id).inputs().skip_binder().len() == 1
170             });
171
172         if !is_empty_method_found {
173             span_lint(
174                 cx,
175                 LEN_WITHOUT_IS_EMPTY,
176                 visited_trait.span,
177                 &format!(
178                     "trait `{}` has a `len` method but no (possibly inherited) `is_empty` method",
179                     visited_trait.name
180                 ),
181             );
182         }
183     }
184 }
185
186 fn check_impl_items(cx: &LateContext<'_, '_>, item: &Item, impl_items: &[ImplItemRef]) {
187     fn is_named_self(cx: &LateContext<'_, '_>, item: &ImplItemRef, name: &str) -> bool {
188         item.ident.name == name
189             && if let AssociatedItemKind::Method { has_self } = item.kind {
190                 has_self && {
191                     let did = cx.tcx.hir().local_def_id(item.id.node_id);
192                     cx.tcx.fn_sig(did).inputs().skip_binder().len() == 1
193                 }
194             } else {
195                 false
196             }
197     }
198
199     let is_empty = if let Some(is_empty) = impl_items.iter().find(|i| is_named_self(cx, i, "is_empty")) {
200         if cx.access_levels.is_exported(is_empty.id.node_id) {
201             return;
202         } else {
203             "a private"
204         }
205     } else {
206         "no corresponding"
207     };
208
209     if let Some(i) = impl_items.iter().find(|i| is_named_self(cx, i, "len")) {
210         if cx.access_levels.is_exported(i.id.node_id) {
211             let def_id = cx.tcx.hir().local_def_id(item.id);
212             let ty = cx.tcx.type_of(def_id);
213
214             span_lint(
215                 cx,
216                 LEN_WITHOUT_IS_EMPTY,
217                 item.span,
218                 &format!(
219                     "item `{}` has a public `len` method but {} `is_empty` method",
220                     ty, is_empty
221                 ),
222             );
223         }
224     }
225 }
226
227 fn check_cmp(cx: &LateContext<'_, '_>, span: Span, method: &Expr, lit: &Expr, op: &str, compare_to: u32) {
228     if let (&ExprKind::MethodCall(ref method_path, _, ref args), &ExprKind::Lit(ref lit)) = (&method.node, &lit.node) {
229         // check if we are in an is_empty() method
230         if let Some(name) = get_item_name(cx, method) {
231             if name == "is_empty" {
232                 return;
233             }
234         }
235
236         check_len(cx, span, method_path.ident.name, args, lit, op, compare_to)
237     }
238 }
239
240 fn check_len(
241     cx: &LateContext<'_, '_>,
242     span: Span,
243     method_name: Name,
244     args: &[Expr],
245     lit: &Lit,
246     op: &str,
247     compare_to: u32,
248 ) {
249     if let Spanned {
250         node: LitKind::Int(lit, _),
251         ..
252     } = *lit
253     {
254         // check if length is compared to the specified number
255         if lit != u128::from(compare_to) {
256             return;
257         }
258
259         if method_name == "len" && args.len() == 1 && has_is_empty(cx, &args[0]) {
260             let mut applicability = Applicability::MachineApplicable;
261             span_lint_and_sugg(
262                 cx,
263                 LEN_ZERO,
264                 span,
265                 &format!("length comparison to {}", if compare_to == 0 { "zero" } else { "one" }),
266                 "using `is_empty` is clearer and more explicit",
267                 format!(
268                     "{}{}.is_empty()",
269                     op,
270                     snippet_with_applicability(cx, args[0].span, "_", &mut applicability)
271                 ),
272                 applicability,
273             );
274         }
275     }
276 }
277
278 /// Check if this type has an `is_empty` method.
279 fn has_is_empty(cx: &LateContext<'_, '_>, expr: &Expr) -> bool {
280     /// Get an `AssociatedItem` and return true if it matches `is_empty(self)`.
281     fn is_is_empty(cx: &LateContext<'_, '_>, item: &ty::AssociatedItem) -> bool {
282         if let ty::AssociatedKind::Method = item.kind {
283             if item.ident.name == "is_empty" {
284                 let sig = cx.tcx.fn_sig(item.def_id);
285                 let ty = sig.skip_binder();
286                 ty.inputs().len() == 1
287             } else {
288                 false
289             }
290         } else {
291             false
292         }
293     }
294
295     /// Check the inherent impl's items for an `is_empty(self)` method.
296     fn has_is_empty_impl(cx: &LateContext<'_, '_>, id: DefId) -> bool {
297         cx.tcx
298             .inherent_impls(id)
299             .iter()
300             .any(|imp| cx.tcx.associated_items(*imp).any(|item| is_is_empty(cx, &item)))
301     }
302
303     let ty = &walk_ptrs_ty(cx.tables.expr_ty(expr));
304     match ty.sty {
305         ty::Dynamic(ref tt, ..) => cx
306             .tcx
307             .associated_items(tt.principal().def_id())
308             .any(|item| is_is_empty(cx, &item)),
309         ty::Projection(ref proj) => has_is_empty_impl(cx, proj.item_def_id),
310         ty::Adt(id, _) => has_is_empty_impl(cx, id.did),
311         ty::Array(..) | ty::Slice(..) | ty::Str => true,
312         _ => false,
313     }
314 }