1 use rustc::hir::def_id::DefId;
4 use rustc::{declare_lint, lint_array};
6 use std::collections::HashSet;
7 use syntax::ast::{Lit, LitKind, Name};
8 use syntax::codemap::{Span, Spanned};
9 use crate::utils::{get_item_name, in_macro, snippet, span_lint, span_lint_and_sugg, walk_ptrs_ty};
11 /// **What it does:** Checks for getting the length of something via `.len()`
12 /// just to compare to zero, and suggests using `.is_empty()` where applicable.
14 /// **Why is this bad?** Some structures can answer `.is_empty()` much faster
15 /// than calculating their length. Notably, for slices, getting the length
16 /// requires a subtraction whereas `.is_empty()` is just a comparison. So it is
17 /// good to get into the habit of using `.is_empty()`, and having it is cheap.
18 /// Besides, it makes the intent clearer than a manual comparison.
20 /// **Known problems:** None.
24 /// if x.len() == 0 { .. }
26 declare_clippy_lint! {
29 "checking `.len() == 0` or `.len() > 0` (or similar) when `.is_empty()` \
30 could be used instead"
33 /// **What it does:** Checks for items that implement `.len()` but not
36 /// **Why is this bad?** It is good custom to have both methods, because for
37 /// some data structures, asking about the length will be a costly operation,
38 /// whereas `.is_empty()` can usually answer in constant time. Also it used to
39 /// lead to false positives on the [`len_zero`](#len_zero) lint – currently that
40 /// lint will ignore such entities.
42 /// **Known problems:** None.
47 /// pub fn len(&self) -> usize { .. }
50 declare_clippy_lint! {
51 pub LEN_WITHOUT_IS_EMPTY,
53 "traits or impls with a public `len` method but no corresponding `is_empty` method"
56 #[derive(Copy, Clone)]
59 impl LintPass for LenZero {
60 fn get_lints(&self) -> LintArray {
61 lint_array!(LEN_ZERO, LEN_WITHOUT_IS_EMPTY)
65 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for LenZero {
66 fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item) {
67 if in_macro(item.span) {
72 ItemKind::Trait(_, _, _, _, ref trait_items) => check_trait_items(cx, item, trait_items),
73 ItemKind::Impl(_, _, _, _, None, _, ref impl_items) => check_impl_items(cx, item, impl_items),
78 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
79 if in_macro(expr.span) {
83 if let ExprKind::Binary(Spanned { node: cmp, .. }, ref left, ref right) = expr.node {
86 check_cmp(cx, expr.span, left, right, "", 0); // len == 0
87 check_cmp(cx, expr.span, right, left, "", 0); // 0 == len
90 check_cmp(cx, expr.span, left, right, "!", 0); // len != 0
91 check_cmp(cx, expr.span, right, left, "!", 0); // 0 != len
94 check_cmp(cx, expr.span, left, right, "!", 0); // len > 0
95 check_cmp(cx, expr.span, right, left, "", 1); // 1 > len
98 check_cmp(cx, expr.span, left, right, "", 1); // len < 1
99 check_cmp(cx, expr.span, right, left, "!", 0); // 0 < len
101 BinOpKind::Ge => check_cmp(cx, expr.span, left, right, "!", 1), // len <= 1
102 BinOpKind::Le => check_cmp(cx, expr.span, right, left, "!", 1), // 1 >= len
109 fn check_trait_items(cx: &LateContext, visited_trait: &Item, trait_items: &[TraitItemRef]) {
110 fn is_named_self(cx: &LateContext, item: &TraitItemRef, name: &str) -> bool {
111 item.ident.name == name && if let AssociatedItemKind::Method { has_self } = item.kind {
113 let did = cx.tcx.hir.local_def_id(item.id.node_id);
114 cx.tcx.fn_sig(did).inputs().skip_binder().len() == 1
121 // fill the set with current and super traits
122 fn fill_trait_set(traitt: DefId, set: &mut HashSet<DefId>, cx: &LateContext) {
123 if set.insert(traitt) {
124 for supertrait in ::rustc::traits::supertrait_def_ids(cx.tcx, traitt) {
125 fill_trait_set(supertrait, set, cx);
130 if cx.access_levels.is_exported(visited_trait.id) && trait_items.iter().any(|i| is_named_self(cx, i, "len")) {
131 let mut current_and_super_traits = HashSet::new();
132 let visited_trait_def_id = cx.tcx.hir.local_def_id(visited_trait.id);
133 fill_trait_set(visited_trait_def_id, &mut current_and_super_traits, cx);
135 let is_empty_method_found = current_and_super_traits
137 .flat_map(|&i| cx.tcx.associated_items(i))
139 i.kind == ty::AssociatedKind::Method && i.method_has_self_argument && i.ident.name == "is_empty"
140 && cx.tcx.fn_sig(i.def_id).inputs().skip_binder().len() == 1
143 if !is_empty_method_found {
146 LEN_WITHOUT_IS_EMPTY,
149 "trait `{}` has a `len` method but no (possibly inherited) `is_empty` method",
157 fn check_impl_items(cx: &LateContext, item: &Item, impl_items: &[ImplItemRef]) {
158 fn is_named_self(cx: &LateContext, item: &ImplItemRef, name: &str) -> bool {
159 item.ident.name == name && if let AssociatedItemKind::Method { has_self } = item.kind {
161 let did = cx.tcx.hir.local_def_id(item.id.node_id);
162 cx.tcx.fn_sig(did).inputs().skip_binder().len() == 1
169 let is_empty = if let Some(is_empty) = impl_items.iter().find(|i| is_named_self(cx, i, "is_empty")) {
170 if cx.access_levels.is_exported(is_empty.id.node_id) {
179 if let Some(i) = impl_items.iter().find(|i| is_named_self(cx, i, "len")) {
180 if cx.access_levels.is_exported(i.id.node_id) {
181 let def_id = cx.tcx.hir.local_def_id(item.id);
182 let ty = cx.tcx.type_of(def_id);
186 LEN_WITHOUT_IS_EMPTY,
189 "item `{}` has a public `len` method but {} `is_empty` method",
197 fn check_cmp(cx: &LateContext, span: Span, method: &Expr, lit: &Expr, op: &str, compare_to: u32) {
198 if let (&ExprKind::MethodCall(ref method_path, _, ref args), &ExprKind::Lit(ref lit)) = (&method.node, &lit.node) {
199 // check if we are in an is_empty() method
200 if let Some(name) = get_item_name(cx, method) {
201 if name == "is_empty" {
206 check_len(cx, span, method_path.ident.name, args, lit, op, compare_to)
210 fn check_len(cx: &LateContext, span: Span, method_name: Name, args: &[Expr], lit: &Lit, op: &str, compare_to: u32) {
212 node: LitKind::Int(lit, _),
216 // check if length is compared to the specified number
217 if lit != u128::from(compare_to) {
221 if method_name == "len" && args.len() == 1 && has_is_empty(cx, &args[0]) {
226 &format!("length comparison to {}", if compare_to == 0 { "zero" } else { "one" }),
227 "using `is_empty` is more concise",
228 format!("{}{}.is_empty()", op, snippet(cx, args[0].span, "_")),
234 /// Check if this type has an `is_empty` method.
235 fn has_is_empty(cx: &LateContext, expr: &Expr) -> bool {
236 /// Get an `AssociatedItem` and return true if it matches `is_empty(self)`.
237 fn is_is_empty(cx: &LateContext, item: &ty::AssociatedItem) -> bool {
238 if let ty::AssociatedKind::Method = item.kind {
239 if item.ident.name == "is_empty" {
240 let sig = cx.tcx.fn_sig(item.def_id);
241 let ty = sig.skip_binder();
242 ty.inputs().len() == 1
251 /// Check the inherent impl's items for an `is_empty(self)` method.
252 fn has_is_empty_impl(cx: &LateContext, id: DefId) -> bool {
253 cx.tcx.inherent_impls(id).iter().any(|imp| {
255 .associated_items(*imp)
256 .any(|item| is_is_empty(cx, &item))
260 let ty = &walk_ptrs_ty(cx.tables.expr_ty(expr));
262 ty::TyDynamic(ref tt, ..) => cx.tcx
263 .associated_items(tt.principal().expect("trait impl not found").def_id())
264 .any(|item| is_is_empty(cx, &item)),
265 ty::TyProjection(ref proj) => has_is_empty_impl(cx, proj.item_def_id),
266 ty::TyAdt(id, _) => has_is_empty_impl(cx, id.did),
267 ty::TyArray(..) | ty::TySlice(..) | ty::TyStr => true,