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