2 get_item_name, get_parent_as_impl, is_allowed, snippet_with_applicability, span_lint, span_lint_and_sugg,
5 use if_chain::if_chain;
6 use rustc_ast::ast::LitKind;
7 use rustc_data_structures::fx::FxHashSet;
8 use rustc_errors::Applicability;
10 def_id::DefId, AssocItemKind, BinOpKind, Expr, ExprKind, FnRetTy, ImplItem, ImplItemKind, ImplicitSelfKind, Item,
11 ItemKind, Mutability, Node, TraitItemRef, TyKind,
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};
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.
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.
27 /// **Known problems:** None.
43 /// if !y.is_empty() {
49 "checking `.len() == 0` or `.len() > 0` (or similar) when `.is_empty()` could be used instead"
52 declare_clippy_lint! {
53 /// **What it does:** Checks for items that implement `.len()` but not
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.
62 /// **Known problems:** None.
67 /// pub fn len(&self) -> usize {
72 pub LEN_WITHOUT_IS_EMPTY,
74 "traits or impls with a public `len` method but no corresponding `is_empty` method"
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.
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.
86 /// **Known problems:** None.
101 /// if s.is_empty() {
105 /// if arr.is_empty() {
109 pub COMPARISON_TO_EMPTY,
111 "checking `x == \"\"` or `x == []` (or similar) when `.is_empty()` could be used instead"
114 declare_lint_pass!(LenZero => [LEN_ZERO, LEN_WITHOUT_IS_EMPTY, COMPARISON_TO_EMPTY]);
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() {
122 if let ItemKind::Trait(_, _, _, _, ref trait_items) = item.kind {
123 check_trait_items(cx, item, trait_items);
127 fn check_impl_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx ImplItem<'_>) {
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);
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"),
152 check_for_is_empty(cx, sig.span, sig.decl.implicit_self, ty_id, name, kind)
157 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
158 if expr.span.from_expansion() {
162 if let ExprKind::Binary(Spanned { node: cmp, .. }, ref left, ref right) = expr.kind {
165 check_cmp(cx, expr.span, left, right, "", 0); // len == 0
166 check_cmp(cx, expr.span, right, left, "", 0); // 0 == len
169 check_cmp(cx, expr.span, left, right, "!", 0); // len != 0
170 check_cmp(cx, expr.span, right, left, "!", 0); // 0 != len
173 check_cmp(cx, expr.span, left, right, "!", 0); // len > 0
174 check_cmp(cx, expr.span, right, left, "", 1); // 1 > len
177 check_cmp(cx, expr.span, left, right, "", 1); // len < 1
178 check_cmp(cx, expr.span, right, left, "!", 0); // 0 < len
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
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 }
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);
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);
211 let is_empty_method_found = current_and_super_traits
213 .flat_map(|&i| cx.tcx.associated_items(i).in_definition_order())
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
221 if !is_empty_method_found {
224 LEN_WITHOUT_IS_EMPTY,
227 "trait `{}` has a `len` method but no (possibly inherited) `is_empty` method",
228 visited_trait.ident.name
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 => {
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))
249 /// Checks if the given type has an `is_empty` method with the appropriate signature.
250 fn check_for_is_empty(
251 cx: &LateContext<'_>,
253 self_kind: ImplicitSelfKind,
258 let is_empty = Symbol::intern("is_empty");
261 .inherent_impls(impl_ty)
263 .flat_map(|&id| cx.tcx.associated_items(id).filter_by_name_unhygienic(is_empty))
264 .find(|item| item.kind == AssocKind::Fn);
266 let (msg, is_empty_span, self_kind) = match is_empty {
269 "{} `{}` has a public `len` method, but no `is_empty` method",
279 .is_exported(cx.tcx.hir().local_def_id_to_hir_id(is_empty.def_id.expect_local())) =>
283 "{} `{}` has a public `len` method, but a private `is_empty` method",
287 Some(cx.tcx.def_span(is_empty.def_id)),
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)) =>
297 "{} `{}` has a public `len` method, but the `is_empty` method has an unexpected signature",
301 Some(cx.tcx.def_span(is_empty.def_id)),
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");
312 if let Some(self_kind) = self_kind {
314 "expected signature: `({}self) -> bool`",
316 ImplicitSelfKind::ImmRef => "&",
317 ImplicitSelfKind::MutRef => "&mut ",
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)
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" {
335 check_len(cx, span, method_path.ident.name, args, &lit.node, op, compare_to)
337 check_empty_expr(cx, span, method, lit, op)
342 cx: &LateContext<'_>,
350 if let LitKind::Int(lit, _) = *lit {
351 // check if length is compared to the specified number
352 if lit != u128::from(compare_to) {
356 if method_name.as_str() == "len" && args.len() == 1 && has_is_empty(cx, &args[0]) {
357 let mut applicability = Applicability::MachineApplicable;
362 &format!("length comparison to {}", if compare_to == 0 { "zero" } else { "one" }),
363 &format!("using `{}is_empty` is clearer and more explicit", op),
367 snippet_with_applicability(cx, args[0].span, "_", &mut applicability)
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;
382 "comparison to empty slice",
383 &format!("using `{}is_empty` is clearer and more explicit", op),
387 snippet_with_applicability(cx, lit1.span, "_", &mut applicability)
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();
404 fn is_empty_array(expr: &Expr<'_>) -> bool {
405 if let ExprKind::Array(ref arr) = expr.kind {
406 return arr.is_empty();
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
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| {
432 .associated_items(*imp)
433 .in_definition_order()
434 .any(|item| is_is_empty(cx, &item))
438 let ty = &cx.typeck_results().expr_ty(expr).peel_refs();
440 ty::Dynamic(ref tt, ..) => tt.principal().map_or(false, |principal| {
442 .associated_items(principal.def_id())
443 .in_definition_order()
444 .any(|item| is_is_empty(cx, &item))
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,