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