]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/len_zero.rs
Merge branch 'macro-use' into HEAD
[rust.git] / clippy_lints / src / len_zero.rs
1 use rustc::hir::def_id::DefId;
2 use rustc::hir::*;
3 use rustc::lint::*;
4 use rustc::{declare_lint, lint_array};
5 use rustc::ty;
6 use std::collections::HashSet;
7 use syntax::ast::{Lit, LitKind, Name};
8 use syntax::codemap::{Span, Spanned};
9 use crate::utils::{get_item_name, in_macro, snippet, span_lint, span_lint_and_sugg, walk_ptrs_ty};
10
11 /// **What it does:** Checks for getting the length of something via `.len()`
12 /// just to compare to zero, and suggests using `.is_empty()` where applicable.
13 ///
14 /// **Why is this bad?** Some structures can answer `.is_empty()` much faster
15 /// than calculating their length. Notably, for slices, getting the length
16 /// requires a subtraction whereas `.is_empty()` is just a comparison. So it is
17 /// good to get into the habit of using `.is_empty()`, and having it is cheap.
18 /// Besides, it makes the intent clearer than a manual comparison.
19 ///
20 /// **Known problems:** None.
21 ///
22 /// **Example:**
23 /// ```rust
24 /// if x.len() == 0 { .. }
25 /// ```
26 declare_clippy_lint! {
27     pub LEN_ZERO,
28     style,
29     "checking `.len() == 0` or `.len() > 0` (or similar) when `.is_empty()` \
30      could be used instead"
31 }
32
33 /// **What it does:** Checks for items that implement `.len()` but not
34 /// `.is_empty()`.
35 ///
36 /// **Why is this bad?** It is good custom to have both methods, because for
37 /// some data structures, asking about the length will be a costly operation,
38 /// whereas `.is_empty()` can usually answer in constant time. Also it used to
39 /// lead to false positives on the [`len_zero`](#len_zero) lint – currently that
40 /// lint will ignore such entities.
41 ///
42 /// **Known problems:** None.
43 ///
44 /// **Example:**
45 /// ```rust
46 /// impl X {
47 ///     pub fn len(&self) -> usize { .. }
48 /// }
49 /// ```
50 declare_clippy_lint! {
51     pub LEN_WITHOUT_IS_EMPTY,
52     style,
53     "traits or impls with a public `len` method but no corresponding `is_empty` method"
54 }
55
56 #[derive(Copy, Clone)]
57 pub struct LenZero;
58
59 impl LintPass for LenZero {
60     fn get_lints(&self) -> LintArray {
61         lint_array!(LEN_ZERO, LEN_WITHOUT_IS_EMPTY)
62     }
63 }
64
65 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for LenZero {
66     fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item) {
67         if in_macro(item.span) {
68             return;
69         }
70
71         match item.node {
72             ItemKind::Trait(_, _, _, _, ref trait_items) => check_trait_items(cx, item, trait_items),
73             ItemKind::Impl(_, _, _, _, None, _, ref impl_items) => check_impl_items(cx, item, impl_items),
74             _ => (),
75         }
76     }
77
78     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
79         if in_macro(expr.span) {
80             return;
81         }
82
83         if let ExprKind::Binary(Spanned { node: cmp, .. }, ref left, ref right) = expr.node {
84             match cmp {
85                 BinOpKind::Eq => {
86                     check_cmp(cx, expr.span, left, right, "", 0); // len == 0
87                     check_cmp(cx, expr.span, right, left, "", 0); // 0 == len
88                 },
89                 BinOpKind::Ne => {
90                     check_cmp(cx, expr.span, left, right, "!", 0); // len != 0
91                     check_cmp(cx, expr.span, right, left, "!", 0); // 0 != len
92                 },
93                 BinOpKind::Gt => {
94                     check_cmp(cx, expr.span, left, right, "!", 0); // len > 0
95                     check_cmp(cx, expr.span, right, left, "", 1); // 1 > len
96                 },
97                 BinOpKind::Lt => {
98                     check_cmp(cx, expr.span, left, right, "", 1); // len < 1
99                     check_cmp(cx, expr.span, right, left, "!", 0); // 0 < len
100                 },
101                 BinOpKind::Ge => check_cmp(cx, expr.span, left, right, "!", 1), // len <= 1
102                 BinOpKind::Le => check_cmp(cx, expr.span, right, left, "!", 1), // 1 >= len
103                 _ => (),
104             }
105         }
106     }
107 }
108
109 fn check_trait_items(cx: &LateContext, visited_trait: &Item, trait_items: &[TraitItemRef]) {
110     fn is_named_self(cx: &LateContext, item: &TraitItemRef, name: &str) -> bool {
111         item.ident.name == name && if let AssociatedItemKind::Method { has_self } = item.kind {
112             has_self && {
113                 let did = cx.tcx.hir.local_def_id(item.id.node_id);
114                 cx.tcx.fn_sig(did).inputs().skip_binder().len() == 1
115             }
116         } else {
117             false
118         }
119     }
120
121     // fill the set with current and super traits
122     fn fill_trait_set(traitt: DefId, set: &mut HashSet<DefId>, cx: &LateContext) {
123         if set.insert(traitt) {
124             for supertrait in ::rustc::traits::supertrait_def_ids(cx.tcx, traitt) {
125                 fill_trait_set(supertrait, set, cx);
126             }
127         }
128     }
129
130     if cx.access_levels.is_exported(visited_trait.id) && trait_items.iter().any(|i| is_named_self(cx, i, "len")) {
131         let mut current_and_super_traits = HashSet::new();
132         let visited_trait_def_id = cx.tcx.hir.local_def_id(visited_trait.id);
133         fill_trait_set(visited_trait_def_id, &mut current_and_super_traits, cx);
134
135         let is_empty_method_found = current_and_super_traits
136             .iter()
137             .flat_map(|&i| cx.tcx.associated_items(i))
138             .any(|i| {
139                 i.kind == ty::AssociatedKind::Method && i.method_has_self_argument && i.ident.name == "is_empty"
140                     && cx.tcx.fn_sig(i.def_id).inputs().skip_binder().len() == 1
141             });
142
143         if !is_empty_method_found {
144             span_lint(
145                 cx,
146                 LEN_WITHOUT_IS_EMPTY,
147                 visited_trait.span,
148                 &format!(
149                     "trait `{}` has a `len` method but no (possibly inherited) `is_empty` method",
150                     visited_trait.name
151                 ),
152             );
153         }
154     }
155 }
156
157 fn check_impl_items(cx: &LateContext, item: &Item, impl_items: &[ImplItemRef]) {
158     fn is_named_self(cx: &LateContext, item: &ImplItemRef, name: &str) -> bool {
159         item.ident.name == name && if let AssociatedItemKind::Method { has_self } = item.kind {
160             has_self && {
161                 let did = cx.tcx.hir.local_def_id(item.id.node_id);
162                 cx.tcx.fn_sig(did).inputs().skip_binder().len() == 1
163             }
164         } else {
165             false
166         }
167     }
168
169     let is_empty = if let Some(is_empty) = impl_items.iter().find(|i| is_named_self(cx, i, "is_empty")) {
170         if cx.access_levels.is_exported(is_empty.id.node_id) {
171             return;
172         } else {
173             "a private"
174         }
175     } else {
176         "no corresponding"
177     };
178
179     if let Some(i) = impl_items.iter().find(|i| is_named_self(cx, i, "len")) {
180         if cx.access_levels.is_exported(i.id.node_id) {
181             let def_id = cx.tcx.hir.local_def_id(item.id);
182             let ty = cx.tcx.type_of(def_id);
183
184             span_lint(
185                 cx,
186                 LEN_WITHOUT_IS_EMPTY,
187                 item.span,
188                 &format!(
189                     "item `{}` has a public `len` method but {} `is_empty` method",
190                     ty, is_empty
191                 ),
192             );
193         }
194     }
195 }
196
197 fn check_cmp(cx: &LateContext, span: Span, method: &Expr, lit: &Expr, op: &str, compare_to: u32) {
198     if let (&ExprKind::MethodCall(ref method_path, _, ref args), &ExprKind::Lit(ref lit)) = (&method.node, &lit.node) {
199         // check if we are in an is_empty() method
200         if let Some(name) = get_item_name(cx, method) {
201             if name == "is_empty" {
202                 return;
203             }
204         }
205
206         check_len(cx, span, method_path.ident.name, args, lit, op, compare_to)
207     }
208 }
209
210 fn check_len(cx: &LateContext, span: Span, method_name: Name, args: &[Expr], lit: &Lit, op: &str, compare_to: u32) {
211     if let Spanned {
212         node: LitKind::Int(lit, _),
213         ..
214     } = *lit
215     {
216         // check if length is compared to the specified number
217         if lit != u128::from(compare_to) {
218             return;
219         }
220
221         if method_name == "len" && args.len() == 1 && has_is_empty(cx, &args[0]) {
222             span_lint_and_sugg(
223                 cx,
224                 LEN_ZERO,
225                 span,
226                 &format!("length comparison to {}", if compare_to == 0 { "zero" } else { "one" }),
227                 "using `is_empty` is more concise",
228                 format!("{}{}.is_empty()", op, snippet(cx, args[0].span, "_")),
229             );
230         }
231     }
232 }
233
234 /// Check if this type has an `is_empty` method.
235 fn has_is_empty(cx: &LateContext, expr: &Expr) -> bool {
236     /// Get an `AssociatedItem` and return true if it matches `is_empty(self)`.
237     fn is_is_empty(cx: &LateContext, item: &ty::AssociatedItem) -> bool {
238         if let ty::AssociatedKind::Method = item.kind {
239             if item.ident.name == "is_empty" {
240                 let sig = cx.tcx.fn_sig(item.def_id);
241                 let ty = sig.skip_binder();
242                 ty.inputs().len() == 1
243             } else {
244                 false
245             }
246         } else {
247             false
248         }
249     }
250
251     /// Check the inherent impl's items for an `is_empty(self)` method.
252     fn has_is_empty_impl(cx: &LateContext, id: DefId) -> bool {
253         cx.tcx.inherent_impls(id).iter().any(|imp| {
254             cx.tcx
255                 .associated_items(*imp)
256                 .any(|item| is_is_empty(cx, &item))
257         })
258     }
259
260     let ty = &walk_ptrs_ty(cx.tables.expr_ty(expr));
261     match ty.sty {
262         ty::TyDynamic(ref tt, ..) => cx.tcx
263             .associated_items(tt.principal().expect("trait impl not found").def_id())
264             .any(|item| is_is_empty(cx, &item)),
265         ty::TyProjection(ref proj) => has_is_empty_impl(cx, proj.item_def_id),
266         ty::TyAdt(id, _) => has_is_empty_impl(cx, id.did),
267         ty::TyArray(..) | ty::TySlice(..) | ty::TyStr => true,
268         _ => false,
269     }
270 }