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