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};
4 use if_chain::if_chain;
5 use rustc_ast::ast::LitKind;
6 use rustc_errors::Applicability;
7 use rustc_hir::def_id::DefIdSet;
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, Ty, TyS};
14 use rustc_session::{declare_lint_pass, declare_tool_lint};
16 source_map::{Span, Spanned, Symbol},
20 declare_clippy_lint! {
22 /// Checks for getting the length of something via `.len()`
23 /// just to compare to zero, and suggests using `.is_empty()` where applicable.
25 /// ### Why is this bad?
26 /// Some structures can answer `.is_empty()` much faster
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.
45 /// if !y.is_empty() {
51 "checking `.len() == 0` or `.len() > 0` (or similar) when `.is_empty()` could be used instead"
54 declare_clippy_lint! {
56 /// Checks for items that implement `.len()` but not
59 /// ### Why is this bad?
60 /// It is good custom to have both methods, because for
61 /// some data structures, asking about the length will be a costly operation,
62 /// whereas `.is_empty()` can usually answer in constant time. Also it used to
63 /// lead to false positives on the [`len_zero`](#len_zero) lint – currently that
64 /// lint will ignore such entities.
69 /// pub fn len(&self) -> usize {
74 pub LEN_WITHOUT_IS_EMPTY,
76 "traits or impls with a public `len` method but no corresponding `is_empty` method"
79 declare_clippy_lint! {
81 /// Checks for comparing to an empty slice such as `""` or `[]`,
82 /// and suggests using `.is_empty()` where applicable.
84 /// ### Why is this bad?
85 /// Some structures can answer `.is_empty()` much faster
86 /// than checking for equality. So it is good to get into the habit of using
87 /// `.is_empty()`, and having it is cheap.
88 /// Besides, it makes the intent clearer than a manual comparison in some contexts.
103 /// if s.is_empty() {
107 /// if arr.is_empty() {
111 pub COMPARISON_TO_EMPTY,
113 "checking `x == \"\"` or `x == []` (or similar) when `.is_empty()` could be used instead"
116 declare_lint_pass!(LenZero => [LEN_ZERO, LEN_WITHOUT_IS_EMPTY, COMPARISON_TO_EMPTY]);
118 impl<'tcx> LateLintPass<'tcx> for LenZero {
119 fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) {
120 if item.span.from_expansion() {
124 if let ItemKind::Trait(_, _, _, _, trait_items) = item.kind {
125 check_trait_items(cx, item, trait_items);
129 fn check_impl_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx ImplItem<'_>) {
131 if item.ident.name == sym::len;
132 if let ImplItemKind::Fn(sig, _) = &item.kind;
133 if sig.decl.implicit_self.has_implicit_self();
134 if cx.access_levels.is_exported(item.def_id);
135 if matches!(sig.decl.output, FnRetTy::Return(_));
136 if let Some(imp) = get_parent_as_impl(cx.tcx, item.hir_id());
137 if imp.of_trait.is_none();
138 if let TyKind::Path(ty_path) = &imp.self_ty.kind;
139 if let Some(ty_id) = cx.qpath_res(ty_path, imp.self_ty.hir_id).opt_def_id();
140 if let Some(local_id) = ty_id.as_local();
141 let ty_hir_id = cx.tcx.hir().local_def_id_to_hir_id(local_id);
142 if !is_lint_allowed(cx, LEN_WITHOUT_IS_EMPTY, ty_hir_id);
143 if let Some(output) = parse_len_output(cx, cx.tcx.fn_sig(item.def_id).skip_binder());
145 let (name, kind) = match cx.tcx.hir().find(ty_hir_id) {
146 Some(Node::ForeignItem(x)) => (x.ident.name, "extern type"),
147 Some(Node::Item(x)) => match x.kind {
148 ItemKind::Struct(..) => (x.ident.name, "struct"),
149 ItemKind::Enum(..) => (x.ident.name, "enum"),
150 ItemKind::Union(..) => (x.ident.name, "union"),
151 _ => (x.ident.name, "type"),
155 check_for_is_empty(cx, sig.span, sig.decl.implicit_self, output, ty_id, name, kind)
160 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
161 if expr.span.from_expansion() {
165 if let ExprKind::Binary(Spanned { node: cmp, .. }, left, right) = expr.kind {
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, "!", 0); // 0 != len
176 check_cmp(cx, expr.span, left, right, "!", 0); // len > 0
177 check_cmp(cx, expr.span, right, left, "", 1); // 1 > len
180 check_cmp(cx, expr.span, left, right, "", 1); // len < 1
181 check_cmp(cx, expr.span, right, left, "!", 0); // 0 < len
183 BinOpKind::Ge => check_cmp(cx, expr.span, left, right, "!", 1), // len >= 1
184 BinOpKind::Le => check_cmp(cx, expr.span, right, left, "!", 1), // 1 <= len
191 fn check_trait_items(cx: &LateContext<'_>, visited_trait: &Item<'_>, trait_items: &[TraitItemRef]) {
192 fn is_named_self(cx: &LateContext<'_>, item: &TraitItemRef, name: Symbol) -> bool {
193 item.ident.name == name
194 && if let AssocItemKind::Fn { has_self } = item.kind {
195 has_self && { cx.tcx.fn_sig(item.id.def_id).inputs().skip_binder().len() == 1 }
201 // fill the set with current and super traits
202 fn fill_trait_set(traitt: DefId, set: &mut DefIdSet, cx: &LateContext<'_>) {
203 if set.insert(traitt) {
204 for supertrait in rustc_trait_selection::traits::supertrait_def_ids(cx.tcx, traitt) {
205 fill_trait_set(supertrait, set, cx);
210 if cx.access_levels.is_exported(visited_trait.def_id) && trait_items.iter().any(|i| is_named_self(cx, i, sym::len))
212 let mut current_and_super_traits = DefIdSet::default();
213 fill_trait_set(visited_trait.def_id.to_def_id(), &mut current_and_super_traits, cx);
215 let is_empty_method_found = current_and_super_traits
217 .flat_map(|&i| cx.tcx.associated_items(i).in_definition_order())
219 i.kind == ty::AssocKind::Fn
220 && i.fn_has_self_parameter
221 && i.ident.name == sym!(is_empty)
222 && cx.tcx.fn_sig(i.def_id).inputs().skip_binder().len() == 1
225 if !is_empty_method_found {
228 LEN_WITHOUT_IS_EMPTY,
231 "trait `{}` has a `len` method but no (possibly inherited) `is_empty` method",
232 visited_trait.ident.name
239 #[derive(Debug, Clone, Copy)]
240 enum LenOutput<'tcx> {
243 Result(DefId, Ty<'tcx>),
245 fn parse_len_output(cx: &LateContext<'_>, sig: FnSig<'tcx>) -> Option<LenOutput<'tcx>> {
246 match *sig.output().kind() {
247 ty::Int(_) | ty::Uint(_) => Some(LenOutput::Integral),
248 ty::Adt(adt, subs) if cx.tcx.is_diagnostic_item(sym::Option, adt.did) => {
249 subs.type_at(0).is_integral().then(|| LenOutput::Option(adt.did))
251 ty::Adt(adt, subs) if cx.tcx.is_diagnostic_item(sym::Result, adt.did) => subs
254 .then(|| LenOutput::Result(adt.did, subs.type_at(1))),
260 fn matches_is_empty_output(self, ty: Ty<'_>) -> bool {
261 match (self, ty.kind()) {
262 (_, &ty::Bool) => true,
263 (Self::Option(id), &ty::Adt(adt, subs)) if id == adt.did => subs.type_at(0).is_bool(),
264 (Self::Result(id, err_ty), &ty::Adt(adt, subs)) if id == adt.did => {
265 subs.type_at(0).is_bool() && TyS::same_type(subs.type_at(1), err_ty)
271 fn expected_sig(self, self_kind: ImplicitSelfKind) -> String {
272 let self_ref = match self_kind {
273 ImplicitSelfKind::ImmRef => "&",
274 ImplicitSelfKind::MutRef => "&mut ",
278 Self::Integral => format!("expected signature: `({}self) -> bool`", self_ref),
279 Self::Option(_) => format!(
280 "expected signature: `({}self) -> bool` or `({}self) -> Option<bool>",
283 Self::Result(..) => format!(
284 "expected signature: `({}self) -> bool` or `({}self) -> Result<bool>",
291 /// Checks if the given signature matches the expectations for `is_empty`
292 fn check_is_empty_sig(sig: FnSig<'_>, self_kind: ImplicitSelfKind, len_output: LenOutput<'_>) -> bool {
293 match &**sig.inputs_and_output {
294 [arg, res] if len_output.matches_is_empty_output(res) => {
296 (arg.kind(), self_kind),
297 (ty::Ref(_, _, Mutability::Not), ImplicitSelfKind::ImmRef)
298 | (ty::Ref(_, _, Mutability::Mut), ImplicitSelfKind::MutRef)
299 ) || (!arg.is_ref() && matches!(self_kind, ImplicitSelfKind::Imm | ImplicitSelfKind::Mut))
305 /// Checks if the given type has an `is_empty` method with the appropriate signature.
306 fn check_for_is_empty(
307 cx: &LateContext<'_>,
309 self_kind: ImplicitSelfKind,
310 output: LenOutput<'_>,
315 let is_empty = Symbol::intern("is_empty");
318 .inherent_impls(impl_ty)
320 .flat_map(|&id| cx.tcx.associated_items(id).filter_by_name_unhygienic(is_empty))
321 .find(|item| item.kind == AssocKind::Fn);
323 let (msg, is_empty_span, self_kind) = match is_empty {
326 "{} `{}` has a public `len` method, but no `is_empty` method",
333 Some(is_empty) if !cx.access_levels.is_exported(is_empty.def_id.expect_local()) => (
335 "{} `{}` has a public `len` method, but a private `is_empty` method",
339 Some(cx.tcx.def_span(is_empty.def_id)),
343 if !(is_empty.fn_has_self_parameter
344 && check_is_empty_sig(cx.tcx.fn_sig(is_empty.def_id).skip_binder(), self_kind, output)) =>
348 "{} `{}` has a public `len` method, but the `is_empty` method has an unexpected signature",
352 Some(cx.tcx.def_span(is_empty.def_id)),
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");
363 if let Some(self_kind) = self_kind {
364 db.note(&output.expected_sig(self_kind));
369 fn check_cmp(cx: &LateContext<'_>, span: Span, method: &Expr<'_>, lit: &Expr<'_>, op: &str, compare_to: u32) {
370 if let (&ExprKind::MethodCall(method_path, _, args, _), &ExprKind::Lit(ref 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" {
378 check_len(cx, span, method_path.ident.name, args, &lit.node, op, compare_to);
380 check_empty_expr(cx, span, method, lit, op);
385 cx: &LateContext<'_>,
393 if let LitKind::Int(lit, _) = *lit {
394 // check if length is compared to the specified number
395 if lit != u128::from(compare_to) {
399 if method_name == sym::len && args.len() == 1 && has_is_empty(cx, &args[0]) {
400 let mut applicability = Applicability::MachineApplicable;
405 &format!("length comparison to {}", if compare_to == 0 { "zero" } else { "one" }),
406 &format!("using `{}is_empty` is clearer and more explicit", op),
410 snippet_with_applicability(cx, args[0].span, "_", &mut applicability)
418 fn check_empty_expr(cx: &LateContext<'_>, span: Span, lit1: &Expr<'_>, lit2: &Expr<'_>, op: &str) {
419 if (is_empty_array(lit2) || is_empty_string(lit2)) && has_is_empty(cx, lit1) {
420 let mut applicability = Applicability::MachineApplicable;
425 "comparison to empty slice",
426 &format!("using `{}is_empty` is clearer and more explicit", op),
430 snippet_with_applicability(cx, lit1.span, "_", &mut applicability)
437 fn is_empty_string(expr: &Expr<'_>) -> bool {
438 if let ExprKind::Lit(ref lit) = expr.kind {
439 if let LitKind::Str(lit, _) = lit.node {
440 let lit = lit.as_str();
447 fn is_empty_array(expr: &Expr<'_>) -> bool {
448 if let ExprKind::Array(arr) = expr.kind {
449 return arr.is_empty();
454 /// Checks if this type has an `is_empty` method.
455 fn has_is_empty(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
456 /// Gets an `AssocItem` and return true if it matches `is_empty(self)`.
457 fn is_is_empty(cx: &LateContext<'_>, item: &ty::AssocItem) -> bool {
458 if let ty::AssocKind::Fn = item.kind {
459 if item.ident.name.as_str() == "is_empty" {
460 let sig = cx.tcx.fn_sig(item.def_id);
461 let ty = sig.skip_binder();
462 ty.inputs().len() == 1
471 /// Checks the inherent impl's items for an `is_empty(self)` method.
472 fn has_is_empty_impl(cx: &LateContext<'_>, id: DefId) -> bool {
473 cx.tcx.inherent_impls(id).iter().any(|imp| {
475 .associated_items(*imp)
476 .in_definition_order()
477 .any(|item| is_is_empty(cx, item))
481 let ty = &cx.typeck_results().expr_ty(expr).peel_refs();
483 ty::Dynamic(tt, ..) => tt.principal().map_or(false, |principal| {
485 .associated_items(principal.def_id())
486 .in_definition_order()
487 .any(|item| is_is_empty(cx, item))
489 ty::Projection(ref proj) => has_is_empty_impl(cx, proj.item_def_id),
490 ty::Adt(id, _) => has_is_empty_impl(cx, id.did),
491 ty::Array(..) | ty::Slice(..) | ty::Str => true,