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