]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/len_zero.rs
fd58f86d42f66bcfae10c016f174c17da88abb9e
[rust.git] / clippy_lints / src / len_zero.rs
1 use rustc::lint::*;
2 use rustc::hir::def_id::DefId;
3 use rustc::ty;
4 use rustc::hir::*;
5 use syntax::ast::{Lit, LitKind, Name};
6 use syntax::codemap::{Span, Spanned};
7 use utils::{get_item_name, in_macro, snippet, span_lint, span_lint_and_then, walk_ptrs_ty};
8
9 /// **What it does:** Checks for getting the length of something via `.len()`
10 /// just to compare to zero, and suggests using `.is_empty()` where applicable.
11 ///
12 /// **Why is this bad?** Some structures can answer `.is_empty()` much faster
13 /// than calculating their length. So it is good to get into the habit of using
14 /// `.is_empty()`, and having it is cheap. Besides, it makes the intent clearer
15 /// than a comparison.
16 ///
17 /// **Known problems:** None.
18 ///
19 /// **Example:**
20 /// ```rust
21 /// if x.len() == 0 { .. }
22 /// ```
23 declare_lint! {
24     pub LEN_ZERO,
25     Warn,
26     "checking `.len() == 0` or `.len() > 0` (or similar) when `.is_empty()` \
27      could be used instead"
28 }
29
30 /// **What it does:** Checks for items that implement `.len()` but not
31 /// `.is_empty()`.
32 ///
33 /// **Why is this bad?** It is good custom to have both methods, because for
34 /// some data structures, asking about the length will be a costly operation,
35 /// whereas `.is_empty()` can usually answer in constant time. Also it used to
36 /// lead to false positives on the [`len_zero`](#len_zero) lint – currently that
37 /// lint will ignore such entities.
38 ///
39 /// **Known problems:** None.
40 ///
41 /// **Example:**
42 /// ```rust
43 /// impl X {
44 ///     pub fn len(&self) -> usize { .. }
45 /// }
46 /// ```
47 declare_lint! {
48     pub LEN_WITHOUT_IS_EMPTY,
49     Warn,
50     "traits or impls with a public `len` method but no corresponding `is_empty` method"
51 }
52
53 #[derive(Copy,Clone)]
54 pub struct LenZero;
55
56 impl LintPass for LenZero {
57     fn get_lints(&self) -> LintArray {
58         lint_array!(LEN_ZERO, LEN_WITHOUT_IS_EMPTY)
59     }
60 }
61
62 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for LenZero {
63     fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item) {
64         if in_macro(cx, item.span) {
65             return;
66         }
67
68         match item.node {
69             ItemTrait(_, _, _, ref trait_items) => check_trait_items(cx, item, trait_items),
70             ItemImpl(_, _, _, None, _, ref impl_items) => check_impl_items(cx, item, impl_items),
71             _ => (),
72         }
73     }
74
75     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
76         if in_macro(cx, expr.span) {
77             return;
78         }
79
80         if let ExprBinary(Spanned { node: cmp, .. }, ref left, ref right) = expr.node {
81             match cmp {
82                 BiEq => check_cmp(cx, expr.span, left, right, ""),
83                 BiGt | BiNe => check_cmp(cx, expr.span, left, right, "!"),
84                 _ => (),
85             }
86         }
87     }
88 }
89
90 fn check_trait_items(cx: &LateContext, item: &Item, trait_items: &[TraitItem]) {
91     fn is_named_self(item: &TraitItem, name: &str) -> bool {
92         &*item.name.as_str() == name &&
93         if let MethodTraitItem(ref sig, _) = item.node {
94             if sig.decl.has_self() {
95                 sig.decl.inputs.len() == 1
96             } else {
97                 false
98             }
99         } else {
100             false
101         }
102     }
103
104     if !trait_items.iter().any(|i| is_named_self(i, "is_empty")) {
105         if let Some(i) = trait_items.iter().find(|i| is_named_self(i, "len")) {
106             if cx.access_levels.is_exported(i.id) {
107                 span_lint(cx,
108                           LEN_WITHOUT_IS_EMPTY,
109                           i.span,
110                           &format!("trait `{}` has a `len` method but no `is_empty` method",
111                                    item.name));
112             }
113         }
114     }
115 }
116
117 fn check_impl_items(cx: &LateContext, item: &Item, impl_items: &[ImplItemRef]) {
118     fn is_named_self(cx: &LateContext, item: &ImplItemRef, name: &str) -> bool {
119         &*item.name.as_str() == name &&
120         if let AssociatedItemKind::Method { has_self } = item.kind {
121             has_self && {
122                 let did = cx.tcx.map.local_def_id(item.id.node_id);
123                 let impl_ty = cx.tcx.item_type(did);
124                 impl_ty.fn_args().skip_binder().len() == 1
125             }
126         } else {
127             false
128         }
129     }
130
131     let is_empty = if let Some(is_empty) = impl_items.iter().find(|i| is_named_self(cx, i, "is_empty")) {
132         if cx.access_levels.is_exported(is_empty.id.node_id) {
133             return;
134         } else {
135             "a private"
136         }
137     } else {
138         "no corresponding"
139     };
140
141     if let Some(i) = impl_items.iter().find(|i| is_named_self(cx, i, "len")) {
142         if cx.access_levels.is_exported(i.id.node_id) {
143             let def_id = cx.tcx.map.local_def_id(item.id);
144             let ty = cx.tcx.item_type(def_id);
145
146             span_lint(cx,
147                       LEN_WITHOUT_IS_EMPTY,
148                       i.span,
149                       &format!("item `{}` has a public `len` method but {} `is_empty` method",
150                                ty,
151                                is_empty));
152         }
153     }
154 }
155
156 fn check_cmp(cx: &LateContext, span: Span, left: &Expr, right: &Expr, op: &str) {
157     // check if we are in an is_empty() method
158     if let Some(name) = get_item_name(cx, left) {
159         if &*name.as_str() == "is_empty" {
160             return;
161         }
162     }
163     match (&left.node, &right.node) {
164         (&ExprLit(ref lit), &ExprMethodCall(ref method, _, ref args)) |
165         (&ExprMethodCall(ref method, _, ref args), &ExprLit(ref lit)) => {
166             check_len_zero(cx, span, &method.node, args, lit, op)
167         }
168         _ => (),
169     }
170 }
171
172 fn check_len_zero(cx: &LateContext, span: Span, name: &Name, args: &[Expr], lit: &Lit, op: &str) {
173     if let Spanned { node: LitKind::Int(0, _), .. } = *lit {
174         if &*name.as_str() == "len" && args.len() == 1 && has_is_empty(cx, &args[0]) {
175             span_lint_and_then(cx, LEN_ZERO, span, "length comparison to zero", |db| {
176                 db.span_suggestion(span,
177                                    "consider using `is_empty`",
178                                    format!("{}{}.is_empty()", op, snippet(cx, args[0].span, "_")));
179             });
180         }
181     }
182 }
183
184 /// Check if this type has an `is_empty` method.
185 fn has_is_empty(cx: &LateContext, expr: &Expr) -> bool {
186     /// Get an `AssociatedItem` and return true if it matches `is_empty(self)`.
187     fn is_is_empty(cx: &LateContext, item: &ty::AssociatedItem) -> bool {
188         if let ty::AssociatedKind::Method = item.kind {
189             if &*item.name.as_str() == "is_empty" {
190                 let ty = cx.tcx.item_type(item.def_id).fn_sig().skip_binder();
191                 ty.inputs.len() == 1
192             } else {
193                 false
194             }
195         } else {
196             false
197         }
198     }
199
200     /// Check the inherent impl's items for an `is_empty(self)` method.
201     fn has_is_empty_impl(cx: &LateContext, id: DefId) -> bool {
202         cx.tcx.inherent_impls.borrow().get(&id).map_or(false, |impls| impls.iter().any(|imp| {
203             cx.tcx.associated_items(*imp).any(|item| {
204                 is_is_empty(cx, &item)
205             })
206         }))
207     }
208
209     let ty = &walk_ptrs_ty(cx.tcx.tables().expr_ty(expr));
210     match ty.sty {
211         ty::TyDynamic(..) => {
212             cx.tcx
213               .associated_items(ty.ty_to_def_id().expect("trait impl not found"))
214               .any(|item| is_is_empty(cx, &item))
215         }
216         ty::TyProjection(_) => ty.ty_to_def_id().map_or(false, |id| has_is_empty_impl(cx, id)),
217         ty::TyAdt(id, _) => has_is_empty_impl(cx, id.did),
218         ty::TyArray(..) | ty::TyStr => true,
219         _ => false,
220     }
221 }