1 use crate::utils::{get_item_name, snippet_with_applicability, span_lint, span_lint_and_sugg, walk_ptrs_ty};
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_lint_pass!(LenZero => [LEN_ZERO, LEN_WITHOUT_IS_EMPTY]);
73 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for LenZero {
74 fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item<'_>) {
75 if item.span.from_expansion() {
80 ItemKind::Trait(_, _, _, _, ref trait_items) => check_trait_items(cx, item, trait_items),
83 items: ref impl_items,
85 } => check_impl_items(cx, item, impl_items),
90 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'_>) {
91 if expr.span.from_expansion() {
95 if let ExprKind::Binary(Spanned { node: cmp, .. }, ref left, ref right) = expr.kind {
98 check_cmp(cx, expr.span, left, right, "", 0); // len == 0
99 check_cmp(cx, expr.span, right, left, "", 0); // 0 == len
102 check_cmp(cx, expr.span, left, right, "!", 0); // len != 0
103 check_cmp(cx, expr.span, right, left, "!", 0); // 0 != len
106 check_cmp(cx, expr.span, left, right, "!", 0); // len > 0
107 check_cmp(cx, expr.span, right, left, "", 1); // 1 > len
110 check_cmp(cx, expr.span, left, right, "", 1); // len < 1
111 check_cmp(cx, expr.span, right, left, "!", 0); // 0 < len
113 BinOpKind::Ge => check_cmp(cx, expr.span, left, right, "!", 1), // len >= 1
114 BinOpKind::Le => check_cmp(cx, expr.span, right, left, "!", 1), // 1 <= len
121 fn check_trait_items(cx: &LateContext<'_, '_>, visited_trait: &Item<'_>, trait_items: &[TraitItemRef]) {
122 fn is_named_self(cx: &LateContext<'_, '_>, item: &TraitItemRef, name: &str) -> bool {
123 item.ident.name.as_str() == name
124 && if let AssocItemKind::Fn { has_self } = item.kind {
126 let did = cx.tcx.hir().local_def_id(item.id.hir_id);
127 cx.tcx.fn_sig(did).inputs().skip_binder().len() == 1
134 // fill the set with current and super traits
135 fn fill_trait_set(traitt: DefId, set: &mut FxHashSet<DefId>, cx: &LateContext<'_, '_>) {
136 if set.insert(traitt) {
137 for supertrait in rustc_trait_selection::traits::supertrait_def_ids(cx.tcx, traitt) {
138 fill_trait_set(supertrait, set, cx);
143 if cx.access_levels.is_exported(visited_trait.hir_id) && trait_items.iter().any(|i| is_named_self(cx, i, "len")) {
144 let mut current_and_super_traits = FxHashSet::default();
145 let visited_trait_def_id = cx.tcx.hir().local_def_id(visited_trait.hir_id);
146 fill_trait_set(visited_trait_def_id.to_def_id(), &mut current_and_super_traits, cx);
148 let is_empty_method_found = current_and_super_traits
150 .flat_map(|&i| cx.tcx.associated_items(i).in_definition_order())
152 i.kind == ty::AssocKind::Fn
153 && i.fn_has_self_parameter
154 && i.ident.name == sym!(is_empty)
155 && cx.tcx.fn_sig(i.def_id).inputs().skip_binder().len() == 1
158 if !is_empty_method_found {
161 LEN_WITHOUT_IS_EMPTY,
164 "trait `{}` has a `len` method but no (possibly inherited) `is_empty` method",
165 visited_trait.ident.name
172 fn check_impl_items(cx: &LateContext<'_, '_>, item: &Item<'_>, impl_items: &[ImplItemRef<'_>]) {
173 fn is_named_self(cx: &LateContext<'_, '_>, item: &ImplItemRef<'_>, name: &str) -> bool {
174 item.ident.name.as_str() == name
175 && if let AssocItemKind::Fn { has_self } = item.kind {
177 let did = cx.tcx.hir().local_def_id(item.id.hir_id);
178 cx.tcx.fn_sig(did).inputs().skip_binder().len() == 1
185 let is_empty = if let Some(is_empty) = impl_items.iter().find(|i| is_named_self(cx, i, "is_empty")) {
186 if cx.access_levels.is_exported(is_empty.id.hir_id) {
195 if let Some(i) = impl_items.iter().find(|i| is_named_self(cx, i, "len")) {
196 if cx.access_levels.is_exported(i.id.hir_id) {
197 let def_id = cx.tcx.hir().local_def_id(item.hir_id);
198 let ty = cx.tcx.type_of(def_id);
202 LEN_WITHOUT_IS_EMPTY,
205 "item `{}` has a public `len` method but {} `is_empty` method",
213 fn check_cmp(cx: &LateContext<'_, '_>, span: Span, method: &Expr<'_>, lit: &Expr<'_>, op: &str, compare_to: u32) {
214 if let (&ExprKind::MethodCall(ref method_path, _, ref args), &ExprKind::Lit(ref lit)) = (&method.kind, &lit.kind) {
215 // check if we are in an is_empty() method
216 if let Some(name) = get_item_name(cx, method) {
217 if name.as_str() == "is_empty" {
222 check_len(cx, span, method_path.ident.name, args, &lit.node, op, compare_to)
227 cx: &LateContext<'_, '_>,
235 if let LitKind::Int(lit, _) = *lit {
236 // check if length is compared to the specified number
237 if lit != u128::from(compare_to) {
241 if method_name.as_str() == "len" && args.len() == 1 && has_is_empty(cx, &args[0]) {
242 let mut applicability = Applicability::MachineApplicable;
247 &format!("length comparison to {}", if compare_to == 0 { "zero" } else { "one" }),
248 &format!("using `{}is_empty` is clearer and more explicit", op),
252 snippet_with_applicability(cx, args[0].span, "_", &mut applicability)
260 /// Checks if this type has an `is_empty` method.
261 fn has_is_empty(cx: &LateContext<'_, '_>, expr: &Expr<'_>) -> bool {
262 /// Gets an `AssocItem` and return true if it matches `is_empty(self)`.
263 fn is_is_empty(cx: &LateContext<'_, '_>, item: &ty::AssocItem) -> bool {
264 if let ty::AssocKind::Fn = item.kind {
265 if item.ident.name.as_str() == "is_empty" {
266 let sig = cx.tcx.fn_sig(item.def_id);
267 let ty = sig.skip_binder();
268 ty.inputs().len() == 1
277 /// Checks the inherent impl's items for an `is_empty(self)` method.
278 fn has_is_empty_impl(cx: &LateContext<'_, '_>, id: DefId) -> bool {
279 cx.tcx.inherent_impls(id).iter().any(|imp| {
281 .associated_items(*imp)
282 .in_definition_order()
283 .any(|item| is_is_empty(cx, &item))
287 let ty = &walk_ptrs_ty(cx.tables.expr_ty(expr));
289 ty::Dynamic(ref tt, ..) => {
290 if let Some(principal) = tt.principal() {
292 .associated_items(principal.def_id())
293 .in_definition_order()
294 .any(|item| is_is_empty(cx, &item))
299 ty::Projection(ref proj) => has_is_empty_impl(cx, proj.item_def_id),
300 ty::Adt(id, _) => has_is_empty_impl(cx, id.did),
301 ty::Array(..) | ty::Slice(..) | ty::Str => true,