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;
9 def_id::DefId, AssocItemKind, BinOpKind, Expr, ExprKind, FnRetTy, ImplItem, ImplItemKind, ImplicitSelfKind, Item,
10 ItemKind, Mutability, Node, TraitItemRef, TyKind,
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};
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.
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.
26 /// **Known problems:** None.
42 /// if !y.is_empty() {
48 "checking `.len() == 0` or `.len() > 0` (or similar) when `.is_empty()` could be used instead"
51 declare_clippy_lint! {
52 /// **What it does:** Checks for items that implement `.len()` but not
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.
61 /// **Known problems:** None.
66 /// pub fn len(&self) -> usize {
71 pub LEN_WITHOUT_IS_EMPTY,
73 "traits or impls with a public `len` method but no corresponding `is_empty` method"
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.
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.
85 /// **Known problems:** None.
100 /// if s.is_empty() {
104 /// if arr.is_empty() {
108 pub COMPARISON_TO_EMPTY,
110 "checking `x == \"\"` or `x == []` (or similar) when `.is_empty()` could be used instead"
113 declare_lint_pass!(LenZero => [LEN_ZERO, LEN_WITHOUT_IS_EMPTY, COMPARISON_TO_EMPTY]);
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() {
121 if let ItemKind::Trait(_, _, _, _, ref trait_items) = item.kind {
122 check_trait_items(cx, item, trait_items);
126 fn check_impl_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx ImplItem<'_>) {
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);
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"),
151 check_for_is_empty(cx, sig.span, sig.decl.implicit_self, ty_id, name, kind)
156 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
157 if expr.span.from_expansion() {
161 if let ExprKind::Binary(Spanned { node: cmp, .. }, ref left, ref right) = expr.kind {
164 check_cmp(cx, expr.span, left, right, "", 0); // len == 0
165 check_cmp(cx, expr.span, right, left, "", 0); // 0 == len
168 check_cmp(cx, expr.span, left, right, "!", 0); // len != 0
169 check_cmp(cx, expr.span, right, left, "!", 0); // 0 != len
172 check_cmp(cx, expr.span, left, right, "!", 0); // len > 0
173 check_cmp(cx, expr.span, right, left, "", 1); // 1 > len
176 check_cmp(cx, expr.span, left, right, "", 1); // len < 1
177 check_cmp(cx, expr.span, right, left, "!", 0); // 0 < len
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
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 }
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);
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);
210 let is_empty_method_found = current_and_super_traits
212 .flat_map(|&i| cx.tcx.associated_items(i).in_definition_order())
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
220 if !is_empty_method_found {
223 LEN_WITHOUT_IS_EMPTY,
226 "trait `{}` has a `len` method but no (possibly inherited) `is_empty` method",
227 visited_trait.ident.name
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 => {
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))
248 /// Checks if the given type has an `is_empty` method with the appropriate signature.
249 fn check_for_is_empty(
250 cx: &LateContext<'_>,
252 self_kind: ImplicitSelfKind,
257 let is_empty = Symbol::intern("is_empty");
260 .inherent_impls(impl_ty)
262 .flat_map(|&id| cx.tcx.associated_items(id).filter_by_name_unhygienic(is_empty))
263 .find(|item| item.kind == AssocKind::Fn);
265 let (msg, is_empty_span, self_kind) = match is_empty {
268 "{} `{}` has a public `len` method, but no `is_empty` method",
278 .is_exported(cx.tcx.hir().local_def_id_to_hir_id(is_empty.def_id.expect_local())) =>
282 "{} `{}` has a public `len` method, but a private `is_empty` method",
286 Some(cx.tcx.def_span(is_empty.def_id)),
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)) =>
296 "{} `{}` has a public `len` method, but the `is_empty` method has an unexpected signature",
300 Some(cx.tcx.def_span(is_empty.def_id)),
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");
311 if let Some(self_kind) = self_kind {
313 "expected signature: `({}self) -> bool`",
315 ImplicitSelfKind::ImmRef => "&",
316 ImplicitSelfKind::MutRef => "&mut ",
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)
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" {
334 check_len(cx, span, method_path.ident.name, args, &lit.node, op, compare_to)
336 check_empty_expr(cx, span, method, lit, op)
341 cx: &LateContext<'_>,
349 if let LitKind::Int(lit, _) = *lit {
350 // check if length is compared to the specified number
351 if lit != u128::from(compare_to) {
355 if method_name.as_str() == "len" && args.len() == 1 && has_is_empty(cx, &args[0]) {
356 let mut applicability = Applicability::MachineApplicable;
361 &format!("length comparison to {}", if compare_to == 0 { "zero" } else { "one" }),
362 &format!("using `{}is_empty` is clearer and more explicit", op),
366 snippet_with_applicability(cx, args[0].span, "_", &mut applicability)
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;
381 "comparison to empty slice",
382 &format!("using `{}is_empty` is clearer and more explicit", op),
386 snippet_with_applicability(cx, lit1.span, "_", &mut applicability)
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();
403 fn is_empty_array(expr: &Expr<'_>) -> bool {
404 if let ExprKind::Array(ref arr) = expr.kind {
405 return arr.is_empty();
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
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| {
431 .associated_items(*imp)
432 .in_definition_order()
433 .any(|item| is_is_empty(cx, &item))
437 let ty = &cx.typeck_results().expr_ty(expr).peel_refs();
439 ty::Dynamic(ref tt, ..) => tt.principal().map_or(false, |principal| {
441 .associated_items(principal.def_id())
442 .in_definition_order()
443 .any(|item| is_is_empty(cx, &item))
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,