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