]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/len_zero.rs
Auto merge of #6924 - mgacek8:issue6727_copy_types, r=llogiq
[rust.git] / clippy_lints / src / len_zero.rs
1 use clippy_utils::diagnostics::{span_lint, span_lint_and_sugg, span_lint_and_then};
2 use clippy_utils::source::snippet_with_applicability;
3 use clippy_utils::{get_item_name, get_parent_as_impl, is_allowed};
4 use if_chain::if_chain;
5 use rustc_ast::ast::LitKind;
6 use rustc_data_structures::fx::FxHashSet;
7 use rustc_errors::Applicability;
8 use rustc_hir::{
9     def_id::DefId, AssocItemKind, BinOpKind, Expr, ExprKind, FnRetTy, ImplItem, ImplItemKind, ImplicitSelfKind, Item,
10     ItemKind, Mutability, Node, TraitItemRef, TyKind,
11 };
12 use rustc_lint::{LateContext, LateLintPass};
13 use rustc_middle::ty::{self, AssocKind, FnSig};
14 use rustc_session::{declare_lint_pass, declare_tool_lint};
15 use rustc_span::source_map::{Span, Spanned, Symbol};
16
17 declare_clippy_lint! {
18     /// **What it does:** Checks for getting the length of something via `.len()`
19     /// just to compare to zero, and suggests using `.is_empty()` where applicable.
20     ///
21     /// **Why is this bad?** Some structures can answer `.is_empty()` much faster
22     /// than calculating their length. So it is good to get into the habit of using
23     /// `.is_empty()`, and having it is cheap.
24     /// Besides, it makes the intent clearer than a manual comparison in some contexts.
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_clippy_lint! {
77     /// **What it does:** Checks for comparing to an empty slice such as `""` or `[]`,
78     /// and suggests using `.is_empty()` where applicable.
79     ///
80     /// **Why is this bad?** Some structures can answer `.is_empty()` much faster
81     /// than checking for equality. So it is good to get into the habit of using
82     /// `.is_empty()`, and having it is cheap.
83     /// Besides, it makes the intent clearer than a manual comparison in some contexts.
84     ///
85     /// **Known problems:** None.
86     ///
87     /// **Example:**
88     ///
89     /// ```ignore
90     /// if s == "" {
91     ///     ..
92     /// }
93     ///
94     /// if arr == [] {
95     ///     ..
96     /// }
97     /// ```
98     /// Use instead:
99     /// ```ignore
100     /// if s.is_empty() {
101     ///     ..
102     /// }
103     ///
104     /// if arr.is_empty() {
105     ///     ..
106     /// }
107     /// ```
108     pub COMPARISON_TO_EMPTY,
109     style,
110     "checking `x == \"\"` or `x == []` (or similar) when `.is_empty()` could be used instead"
111 }
112
113 declare_lint_pass!(LenZero => [LEN_ZERO, LEN_WITHOUT_IS_EMPTY, COMPARISON_TO_EMPTY]);
114
115 impl<'tcx> LateLintPass<'tcx> for LenZero {
116     fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) {
117         if item.span.from_expansion() {
118             return;
119         }
120
121         if let ItemKind::Trait(_, _, _, _, ref trait_items) = item.kind {
122             check_trait_items(cx, item, trait_items);
123         }
124     }
125
126     fn check_impl_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx ImplItem<'_>) {
127         if_chain! {
128             if item.ident.as_str() == "len";
129             if let ImplItemKind::Fn(sig, _) = &item.kind;
130             if sig.decl.implicit_self.has_implicit_self();
131             if cx.access_levels.is_exported(item.hir_id());
132             if matches!(sig.decl.output, FnRetTy::Return(_));
133             if let Some(imp) = get_parent_as_impl(cx.tcx, item.hir_id());
134             if imp.of_trait.is_none();
135             if let TyKind::Path(ty_path) = &imp.self_ty.kind;
136             if let Some(ty_id) = cx.qpath_res(ty_path, imp.self_ty.hir_id).opt_def_id();
137             if let Some(local_id) = ty_id.as_local();
138             let ty_hir_id = cx.tcx.hir().local_def_id_to_hir_id(local_id);
139             if !is_allowed(cx, LEN_WITHOUT_IS_EMPTY, ty_hir_id);
140             then {
141                 let (name, kind) = match cx.tcx.hir().find(ty_hir_id) {
142                     Some(Node::ForeignItem(x)) => (x.ident.name, "extern type"),
143                     Some(Node::Item(x)) => match x.kind {
144                         ItemKind::Struct(..) => (x.ident.name, "struct"),
145                         ItemKind::Enum(..) => (x.ident.name, "enum"),
146                         ItemKind::Union(..) => (x.ident.name, "union"),
147                         _ => (x.ident.name, "type"),
148                     }
149                     _ => return,
150                 };
151                 check_for_is_empty(cx, sig.span, sig.decl.implicit_self, ty_id, name, kind)
152             }
153         }
154     }
155
156     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
157         if expr.span.from_expansion() {
158             return;
159         }
160
161         if let ExprKind::Binary(Spanned { node: cmp, .. }, ref left, ref right) = expr.kind {
162             match cmp {
163                 BinOpKind::Eq => {
164                     check_cmp(cx, expr.span, left, right, "", 0); // len == 0
165                     check_cmp(cx, expr.span, right, left, "", 0); // 0 == len
166                 },
167                 BinOpKind::Ne => {
168                     check_cmp(cx, expr.span, left, right, "!", 0); // len != 0
169                     check_cmp(cx, expr.span, right, left, "!", 0); // 0 != len
170                 },
171                 BinOpKind::Gt => {
172                     check_cmp(cx, expr.span, left, right, "!", 0); // len > 0
173                     check_cmp(cx, expr.span, right, left, "", 1); // 1 > len
174                 },
175                 BinOpKind::Lt => {
176                     check_cmp(cx, expr.span, left, right, "", 1); // len < 1
177                     check_cmp(cx, expr.span, right, left, "!", 0); // 0 < len
178                 },
179                 BinOpKind::Ge => check_cmp(cx, expr.span, left, right, "!", 1), // len >= 1
180                 BinOpKind::Le => check_cmp(cx, expr.span, right, left, "!", 1), // 1 <= len
181                 _ => (),
182             }
183         }
184     }
185 }
186
187 fn check_trait_items(cx: &LateContext<'_>, visited_trait: &Item<'_>, trait_items: &[TraitItemRef]) {
188     fn is_named_self(cx: &LateContext<'_>, item: &TraitItemRef, name: &str) -> bool {
189         item.ident.name.as_str() == name
190             && if let AssocItemKind::Fn { has_self } = item.kind {
191                 has_self && { cx.tcx.fn_sig(item.id.def_id).inputs().skip_binder().len() == 1 }
192             } else {
193                 false
194             }
195     }
196
197     // fill the set with current and super traits
198     fn fill_trait_set(traitt: DefId, set: &mut FxHashSet<DefId>, cx: &LateContext<'_>) {
199         if set.insert(traitt) {
200             for supertrait in rustc_trait_selection::traits::supertrait_def_ids(cx.tcx, traitt) {
201                 fill_trait_set(supertrait, set, cx);
202             }
203         }
204     }
205
206     if cx.access_levels.is_exported(visited_trait.hir_id()) && trait_items.iter().any(|i| is_named_self(cx, i, "len")) {
207         let mut current_and_super_traits = FxHashSet::default();
208         fill_trait_set(visited_trait.def_id.to_def_id(), &mut current_and_super_traits, cx);
209
210         let is_empty_method_found = current_and_super_traits
211             .iter()
212             .flat_map(|&i| cx.tcx.associated_items(i).in_definition_order())
213             .any(|i| {
214                 i.kind == ty::AssocKind::Fn
215                     && i.fn_has_self_parameter
216                     && i.ident.name == sym!(is_empty)
217                     && cx.tcx.fn_sig(i.def_id).inputs().skip_binder().len() == 1
218             });
219
220         if !is_empty_method_found {
221             span_lint(
222                 cx,
223                 LEN_WITHOUT_IS_EMPTY,
224                 visited_trait.span,
225                 &format!(
226                     "trait `{}` has a `len` method but no (possibly inherited) `is_empty` method",
227                     visited_trait.ident.name
228                 ),
229             );
230         }
231     }
232 }
233
234 /// Checks if the given signature matches the expectations for `is_empty`
235 fn check_is_empty_sig(cx: &LateContext<'_>, sig: FnSig<'_>, self_kind: ImplicitSelfKind) -> bool {
236     match &**sig.inputs_and_output {
237         [arg, res] if *res == cx.tcx.types.bool => {
238             matches!(
239                 (arg.kind(), self_kind),
240                 (ty::Ref(_, _, Mutability::Not), ImplicitSelfKind::ImmRef)
241                     | (ty::Ref(_, _, Mutability::Mut), ImplicitSelfKind::MutRef)
242             ) || (!arg.is_ref() && matches!(self_kind, ImplicitSelfKind::Imm | ImplicitSelfKind::Mut))
243         },
244         _ => false,
245     }
246 }
247
248 /// Checks if the given type has an `is_empty` method with the appropriate signature.
249 fn check_for_is_empty(
250     cx: &LateContext<'_>,
251     span: Span,
252     self_kind: ImplicitSelfKind,
253     impl_ty: DefId,
254     item_name: Symbol,
255     item_kind: &str,
256 ) {
257     let is_empty = Symbol::intern("is_empty");
258     let is_empty = cx
259         .tcx
260         .inherent_impls(impl_ty)
261         .iter()
262         .flat_map(|&id| cx.tcx.associated_items(id).filter_by_name_unhygienic(is_empty))
263         .find(|item| item.kind == AssocKind::Fn);
264
265     let (msg, is_empty_span, self_kind) = match is_empty {
266         None => (
267             format!(
268                 "{} `{}` has a public `len` method, but no `is_empty` method",
269                 item_kind,
270                 item_name.as_str(),
271             ),
272             None,
273             None,
274         ),
275         Some(is_empty)
276             if !cx
277                 .access_levels
278                 .is_exported(cx.tcx.hir().local_def_id_to_hir_id(is_empty.def_id.expect_local())) =>
279         {
280             (
281                 format!(
282                     "{} `{}` has a public `len` method, but a private `is_empty` method",
283                     item_kind,
284                     item_name.as_str(),
285                 ),
286                 Some(cx.tcx.def_span(is_empty.def_id)),
287                 None,
288             )
289         },
290         Some(is_empty)
291             if !(is_empty.fn_has_self_parameter
292                 && check_is_empty_sig(cx, cx.tcx.fn_sig(is_empty.def_id).skip_binder(), self_kind)) =>
293         {
294             (
295                 format!(
296                     "{} `{}` has a public `len` method, but the `is_empty` method has an unexpected signature",
297                     item_kind,
298                     item_name.as_str(),
299                 ),
300                 Some(cx.tcx.def_span(is_empty.def_id)),
301                 Some(self_kind),
302             )
303         },
304         Some(_) => return,
305     };
306
307     span_lint_and_then(cx, LEN_WITHOUT_IS_EMPTY, span, &msg, |db| {
308         if let Some(span) = is_empty_span {
309             db.span_note(span, "`is_empty` defined here");
310         }
311         if let Some(self_kind) = self_kind {
312             db.note(&format!(
313                 "expected signature: `({}self) -> bool`",
314                 match self_kind {
315                     ImplicitSelfKind::ImmRef => "&",
316                     ImplicitSelfKind::MutRef => "&mut ",
317                     _ => "",
318                 }
319             ));
320         }
321     });
322 }
323
324 fn check_cmp(cx: &LateContext<'_>, span: Span, method: &Expr<'_>, lit: &Expr<'_>, op: &str, compare_to: u32) {
325     if let (&ExprKind::MethodCall(ref method_path, _, ref args, _), &ExprKind::Lit(ref lit)) = (&method.kind, &lit.kind)
326     {
327         // check if we are in an is_empty() method
328         if let Some(name) = get_item_name(cx, method) {
329             if name.as_str() == "is_empty" {
330                 return;
331             }
332         }
333
334         check_len(cx, span, method_path.ident.name, args, &lit.node, op, compare_to)
335     } else {
336         check_empty_expr(cx, span, method, lit, op)
337     }
338 }
339
340 fn check_len(
341     cx: &LateContext<'_>,
342     span: Span,
343     method_name: Symbol,
344     args: &[Expr<'_>],
345     lit: &LitKind,
346     op: &str,
347     compare_to: u32,
348 ) {
349     if let LitKind::Int(lit, _) = *lit {
350         // check if length is compared to the specified number
351         if lit != u128::from(compare_to) {
352             return;
353         }
354
355         if method_name.as_str() == "len" && args.len() == 1 && has_is_empty(cx, &args[0]) {
356             let mut applicability = Applicability::MachineApplicable;
357             span_lint_and_sugg(
358                 cx,
359                 LEN_ZERO,
360                 span,
361                 &format!("length comparison to {}", if compare_to == 0 { "zero" } else { "one" }),
362                 &format!("using `{}is_empty` is clearer and more explicit", op),
363                 format!(
364                     "{}{}.is_empty()",
365                     op,
366                     snippet_with_applicability(cx, args[0].span, "_", &mut applicability)
367                 ),
368                 applicability,
369             );
370         }
371     }
372 }
373
374 fn check_empty_expr(cx: &LateContext<'_>, span: Span, lit1: &Expr<'_>, lit2: &Expr<'_>, op: &str) {
375     if (is_empty_array(lit2) || is_empty_string(lit2)) && has_is_empty(cx, lit1) {
376         let mut applicability = Applicability::MachineApplicable;
377         span_lint_and_sugg(
378             cx,
379             COMPARISON_TO_EMPTY,
380             span,
381             "comparison to empty slice",
382             &format!("using `{}is_empty` is clearer and more explicit", op),
383             format!(
384                 "{}{}.is_empty()",
385                 op,
386                 snippet_with_applicability(cx, lit1.span, "_", &mut applicability)
387             ),
388             applicability,
389         );
390     }
391 }
392
393 fn is_empty_string(expr: &Expr<'_>) -> bool {
394     if let ExprKind::Lit(ref lit) = expr.kind {
395         if let LitKind::Str(lit, _) = lit.node {
396             let lit = lit.as_str();
397             return lit == "";
398         }
399     }
400     false
401 }
402
403 fn is_empty_array(expr: &Expr<'_>) -> bool {
404     if let ExprKind::Array(ref arr) = expr.kind {
405         return arr.is_empty();
406     }
407     false
408 }
409
410 /// Checks if this type has an `is_empty` method.
411 fn has_is_empty(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
412     /// Gets an `AssocItem` and return true if it matches `is_empty(self)`.
413     fn is_is_empty(cx: &LateContext<'_>, item: &ty::AssocItem) -> bool {
414         if let ty::AssocKind::Fn = item.kind {
415             if item.ident.name.as_str() == "is_empty" {
416                 let sig = cx.tcx.fn_sig(item.def_id);
417                 let ty = sig.skip_binder();
418                 ty.inputs().len() == 1
419             } else {
420                 false
421             }
422         } else {
423             false
424         }
425     }
426
427     /// Checks the inherent impl's items for an `is_empty(self)` method.
428     fn has_is_empty_impl(cx: &LateContext<'_>, id: DefId) -> bool {
429         cx.tcx.inherent_impls(id).iter().any(|imp| {
430             cx.tcx
431                 .associated_items(*imp)
432                 .in_definition_order()
433                 .any(|item| is_is_empty(cx, &item))
434         })
435     }
436
437     let ty = &cx.typeck_results().expr_ty(expr).peel_refs();
438     match ty.kind() {
439         ty::Dynamic(ref tt, ..) => tt.principal().map_or(false, |principal| {
440             cx.tcx
441                 .associated_items(principal.def_id())
442                 .in_definition_order()
443                 .any(|item| is_is_empty(cx, &item))
444         }),
445         ty::Projection(ref proj) => has_is_empty_impl(cx, proj.item_def_id),
446         ty::Adt(id, _) => has_is_empty_impl(cx, id.did),
447         ty::Array(..) | ty::Slice(..) | ty::Str => true,
448         _ => false,
449     }
450 }