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