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