2 use rustc::hir::def_id::DefId;
5 use syntax::ast::{Lit, LitKind, Name};
6 use syntax::codemap::{Span, Spanned};
7 use utils::{get_item_name, in_macro, snippet, span_lint, span_lint_and_then, walk_ptrs_ty};
9 /// **What it does:** Checks for getting the length of something via `.len()`
10 /// just to compare to zero, and suggests using `.is_empty()` where applicable.
12 /// **Why is this bad?** Some structures can answer `.is_empty()` much faster
13 /// than calculating their length. So it is good to get into the habit of using
14 /// `.is_empty()`, and having it is cheap. Besides, it makes the intent clearer
15 /// than a comparison.
17 /// **Known problems:** None.
21 /// if x.len() == 0 { .. }
26 "checking `.len() == 0` or `.len() > 0` (or similar) when `.is_empty()` \
27 could be used instead"
30 /// **What it does:** Checks for items that implement `.len()` but not
33 /// **Why is this bad?** It is good custom to have both methods, because for
34 /// some data structures, asking about the length will be a costly operation,
35 /// whereas `.is_empty()` can usually answer in constant time. Also it used to
36 /// lead to false positives on the [`len_zero`](#len_zero) lint – currently that
37 /// lint will ignore such entities.
39 /// **Known problems:** None.
44 /// pub fn len(&self) -> usize { .. }
48 pub LEN_WITHOUT_IS_EMPTY,
50 "traits or impls with a public `len` method but no corresponding `is_empty` method"
56 impl LintPass for LenZero {
57 fn get_lints(&self) -> LintArray {
58 lint_array!(LEN_ZERO, LEN_WITHOUT_IS_EMPTY)
62 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for LenZero {
63 fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item) {
64 if in_macro(item.span) {
69 ItemTrait(_, _, _, ref trait_items) => check_trait_items(cx, item, trait_items),
70 ItemImpl(_, _, _, _, None, _, ref impl_items) => check_impl_items(cx, item, impl_items),
75 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
76 if in_macro(expr.span) {
80 if let ExprBinary(Spanned { node: cmp, .. }, ref left, ref right) = expr.node {
82 BiEq => check_cmp(cx, expr.span, left, right, ""),
83 BiGt | BiNe => check_cmp(cx, expr.span, left, right, "!"),
90 fn check_trait_items(cx: &LateContext, item: &Item, trait_items: &[TraitItemRef]) {
91 fn is_named_self(cx: &LateContext, item: &TraitItemRef, name: &str) -> bool {
93 if let AssociatedItemKind::Method { has_self } = item.kind {
96 let did = cx.tcx.hir.local_def_id(item.id.node_id);
97 let impl_ty = cx.tcx.type_of(did);
98 impl_ty.fn_args().skip_binder().len() == 1
105 if !trait_items.iter().any(|i| is_named_self(cx, i, "is_empty")) {
106 if let Some(i) = trait_items.iter().find(|i| is_named_self(cx, i, "len")) {
107 if cx.access_levels.is_exported(i.id.node_id) {
109 LEN_WITHOUT_IS_EMPTY,
111 &format!("trait `{}` has a `len` method but no `is_empty` method", item.name));
117 fn check_impl_items(cx: &LateContext, item: &Item, impl_items: &[ImplItemRef]) {
118 fn is_named_self(cx: &LateContext, item: &ImplItemRef, name: &str) -> bool {
120 if let AssociatedItemKind::Method { has_self } = item.kind {
123 let did = cx.tcx.hir.local_def_id(item.id.node_id);
124 let impl_ty = cx.tcx.type_of(did);
125 impl_ty.fn_args().skip_binder().len() == 1
132 let is_empty = if let Some(is_empty) = impl_items.iter().find(|i| is_named_self(cx, i, "is_empty")) {
133 if cx.access_levels.is_exported(is_empty.id.node_id) {
142 if let Some(i) = impl_items.iter().find(|i| is_named_self(cx, i, "len")) {
143 if cx.access_levels.is_exported(i.id.node_id) {
144 let def_id = cx.tcx.hir.local_def_id(item.id);
145 let ty = cx.tcx.type_of(def_id);
148 LEN_WITHOUT_IS_EMPTY,
150 &format!("item `{}` has a public `len` method but {} `is_empty` method", ty, is_empty));
155 fn check_cmp(cx: &LateContext, span: Span, left: &Expr, right: &Expr, op: &str) {
156 // check if we are in an is_empty() method
157 if let Some(name) = get_item_name(cx, left) {
158 if name == "is_empty" {
162 match (&left.node, &right.node) {
163 (&ExprLit(ref lit), &ExprMethodCall(ref method, _, ref args)) |
164 (&ExprMethodCall(ref method, _, ref args), &ExprLit(ref lit)) => {
165 check_len_zero(cx, span, method.node, args, lit, op)
171 fn check_len_zero(cx: &LateContext, span: Span, name: Name, args: &[Expr], lit: &Lit, op: &str) {
172 if let Spanned { node: LitKind::Int(0, _), .. } = *lit {
173 if name == "len" && args.len() == 1 && has_is_empty(cx, &args[0]) {
174 span_lint_and_then(cx, LEN_ZERO, span, "length comparison to zero", |db| {
175 db.span_suggestion(span,
176 "using `is_empty` is more concise:",
177 format!("{}{}.is_empty()", op, snippet(cx, args[0].span, "_")));
183 /// Check if this type has an `is_empty` method.
184 fn has_is_empty(cx: &LateContext, expr: &Expr) -> bool {
185 /// Get an `AssociatedItem` and return true if it matches `is_empty(self)`.
186 fn is_is_empty(cx: &LateContext, item: &ty::AssociatedItem) -> bool {
187 if let ty::AssociatedKind::Method = item.kind {
188 if item.name == "is_empty" {
189 let sig = cx.tcx.type_of(item.def_id).fn_sig();
190 let ty = sig.skip_binder();
191 ty.inputs().len() == 1
200 /// Check the inherent impl's items for an `is_empty(self)` method.
201 fn has_is_empty_impl(cx: &LateContext, id: DefId) -> bool {
202 cx.tcx.inherent_impls(id)
204 .any(|imp| cx.tcx.associated_items(*imp).any(|item| is_is_empty(cx, &item)))
207 let ty = &walk_ptrs_ty(cx.tables.expr_ty(expr));
209 ty::TyDynamic(..) => {
211 .associated_items(ty.ty_to_def_id().expect("trait impl not found"))
212 .any(|item| is_is_empty(cx, &item))
214 ty::TyProjection(_) => ty.ty_to_def_id().map_or(false, |id| has_is_empty_impl(cx, id)),
215 ty::TyAdt(id, _) => has_is_empty_impl(cx, id.did),
216 ty::TyArray(..) | ty::TySlice(..) | ty::TyStr => true,