1 use crate::utils::{get_item_name, snippet_with_applicability, span_lint, span_lint_and_sugg};
2 use rustc_ast::ast::LitKind;
3 use rustc_data_structures::fx::FxHashSet;
4 use rustc_errors::Applicability;
5 use rustc_hir::def_id::DefId;
6 use rustc_hir::{AssocItemKind, BinOpKind, Expr, ExprKind, ImplItemRef, Item, ItemKind, TraitItemRef};
7 use rustc_lint::{LateContext, LateLintPass};
9 use rustc_session::{declare_lint_pass, declare_tool_lint};
10 use rustc_span::source_map::{Span, Spanned, Symbol};
12 declare_clippy_lint! {
13 /// **What it does:** Checks for getting the length of something via `.len()`
14 /// just to compare to zero, and suggests using `.is_empty()` where applicable.
16 /// **Why is this bad?** Some structures can answer `.is_empty()` much faster
17 /// than calculating their length. So it is good to get into the habit of using
18 /// `.is_empty()`, and having it is cheap.
19 /// Besides, it makes the intent clearer than a manual comparison in some contexts.
21 /// **Known problems:** None.
37 /// if !y.is_empty() {
43 "checking `.len() == 0` or `.len() > 0` (or similar) when `.is_empty()` could be used instead"
46 declare_clippy_lint! {
47 /// **What it does:** Checks for items that implement `.len()` but not
50 /// **Why is this bad?** It is good custom to have both methods, because for
51 /// some data structures, asking about the length will be a costly operation,
52 /// whereas `.is_empty()` can usually answer in constant time. Also it used to
53 /// lead to false positives on the [`len_zero`](#len_zero) lint – currently that
54 /// lint will ignore such entities.
56 /// **Known problems:** None.
61 /// pub fn len(&self) -> usize {
66 pub LEN_WITHOUT_IS_EMPTY,
68 "traits or impls with a public `len` method but no corresponding `is_empty` method"
71 declare_clippy_lint! {
72 /// **What it does:** Checks for comparing to an empty slice such as `""` or `[]`,
73 /// and suggests using `.is_empty()` where applicable.
75 /// **Why is this bad?** Some structures can answer `.is_empty()` much faster
76 /// than checking for equality. So it is good to get into the habit of using
77 /// `.is_empty()`, and having it is cheap.
78 /// Besides, it makes the intent clearer than a manual comparison in some contexts.
80 /// **Known problems:** None.
99 /// if arr.is_empty() {
103 pub COMPARISON_TO_EMPTY,
105 "checking `x == \"\"` or `x == []` (or similar) when `.is_empty()` could be used instead"
108 declare_lint_pass!(LenZero => [LEN_ZERO, LEN_WITHOUT_IS_EMPTY, COMPARISON_TO_EMPTY]);
110 impl<'tcx> LateLintPass<'tcx> for LenZero {
111 fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) {
112 if item.span.from_expansion() {
117 ItemKind::Trait(_, _, _, _, ref trait_items) => check_trait_items(cx, item, trait_items),
120 items: ref impl_items,
122 } => check_impl_items(cx, item, impl_items),
127 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
128 if expr.span.from_expansion() {
132 if let ExprKind::Binary(Spanned { node: cmp, .. }, ref left, ref right) = expr.kind {
135 check_cmp(cx, expr.span, left, right, "", 0); // len == 0
136 check_cmp(cx, expr.span, right, left, "", 0); // 0 == len
139 check_cmp(cx, expr.span, left, right, "!", 0); // len != 0
140 check_cmp(cx, expr.span, right, left, "!", 0); // 0 != len
143 check_cmp(cx, expr.span, left, right, "!", 0); // len > 0
144 check_cmp(cx, expr.span, right, left, "", 1); // 1 > len
147 check_cmp(cx, expr.span, left, right, "", 1); // len < 1
148 check_cmp(cx, expr.span, right, left, "!", 0); // 0 < len
150 BinOpKind::Ge => check_cmp(cx, expr.span, left, right, "!", 1), // len >= 1
151 BinOpKind::Le => check_cmp(cx, expr.span, right, left, "!", 1), // 1 <= len
158 fn check_trait_items(cx: &LateContext<'_>, visited_trait: &Item<'_>, trait_items: &[TraitItemRef]) {
159 fn is_named_self(cx: &LateContext<'_>, item: &TraitItemRef, name: &str) -> bool {
160 item.ident.name.as_str() == name
161 && if let AssocItemKind::Fn { has_self } = item.kind {
163 let did = cx.tcx.hir().local_def_id(item.id.hir_id);
164 cx.tcx.fn_sig(did).inputs().skip_binder().len() == 1
171 // fill the set with current and super traits
172 fn fill_trait_set(traitt: DefId, set: &mut FxHashSet<DefId>, cx: &LateContext<'_>) {
173 if set.insert(traitt) {
174 for supertrait in rustc_trait_selection::traits::supertrait_def_ids(cx.tcx, traitt) {
175 fill_trait_set(supertrait, set, cx);
180 if cx.access_levels.is_exported(visited_trait.hir_id) && trait_items.iter().any(|i| is_named_self(cx, i, "len")) {
181 let mut current_and_super_traits = FxHashSet::default();
182 let visited_trait_def_id = cx.tcx.hir().local_def_id(visited_trait.hir_id);
183 fill_trait_set(visited_trait_def_id.to_def_id(), &mut current_and_super_traits, cx);
185 let is_empty_method_found = current_and_super_traits
187 .flat_map(|&i| cx.tcx.associated_items(i).in_definition_order())
189 i.kind == ty::AssocKind::Fn
190 && i.fn_has_self_parameter
191 && i.ident.name == sym!(is_empty)
192 && cx.tcx.fn_sig(i.def_id).inputs().skip_binder().len() == 1
195 if !is_empty_method_found {
198 LEN_WITHOUT_IS_EMPTY,
201 "trait `{}` has a `len` method but no (possibly inherited) `is_empty` method",
202 visited_trait.ident.name
209 fn check_impl_items(cx: &LateContext<'_>, item: &Item<'_>, impl_items: &[ImplItemRef<'_>]) {
210 fn is_named_self(cx: &LateContext<'_>, item: &ImplItemRef<'_>, name: &str) -> bool {
211 item.ident.name.as_str() == name
212 && if let AssocItemKind::Fn { has_self } = item.kind {
214 let did = cx.tcx.hir().local_def_id(item.id.hir_id);
215 cx.tcx.fn_sig(did).inputs().skip_binder().len() == 1
222 let is_empty = if let Some(is_empty) = impl_items.iter().find(|i| is_named_self(cx, i, "is_empty")) {
223 if cx.access_levels.is_exported(is_empty.id.hir_id) {
231 if let Some(i) = impl_items.iter().find(|i| is_named_self(cx, i, "len")) {
232 if cx.access_levels.is_exported(i.id.hir_id) {
233 let def_id = cx.tcx.hir().local_def_id(item.hir_id);
234 let ty = cx.tcx.type_of(def_id);
238 LEN_WITHOUT_IS_EMPTY,
241 "item `{}` has a public `len` method but {} `is_empty` method",
249 fn check_cmp(cx: &LateContext<'_>, span: Span, method: &Expr<'_>, lit: &Expr<'_>, op: &str, compare_to: u32) {
250 if let (&ExprKind::MethodCall(ref method_path, _, ref args, _), &ExprKind::Lit(ref lit)) = (&method.kind, &lit.kind)
252 // check if we are in an is_empty() method
253 if let Some(name) = get_item_name(cx, method) {
254 if name.as_str() == "is_empty" {
259 check_len(cx, span, method_path.ident.name, args, &lit.node, op, compare_to)
261 check_empty_expr(cx, span, method, lit, op)
266 cx: &LateContext<'_>,
274 if let LitKind::Int(lit, _) = *lit {
275 // check if length is compared to the specified number
276 if lit != u128::from(compare_to) {
280 if method_name.as_str() == "len" && args.len() == 1 && has_is_empty(cx, &args[0]) {
281 let mut applicability = Applicability::MachineApplicable;
286 &format!("length comparison to {}", if compare_to == 0 { "zero" } else { "one" }),
287 &format!("using `{}is_empty` is clearer and more explicit", op),
291 snippet_with_applicability(cx, args[0].span, "_", &mut applicability)
299 fn check_empty_expr(cx: &LateContext<'_>, span: Span, lit1: &Expr<'_>, lit2: &Expr<'_>, op: &str) {
300 if (is_empty_array(lit2) || is_empty_string(lit2)) && has_is_empty(cx, lit1) {
301 let mut applicability = Applicability::MachineApplicable;
306 "comparison to empty slice",
307 &format!("using `{}is_empty` is clearer and more explicit", op),
311 snippet_with_applicability(cx, lit1.span, "_", &mut applicability)
318 fn is_empty_string(expr: &Expr<'_>) -> bool {
319 if let ExprKind::Lit(ref lit) = expr.kind {
320 if let LitKind::Str(lit, _) = lit.node {
321 let lit = lit.as_str();
328 fn is_empty_array(expr: &Expr<'_>) -> bool {
329 if let ExprKind::Array(ref arr) = expr.kind {
330 return arr.is_empty();
335 /// Checks if this type has an `is_empty` method.
336 fn has_is_empty(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
337 /// Gets an `AssocItem` and return true if it matches `is_empty(self)`.
338 fn is_is_empty(cx: &LateContext<'_>, item: &ty::AssocItem) -> bool {
339 if let ty::AssocKind::Fn = item.kind {
340 if item.ident.name.as_str() == "is_empty" {
341 let sig = cx.tcx.fn_sig(item.def_id);
342 let ty = sig.skip_binder();
343 ty.inputs().len() == 1
352 /// Checks the inherent impl's items for an `is_empty(self)` method.
353 fn has_is_empty_impl(cx: &LateContext<'_>, id: DefId) -> bool {
354 cx.tcx.inherent_impls(id).iter().any(|imp| {
356 .associated_items(*imp)
357 .in_definition_order()
358 .any(|item| is_is_empty(cx, &item))
362 let ty = &cx.typeck_results().expr_ty(expr).peel_refs();
364 ty::Dynamic(ref tt, ..) => tt.principal().map_or(false, |principal| {
366 .associated_items(principal.def_id())
367 .in_definition_order()
368 .any(|item| is_is_empty(cx, &item))
370 ty::Projection(ref proj) => has_is_empty_impl(cx, proj.item_def_id),
371 ty::Adt(id, _) => has_is_empty_impl(cx, id.did),
372 ty::Array(..) | ty::Slice(..) | ty::Str => true,