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