]> git.proxmox.com Git - rustc.git/blob - src/tools/clippy/clippy_lints/src/len_zero.rs
New upstream version 1.71.1+dfsg1
[rustc.git] / src / tools / clippy / 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_context;
3 use clippy_utils::{get_item_name, get_parent_as_impl, is_lint_allowed, peel_ref_operators, sugg::Sugg};
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::Res, def_id::DefId, lang_items::LangItem, AssocItemKind, BinOpKind, Expr, ExprKind, FnRetTy, GenericArg,
10 GenericBound, ImplItem, ImplItemKind, ImplicitSelfKind, Item, ItemKind, Mutability, Node, PathSegment, PrimTy,
11 QPath, TraitItemRef, TyKind, TypeBindingKind,
12 };
13 use rustc_lint::{LateContext, LateLintPass};
14 use rustc_middle::ty::{self, AssocKind, FnSig, Ty};
15 use rustc_session::{declare_lint_pass, declare_tool_lint};
16 use rustc_span::{
17 source_map::{Span, Spanned, Symbol},
18 symbol::sym,
19 };
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 sig.decl.inputs.len() == 1;
139 if cx.effective_visibilities.is_exported(item.owner_id.def_id);
140 if matches!(sig.decl.output, FnRetTy::Return(_));
141 if let Some(imp) = get_parent_as_impl(cx.tcx, item.hir_id());
142 if imp.of_trait.is_none();
143 if let TyKind::Path(ty_path) = &imp.self_ty.kind;
144 if let Some(ty_id) = cx.qpath_res(ty_path, imp.self_ty.hir_id).opt_def_id();
145 if let Some(local_id) = ty_id.as_local();
146 let ty_hir_id = cx.tcx.hir().local_def_id_to_hir_id(local_id);
147 if !is_lint_allowed(cx, LEN_WITHOUT_IS_EMPTY, ty_hir_id);
148 if let Some(output) = parse_len_output(cx, cx.tcx.fn_sig(item.owner_id).subst_identity().skip_binder());
149 then {
150 let (name, kind) = match cx.tcx.hir().find(ty_hir_id) {
151 Some(Node::ForeignItem(x)) => (x.ident.name, "extern type"),
152 Some(Node::Item(x)) => match x.kind {
153 ItemKind::Struct(..) => (x.ident.name, "struct"),
154 ItemKind::Enum(..) => (x.ident.name, "enum"),
155 ItemKind::Union(..) => (x.ident.name, "union"),
156 _ => (x.ident.name, "type"),
157 }
158 _ => return,
159 };
160 check_for_is_empty(cx, sig.span, sig.decl.implicit_self, output, ty_id, name, kind)
161 }
162 }
163 }
164
165 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
166 if expr.span.from_expansion() {
167 return;
168 }
169
170 if let ExprKind::Binary(Spanned { node: cmp, .. }, left, right) = expr.kind {
171 // expr.span might contains parenthesis, see issue #10529
172 let actual_span = left.span.with_hi(right.span.hi());
173 match cmp {
174 BinOpKind::Eq => {
175 check_cmp(cx, actual_span, left, right, "", 0); // len == 0
176 check_cmp(cx, actual_span, right, left, "", 0); // 0 == len
177 },
178 BinOpKind::Ne => {
179 check_cmp(cx, actual_span, left, right, "!", 0); // len != 0
180 check_cmp(cx, actual_span, right, left, "!", 0); // 0 != len
181 },
182 BinOpKind::Gt => {
183 check_cmp(cx, actual_span, left, right, "!", 0); // len > 0
184 check_cmp(cx, actual_span, right, left, "", 1); // 1 > len
185 },
186 BinOpKind::Lt => {
187 check_cmp(cx, actual_span, left, right, "", 1); // len < 1
188 check_cmp(cx, actual_span, right, left, "!", 0); // 0 < len
189 },
190 BinOpKind::Ge => check_cmp(cx, actual_span, left, right, "!", 1), // len >= 1
191 BinOpKind::Le => check_cmp(cx, actual_span, right, left, "!", 1), // 1 <= len
192 _ => (),
193 }
194 }
195 }
196 }
197
198 fn check_trait_items(cx: &LateContext<'_>, visited_trait: &Item<'_>, trait_items: &[TraitItemRef]) {
199 fn is_named_self(cx: &LateContext<'_>, item: &TraitItemRef, name: Symbol) -> bool {
200 item.ident.name == name
201 && if let AssocItemKind::Fn { has_self } = item.kind {
202 has_self && {
203 cx.tcx
204 .fn_sig(item.id.owner_id)
205 .skip_binder()
206 .inputs()
207 .skip_binder()
208 .len()
209 == 1
210 }
211 } else {
212 false
213 }
214 }
215
216 // fill the set with current and super traits
217 fn fill_trait_set(traitt: DefId, set: &mut DefIdSet, cx: &LateContext<'_>) {
218 if set.insert(traitt) {
219 for supertrait in rustc_trait_selection::traits::supertrait_def_ids(cx.tcx, traitt) {
220 fill_trait_set(supertrait, set, cx);
221 }
222 }
223 }
224
225 if cx.effective_visibilities.is_exported(visited_trait.owner_id.def_id)
226 && trait_items.iter().any(|i| is_named_self(cx, i, sym::len))
227 {
228 let mut current_and_super_traits = DefIdSet::default();
229 fill_trait_set(visited_trait.owner_id.to_def_id(), &mut current_and_super_traits, cx);
230 let is_empty = sym!(is_empty);
231
232 let is_empty_method_found = current_and_super_traits
233 .items()
234 .flat_map(|&i| cx.tcx.associated_items(i).filter_by_name_unhygienic(is_empty))
235 .any(|i| {
236 i.kind == ty::AssocKind::Fn
237 && i.fn_has_self_parameter
238 && cx.tcx.fn_sig(i.def_id).skip_binder().inputs().skip_binder().len() == 1
239 });
240
241 if !is_empty_method_found {
242 span_lint(
243 cx,
244 LEN_WITHOUT_IS_EMPTY,
245 visited_trait.span,
246 &format!(
247 "trait `{}` has a `len` method but no (possibly inherited) `is_empty` method",
248 visited_trait.ident.name
249 ),
250 );
251 }
252 }
253 }
254
255 #[derive(Debug, Clone, Copy)]
256 enum LenOutput {
257 Integral,
258 Option(DefId),
259 Result(DefId),
260 }
261
262 fn extract_future_output<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> Option<&'tcx PathSegment<'tcx>> {
263 if let ty::Alias(_, alias_ty) = ty.kind() &&
264 let Some(Node::Item(item)) = cx.tcx.hir().get_if_local(alias_ty.def_id) &&
265 let Item { kind: ItemKind::OpaqueTy(opaque), .. } = item &&
266 opaque.bounds.len() == 1 &&
267 let GenericBound::LangItemTrait(LangItem::Future, _, _, generic_args) = &opaque.bounds[0] &&
268 generic_args.bindings.len() == 1 &&
269 let TypeBindingKind::Equality {
270 term: rustc_hir::Term::Ty(rustc_hir::Ty {kind: TyKind::Path(QPath::Resolved(_, path)), .. }),
271 } = &generic_args.bindings[0].kind &&
272 path.segments.len() == 1 {
273 return Some(&path.segments[0]);
274 }
275
276 None
277 }
278
279 fn is_first_generic_integral<'tcx>(segment: &'tcx PathSegment<'tcx>) -> bool {
280 if let Some(generic_args) = segment.args {
281 if generic_args.args.is_empty() {
282 return false;
283 }
284 let arg = &generic_args.args[0];
285 if let GenericArg::Type(rustc_hir::Ty {
286 kind: TyKind::Path(QPath::Resolved(_, path)),
287 ..
288 }) = arg
289 {
290 let segments = &path.segments;
291 let segment = &segments[0];
292 let res = &segment.res;
293 if matches!(res, Res::PrimTy(PrimTy::Uint(_))) || matches!(res, Res::PrimTy(PrimTy::Int(_))) {
294 return true;
295 }
296 }
297 }
298
299 false
300 }
301
302 fn parse_len_output<'tcx>(cx: &LateContext<'tcx>, sig: FnSig<'tcx>) -> Option<LenOutput> {
303 if let Some(segment) = extract_future_output(cx, sig.output()) {
304 let res = segment.res;
305
306 if matches!(res, Res::PrimTy(PrimTy::Uint(_))) || matches!(res, Res::PrimTy(PrimTy::Int(_))) {
307 return Some(LenOutput::Integral);
308 }
309
310 if let Res::Def(_, def_id) = res {
311 if cx.tcx.is_diagnostic_item(sym::Option, def_id) && is_first_generic_integral(segment) {
312 return Some(LenOutput::Option(def_id));
313 } else if cx.tcx.is_diagnostic_item(sym::Result, def_id) && is_first_generic_integral(segment) {
314 return Some(LenOutput::Result(def_id));
315 }
316 }
317
318 return None;
319 }
320
321 match *sig.output().kind() {
322 ty::Int(_) | ty::Uint(_) => Some(LenOutput::Integral),
323 ty::Adt(adt, subs) if cx.tcx.is_diagnostic_item(sym::Option, adt.did()) => {
324 subs.type_at(0).is_integral().then(|| LenOutput::Option(adt.did()))
325 },
326 ty::Adt(adt, subs) if cx.tcx.is_diagnostic_item(sym::Result, adt.did()) => {
327 subs.type_at(0).is_integral().then(|| LenOutput::Result(adt.did()))
328 },
329 _ => None,
330 }
331 }
332
333 impl LenOutput {
334 fn matches_is_empty_output<'tcx>(self, cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool {
335 if let Some(segment) = extract_future_output(cx, ty) {
336 return match (self, segment.res) {
337 (_, Res::PrimTy(PrimTy::Bool)) => true,
338 (Self::Option(_), Res::Def(_, def_id)) if cx.tcx.is_diagnostic_item(sym::Option, def_id) => true,
339 (Self::Result(_), Res::Def(_, def_id)) if cx.tcx.is_diagnostic_item(sym::Result, def_id) => true,
340 _ => false,
341 };
342 }
343
344 match (self, ty.kind()) {
345 (_, &ty::Bool) => true,
346 (Self::Option(id), &ty::Adt(adt, subs)) if id == adt.did() => subs.type_at(0).is_bool(),
347 (Self::Result(id), &ty::Adt(adt, subs)) if id == adt.did() => subs.type_at(0).is_bool(),
348 _ => false,
349 }
350 }
351
352 fn expected_sig(self, self_kind: ImplicitSelfKind) -> String {
353 let self_ref = match self_kind {
354 ImplicitSelfKind::ImmRef => "&",
355 ImplicitSelfKind::MutRef => "&mut ",
356 _ => "",
357 };
358 match self {
359 Self::Integral => format!("expected signature: `({self_ref}self) -> bool`"),
360 Self::Option(_) => {
361 format!("expected signature: `({self_ref}self) -> bool` or `({self_ref}self) -> Option<bool>")
362 },
363 Self::Result(..) => {
364 format!("expected signature: `({self_ref}self) -> bool` or `({self_ref}self) -> Result<bool>")
365 },
366 }
367 }
368 }
369
370 /// Checks if the given signature matches the expectations for `is_empty`
371 fn check_is_empty_sig<'tcx>(
372 cx: &LateContext<'tcx>,
373 sig: FnSig<'tcx>,
374 self_kind: ImplicitSelfKind,
375 len_output: LenOutput,
376 ) -> bool {
377 match &**sig.inputs_and_output {
378 [arg, res] if len_output.matches_is_empty_output(cx, *res) => {
379 matches!(
380 (arg.kind(), self_kind),
381 (ty::Ref(_, _, Mutability::Not), ImplicitSelfKind::ImmRef)
382 | (ty::Ref(_, _, Mutability::Mut), ImplicitSelfKind::MutRef)
383 ) || (!arg.is_ref() && matches!(self_kind, ImplicitSelfKind::Imm | ImplicitSelfKind::Mut))
384 },
385 _ => false,
386 }
387 }
388
389 /// Checks if the given type has an `is_empty` method with the appropriate signature.
390 fn check_for_is_empty(
391 cx: &LateContext<'_>,
392 span: Span,
393 self_kind: ImplicitSelfKind,
394 output: LenOutput,
395 impl_ty: DefId,
396 item_name: Symbol,
397 item_kind: &str,
398 ) {
399 let is_empty = Symbol::intern("is_empty");
400 let is_empty = cx
401 .tcx
402 .inherent_impls(impl_ty)
403 .iter()
404 .flat_map(|&id| cx.tcx.associated_items(id).filter_by_name_unhygienic(is_empty))
405 .find(|item| item.kind == AssocKind::Fn);
406
407 let (msg, is_empty_span, self_kind) = match is_empty {
408 None => (
409 format!(
410 "{item_kind} `{}` has a public `len` method, but no `is_empty` method",
411 item_name.as_str(),
412 ),
413 None,
414 None,
415 ),
416 Some(is_empty) if !cx.effective_visibilities.is_exported(is_empty.def_id.expect_local()) => (
417 format!(
418 "{item_kind} `{}` has a public `len` method, but a private `is_empty` method",
419 item_name.as_str(),
420 ),
421 Some(cx.tcx.def_span(is_empty.def_id)),
422 None,
423 ),
424 Some(is_empty)
425 if !(is_empty.fn_has_self_parameter
426 && check_is_empty_sig(
427 cx,
428 cx.tcx.fn_sig(is_empty.def_id).subst_identity().skip_binder(),
429 self_kind,
430 output,
431 )) =>
432 {
433 (
434 format!(
435 "{item_kind} `{}` has a public `len` method, but the `is_empty` method has an unexpected signature",
436 item_name.as_str(),
437 ),
438 Some(cx.tcx.def_span(is_empty.def_id)),
439 Some(self_kind),
440 )
441 },
442 Some(_) => return,
443 };
444
445 span_lint_and_then(cx, LEN_WITHOUT_IS_EMPTY, span, &msg, |db| {
446 if let Some(span) = is_empty_span {
447 db.span_note(span, "`is_empty` defined here");
448 }
449 if let Some(self_kind) = self_kind {
450 db.note(output.expected_sig(self_kind));
451 }
452 });
453 }
454
455 fn check_cmp(cx: &LateContext<'_>, span: Span, method: &Expr<'_>, lit: &Expr<'_>, op: &str, compare_to: u32) {
456 if let (&ExprKind::MethodCall(method_path, receiver, args, _), ExprKind::Lit(lit)) = (&method.kind, &lit.kind) {
457 // check if we are in an is_empty() method
458 if let Some(name) = get_item_name(cx, method) {
459 if name.as_str() == "is_empty" {
460 return;
461 }
462 }
463
464 check_len(
465 cx,
466 span,
467 method_path.ident.name,
468 receiver,
469 args,
470 &lit.node,
471 op,
472 compare_to,
473 );
474 } else {
475 check_empty_expr(cx, span, method, lit, op);
476 }
477 }
478
479 // FIXME(flip1995): Figure out how to reduce the number of arguments
480 #[allow(clippy::too_many_arguments)]
481 fn check_len(
482 cx: &LateContext<'_>,
483 span: Span,
484 method_name: Symbol,
485 receiver: &Expr<'_>,
486 args: &[Expr<'_>],
487 lit: &LitKind,
488 op: &str,
489 compare_to: u32,
490 ) {
491 if let LitKind::Int(lit, _) = *lit {
492 // check if length is compared to the specified number
493 if lit != u128::from(compare_to) {
494 return;
495 }
496
497 if method_name == sym::len && args.is_empty() && has_is_empty(cx, receiver) {
498 let mut applicability = Applicability::MachineApplicable;
499 span_lint_and_sugg(
500 cx,
501 LEN_ZERO,
502 span,
503 &format!("length comparison to {}", if compare_to == 0 { "zero" } else { "one" }),
504 &format!("using `{op}is_empty` is clearer and more explicit"),
505 format!(
506 "{op}{}.is_empty()",
507 snippet_with_context(cx, receiver.span, span.ctxt(), "_", &mut applicability).0,
508 ),
509 applicability,
510 );
511 }
512 }
513 }
514
515 fn check_empty_expr(cx: &LateContext<'_>, span: Span, lit1: &Expr<'_>, lit2: &Expr<'_>, op: &str) {
516 if (is_empty_array(lit2) || is_empty_string(lit2)) && has_is_empty(cx, lit1) {
517 let mut applicability = Applicability::MachineApplicable;
518
519 let lit1 = peel_ref_operators(cx, lit1);
520 let lit_str = Sugg::hir_with_context(cx, lit1, span.ctxt(), "_", &mut applicability).maybe_par();
521
522 span_lint_and_sugg(
523 cx,
524 COMPARISON_TO_EMPTY,
525 span,
526 "comparison to empty slice",
527 &format!("using `{op}is_empty` is clearer and more explicit"),
528 format!("{op}{lit_str}.is_empty()"),
529 applicability,
530 );
531 }
532 }
533
534 fn is_empty_string(expr: &Expr<'_>) -> bool {
535 if let ExprKind::Lit(lit) = expr.kind {
536 if let LitKind::Str(lit, _) = lit.node {
537 let lit = lit.as_str();
538 return lit.is_empty();
539 }
540 }
541 false
542 }
543
544 fn is_empty_array(expr: &Expr<'_>) -> bool {
545 if let ExprKind::Array(arr) = expr.kind {
546 return arr.is_empty();
547 }
548 false
549 }
550
551 /// Checks if this type has an `is_empty` method.
552 fn has_is_empty(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
553 /// Gets an `AssocItem` and return true if it matches `is_empty(self)`.
554 fn is_is_empty(cx: &LateContext<'_>, item: &ty::AssocItem) -> bool {
555 if item.kind == ty::AssocKind::Fn {
556 let sig = cx.tcx.fn_sig(item.def_id).skip_binder();
557 let ty = sig.skip_binder();
558 ty.inputs().len() == 1
559 } else {
560 false
561 }
562 }
563
564 /// Checks the inherent impl's items for an `is_empty(self)` method.
565 fn has_is_empty_impl(cx: &LateContext<'_>, id: DefId) -> bool {
566 let is_empty = sym!(is_empty);
567 cx.tcx.inherent_impls(id).iter().any(|imp| {
568 cx.tcx
569 .associated_items(*imp)
570 .filter_by_name_unhygienic(is_empty)
571 .any(|item| is_is_empty(cx, item))
572 })
573 }
574
575 let ty = &cx.typeck_results().expr_ty(expr).peel_refs();
576 match ty.kind() {
577 ty::Dynamic(tt, ..) => tt.principal().map_or(false, |principal| {
578 let is_empty = sym!(is_empty);
579 cx.tcx
580 .associated_items(principal.def_id())
581 .filter_by_name_unhygienic(is_empty)
582 .any(|item| is_is_empty(cx, item))
583 }),
584 ty::Alias(ty::Projection, ref proj) => has_is_empty_impl(cx, proj.def_id),
585 ty::Adt(id, _) => has_is_empty_impl(cx, id.did()),
586 ty::Array(..) | ty::Slice(..) | ty::Str => true,
587 _ => false,
588 }
589 }