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