]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/len_zero.rs
Rustup to rustc 1.16.0-nightly (468227129 2017-01-03): Body fixes for rustup
[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     is_self, has_self};
9
10 /// **What it does:** Checks for getting the length of something via `.len()`
11 /// just to compare to zero, and suggests using `.is_empty()` where applicable.
12 ///
13 /// **Why is this bad?** Some structures can answer `.is_empty()` much faster
14 /// than calculating their length. So it is good to get into the habit of using
15 /// `.is_empty()`, and having it is cheap. Besides, it makes the intent clearer
16 /// than a 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(cx, 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(cx, 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: &[TraitItem]) {
92     fn is_named_self(item: &TraitItem, name: &str) -> bool {
93         if let TraitItemKind::Method(ref sig, _) = item.node {
94             return has_self(&*sig.decl) && &*item.name.as_str() == name && sig.decl.inputs.len() == 1;
95         }
96         false
97     }
98
99     if !trait_items.iter().any(|i| is_named_self(i, "is_empty")) {
100         if let Some(i) = trait_items.iter().find(|i| is_named_self(i, "len")) {
101             if cx.access_levels.is_exported(i.id) {
102                 span_lint(cx,
103                           LEN_WITHOUT_IS_EMPTY,
104                           i.span,
105                           &format!("trait `{}` has a `len` method but no `is_empty` method", item.name));
106             }
107         }
108     }
109 }
110
111 fn check_impl_items(cx: &LateContext, item: &Item, impl_items: &[ImplItemRef]) {
112     fn is_named_self(cx: &LateContext, item: &ImplItemRef, name: &str) -> bool {
113         &*item.name.as_str() == name &&
114         if let AssociatedItemKind::Method { has_self } = item.kind {
115             has_self &&
116             {
117                 let did = cx.tcx.map.local_def_id(item.id.node_id);
118                 let impl_ty = cx.tcx.item_type(did);
119                 impl_ty.fn_args().skip_binder().len() == 1
120             }
121         } else {
122             false
123         }
124     }
125
126     let is_empty = if let Some(is_empty) = impl_items.iter().find(|i| is_named_self(cx, i, "is_empty")) {
127         if cx.access_levels.is_exported(is_empty.id.node_id) {
128             return;
129         } else {
130             "a private"
131         }
132     } else {
133         "no corresponding"
134     };
135
136     if let Some(i) = impl_items.iter().find(|i| is_named_self(cx, i, "len")) {
137         if cx.access_levels.is_exported(i.id.node_id) {
138             let def_id = cx.tcx.map.local_def_id(item.id);
139             let ty = cx.tcx.item_type(def_id);
140
141             span_lint(cx,
142                       LEN_WITHOUT_IS_EMPTY,
143                       i.span,
144                       &format!("item `{}` has a public `len` method but {} `is_empty` method", ty, is_empty));
145         }
146     }
147 }
148
149 fn check_cmp(cx: &LateContext, span: Span, left: &Expr, right: &Expr, op: &str) {
150     // check if we are in an is_empty() method
151     if let Some(name) = get_item_name(cx, left) {
152         if &*name.as_str() == "is_empty" {
153             return;
154         }
155     }
156     match (&left.node, &right.node) {
157         (&ExprLit(ref lit), &ExprMethodCall(ref method, _, ref args)) |
158         (&ExprMethodCall(ref method, _, ref args), &ExprLit(ref lit)) => {
159             check_len_zero(cx, span, &method.node, args, lit, op)
160         },
161         _ => (),
162     }
163 }
164
165 fn check_len_zero(cx: &LateContext, span: Span, name: &Name, args: &[Expr], lit: &Lit, op: &str) {
166     if let Spanned { node: LitKind::Int(0, _), .. } = *lit {
167         if &*name.as_str() == "len" && args.len() == 1 && has_is_empty(cx, &args[0]) {
168             span_lint_and_then(cx, LEN_ZERO, span, "length comparison to zero", |db| {
169                 db.span_suggestion(span,
170                                    "consider using `is_empty`",
171                                    format!("{}{}.is_empty()", op, snippet(cx, args[0].span, "_")));
172             });
173         }
174     }
175 }
176
177 /// Check if this type has an `is_empty` method.
178 fn has_is_empty(cx: &LateContext, expr: &Expr) -> bool {
179     /// Get an `AssociatedItem` and return true if it matches `is_empty(self)`.
180     fn is_is_empty(cx: &LateContext, item: &ty::AssociatedItem) -> bool {
181         if let ty::AssociatedKind::Method = item.kind {
182             if &*item.name.as_str() == "is_empty" {
183                 let ty = cx.tcx.item_type(item.def_id).fn_sig().skip_binder();
184                 ty.inputs().len() == 1
185             } else {
186                 false
187             }
188         } else {
189             false
190         }
191     }
192
193     /// Check the inherent impl's items for an `is_empty(self)` method.
194     fn has_is_empty_impl(cx: &LateContext, id: DefId) -> bool {
195         cx.tcx.inherent_impls.borrow().get(&id).map_or(false, |impls| {
196             impls.iter().any(|imp| cx.tcx.associated_items(*imp).any(|item| is_is_empty(cx, &item)))
197         })
198     }
199
200     let ty = &walk_ptrs_ty(cx.tcx.tables().expr_ty(expr));
201     match ty.sty {
202         ty::TyDynamic(..) => {
203             cx.tcx
204                 .associated_items(ty.ty_to_def_id().expect("trait impl not found"))
205                 .any(|item| is_is_empty(cx, &item))
206         },
207         ty::TyProjection(_) => ty.ty_to_def_id().map_or(false, |id| has_is_empty_impl(cx, id)),
208         ty::TyAdt(id, _) => has_is_empty_impl(cx, id.did),
209         ty::TyArray(..) | ty::TyStr => true,
210         _ => false,
211     }
212 }