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