]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/len_zero.rs
Merge pull request #3269 from rust-lang-nursery/relicense
[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
11 use crate::rustc::hir::def_id::DefId;
12 use crate::rustc::hir::*;
13 use crate::rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
14 use crate::rustc::{declare_tool_lint, lint_array};
15 use crate::rustc::ty;
16 use crate::rustc_data_structures::fx::FxHashSet;
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, 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 /// if y.len() != 0 { .. }
36 /// ```
37 /// instead use
38 /// ```rust
39 /// if x.len().is_empty() { .. }
40 /// if !y.len().is_empty() { .. }
41 /// ```
42 declare_clippy_lint! {
43     pub LEN_ZERO,
44     style,
45     "checking `.len() == 0` or `.len() > 0` (or similar) when `.is_empty()` \
46      could be used instead"
47 }
48
49 /// **What it does:** Checks for items that implement `.len()` but not
50 /// `.is_empty()`.
51 ///
52 /// **Why is this bad?** It is good custom to have both methods, because for
53 /// some data structures, asking about the length will be a costly operation,
54 /// whereas `.is_empty()` can usually answer in constant time. Also it used to
55 /// lead to false positives on the [`len_zero`](#len_zero) lint – currently that
56 /// lint will ignore such entities.
57 ///
58 /// **Known problems:** None.
59 ///
60 /// **Example:**
61 /// ```rust
62 /// impl X {
63 ///     pub fn len(&self) -> usize { .. }
64 /// }
65 /// ```
66 declare_clippy_lint! {
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
81 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for LenZero {
82     fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item) {
83         if in_macro(item.span) {
84             return;
85         }
86
87         match item.node {
88             ItemKind::Trait(_, _, _, _, ref trait_items) => check_trait_items(cx, item, trait_items),
89             ItemKind::Impl(_, _, _, _, None, _, ref impl_items) => check_impl_items(cx, item, impl_items),
90             _ => (),
91         }
92     }
93
94     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
95         if in_macro(expr.span) {
96             return;
97         }
98
99         if let ExprKind::Binary(Spanned { node: cmp, .. }, ref left, ref right) = expr.node {
100             match cmp {
101                 BinOpKind::Eq => {
102                     check_cmp(cx, expr.span, left, right, "", 0); // len == 0
103                     check_cmp(cx, expr.span, right, left, "", 0); // 0 == len
104                 },
105                 BinOpKind::Ne => {
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::Gt => {
110                     check_cmp(cx, expr.span, left, right, "!", 0); // len > 0
111                     check_cmp(cx, expr.span, right, left, "", 1); // 1 > len
112                 },
113                 BinOpKind::Lt => {
114                     check_cmp(cx, expr.span, left, right, "", 1); // len < 1
115                     check_cmp(cx, expr.span, right, left, "!", 0); // 0 < len
116                 },
117                 BinOpKind::Ge => check_cmp(cx, expr.span, left, right, "!", 1), // len <= 1
118                 BinOpKind::Le => check_cmp(cx, expr.span, right, left, "!", 1), // 1 >= len
119                 _ => (),
120             }
121         }
122     }
123 }
124
125 fn check_trait_items(cx: &LateContext<'_, '_>, visited_trait: &Item, trait_items: &[TraitItemRef]) {
126     fn is_named_self(cx: &LateContext<'_, '_>, item: &TraitItemRef, name: &str) -> bool {
127         item.ident.name == name && if let AssociatedItemKind::Method { has_self } = item.kind {
128             has_self && {
129                 let did = cx.tcx.hir.local_def_id(item.id.node_id);
130                 cx.tcx.fn_sig(did).inputs().skip_binder().len() == 1
131             }
132         } else {
133             false
134         }
135     }
136
137     // fill the set with current and super traits
138     fn fill_trait_set(traitt: DefId, set: &mut FxHashSet<DefId>, cx: &LateContext<'_, '_>) {
139         if set.insert(traitt) {
140             for supertrait in crate::rustc::traits::supertrait_def_ids(cx.tcx, traitt) {
141                 fill_trait_set(supertrait, set, cx);
142             }
143         }
144     }
145
146     if cx.access_levels.is_exported(visited_trait.id) && trait_items.iter().any(|i| is_named_self(cx, i, "len")) {
147         let mut current_and_super_traits = FxHashSet::default();
148         let visited_trait_def_id = cx.tcx.hir.local_def_id(visited_trait.id);
149         fill_trait_set(visited_trait_def_id, &mut current_and_super_traits, cx);
150
151         let is_empty_method_found = current_and_super_traits
152             .iter()
153             .flat_map(|&i| cx.tcx.associated_items(i))
154             .any(|i| {
155                 i.kind == ty::AssociatedKind::Method && i.method_has_self_argument && i.ident.name == "is_empty"
156                     && cx.tcx.fn_sig(i.def_id).inputs().skip_binder().len() == 1
157             });
158
159         if !is_empty_method_found {
160             span_lint(
161                 cx,
162                 LEN_WITHOUT_IS_EMPTY,
163                 visited_trait.span,
164                 &format!(
165                     "trait `{}` has a `len` method but no (possibly inherited) `is_empty` method",
166                     visited_trait.name
167                 ),
168             );
169         }
170     }
171 }
172
173 fn check_impl_items(cx: &LateContext<'_, '_>, item: &Item, impl_items: &[ImplItemRef]) {
174     fn is_named_self(cx: &LateContext<'_, '_>, item: &ImplItemRef, name: &str) -> bool {
175         item.ident.name == name && if let AssociatedItemKind::Method { has_self } = item.kind {
176             has_self && {
177                 let did = cx.tcx.hir.local_def_id(item.id.node_id);
178                 cx.tcx.fn_sig(did).inputs().skip_binder().len() == 1
179             }
180         } else {
181             false
182         }
183     }
184
185     let is_empty = if let Some(is_empty) = impl_items.iter().find(|i| is_named_self(cx, i, "is_empty")) {
186         if cx.access_levels.is_exported(is_empty.id.node_id) {
187             return;
188         } else {
189             "a private"
190         }
191     } else {
192         "no corresponding"
193     };
194
195     if let Some(i) = impl_items.iter().find(|i| is_named_self(cx, i, "len")) {
196         if cx.access_levels.is_exported(i.id.node_id) {
197             let def_id = cx.tcx.hir.local_def_id(item.id);
198             let ty = cx.tcx.type_of(def_id);
199
200             span_lint(
201                 cx,
202                 LEN_WITHOUT_IS_EMPTY,
203                 item.span,
204                 &format!(
205                     "item `{}` has a public `len` method but {} `is_empty` method",
206                     ty, is_empty
207                 ),
208             );
209         }
210     }
211 }
212
213 fn check_cmp(cx: &LateContext<'_, '_>, span: Span, method: &Expr, lit: &Expr, op: &str, compare_to: u32) {
214     if let (&ExprKind::MethodCall(ref method_path, _, ref args), &ExprKind::Lit(ref lit)) = (&method.node, &lit.node) {
215         // check if we are in an is_empty() method
216         if let Some(name) = get_item_name(cx, method) {
217             if name == "is_empty" {
218                 return;
219             }
220         }
221
222         check_len(cx, span, method_path.ident.name, args, lit, op, compare_to)
223     }
224 }
225
226 fn check_len(cx: &LateContext<'_, '_>, span: Span, method_name: Name, args: &[Expr], lit: &Lit, op: &str, compare_to: u32) {
227     if let Spanned {
228         node: LitKind::Int(lit, _),
229         ..
230     } = *lit
231     {
232         // check if length is compared to the specified number
233         if lit != u128::from(compare_to) {
234             return;
235         }
236
237         if method_name == "len" && args.len() == 1 && has_is_empty(cx, &args[0]) {
238             span_lint_and_sugg(
239                 cx,
240                 LEN_ZERO,
241                 span,
242                 &format!("length comparison to {}", if compare_to == 0 { "zero" } else { "one" }),
243                 "using `is_empty` is more concise",
244                 format!("{}{}.is_empty()", op, snippet(cx, args[0].span, "_")),
245             );
246         }
247     }
248 }
249
250 /// Check if this type has an `is_empty` method.
251 fn has_is_empty(cx: &LateContext<'_, '_>, expr: &Expr) -> bool {
252     /// Get an `AssociatedItem` and return true if it matches `is_empty(self)`.
253     fn is_is_empty(cx: &LateContext<'_, '_>, item: &ty::AssociatedItem) -> bool {
254         if let ty::AssociatedKind::Method = item.kind {
255             if item.ident.name == "is_empty" {
256                 let sig = cx.tcx.fn_sig(item.def_id);
257                 let ty = sig.skip_binder();
258                 ty.inputs().len() == 1
259             } else {
260                 false
261             }
262         } else {
263             false
264         }
265     }
266
267     /// Check the inherent impl's items for an `is_empty(self)` method.
268     fn has_is_empty_impl(cx: &LateContext<'_, '_>, id: DefId) -> bool {
269         cx.tcx.inherent_impls(id).iter().any(|imp| {
270             cx.tcx
271                 .associated_items(*imp)
272                 .any(|item| is_is_empty(cx, &item))
273         })
274     }
275
276     let ty = &walk_ptrs_ty(cx.tables.expr_ty(expr));
277     match ty.sty {
278         ty::Dynamic(ref tt, ..) => cx.tcx
279             .associated_items(tt.principal().expect("trait impl not found").def_id())
280             .any(|item| is_is_empty(cx, &item)),
281         ty::Projection(ref proj) => has_is_empty_impl(cx, proj.item_def_id),
282         ty::Adt(id, _) => has_is_empty_impl(cx, id.did),
283         ty::Array(..) | ty::Slice(..) | ty::Str => true,
284         _ => false,
285     }
286 }