2 use rustc_front::hir::*;
5 use syntax::codemap::{Span, Spanned};
6 use rustc::middle::def_id::DefId;
7 use rustc::middle::ty::{self, MethodTraitItemId, ImplOrTraitItemId};
9 use syntax::ast::Lit_::*;
12 use utils::{get_item_name, snippet, span_lint, walk_ptrs_ty};
14 /// **What it does:** This lint checks for getting the length of something via `.len()` just to compare to zero, and suggests using `.is_empty()` where applicable. It is `Warn` by default.
16 /// **Why is this bad?** Some structures can answer `.is_empty()` much faster than calculating their length. So it is good to get into the habit of using `.is_empty()`, and having it is cheap. Besides, it makes the intent clearer than a comparison.
18 /// **Known problems:** None
20 /// **Example:** `if x.len() == 0 { .. }`
21 declare_lint!(pub LEN_ZERO, Warn,
22 "checking `.len() == 0` or `.len() > 0` (or similar) when `.is_empty()` \
23 could be used instead");
25 /// **What it does:** This lint checks for items that implement `.len()` but not `.is_empty()`. It is `Warn` by default.
27 /// **Why is this bad?** It is good custom to have both methods, because for some data structures, asking about the length will be a costly operation, whereas `.is_empty()` can usually answer in constant time. Also it used to lead to false positives on the [`len_zero`](#len_zero) lint – currently that lint will ignore such entities.
29 /// **Known problems:** None
34 /// fn len(&self) -> usize { .. }
37 declare_lint!(pub LEN_WITHOUT_IS_EMPTY, Warn,
38 "traits and impls that have `.len()` but not `.is_empty()`");
43 impl LintPass for LenZero {
44 fn get_lints(&self) -> LintArray {
45 lint_array!(LEN_ZERO, LEN_WITHOUT_IS_EMPTY)
49 impl LateLintPass for LenZero {
50 fn check_item(&mut self, cx: &LateContext, item: &Item) {
52 ItemTrait(_, _, _, ref trait_items) =>
53 check_trait_items(cx, item, trait_items),
54 ItemImpl(_, _, _, None, _, ref impl_items) => // only non-trait
55 check_impl_items(cx, item, impl_items),
60 fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
61 if let ExprBinary(Spanned{node: cmp, ..}, ref left, ref right) =
64 BiEq => check_cmp(cx, expr.span, left, right, ""),
65 BiGt | BiNe => check_cmp(cx, expr.span, left, right, "!"),
72 fn check_trait_items(cx: &LateContext, item: &Item, trait_items: &[TraitItem]) {
73 fn is_named_self(item: &TraitItem, name: &str) -> bool {
74 item.name.as_str() == name && if let MethodTraitItem(ref sig, _) =
75 item.node { is_self_sig(sig) } else { false }
78 if !trait_items.iter().any(|i| is_named_self(i, "is_empty")) {
79 //span_lint(cx, LEN_WITHOUT_IS_EMPTY, item.span, &format!("trait {}", item.ident));
80 for i in trait_items {
81 if is_named_self(i, "len") {
82 span_lint(cx, LEN_WITHOUT_IS_EMPTY, i.span,
83 &format!("trait `{}` has a `.len(_: &Self)` method, but no \
84 `.is_empty(_: &Self)` method. Consider adding one",
91 fn check_impl_items(cx: &LateContext, item: &Item, impl_items: &[ImplItem]) {
92 fn is_named_self(item: &ImplItem, name: &str) -> bool {
93 item.name.as_str() == name && if let ImplItemKind::Method(ref sig, _) =
94 item.node { is_self_sig(sig) } else { false }
97 if !impl_items.iter().any(|i| is_named_self(i, "is_empty")) {
99 if is_named_self(i, "len") {
101 span_lint(cx, LEN_WITHOUT_IS_EMPTY,
102 Span{ lo: s.lo, hi: s.lo, expn_id: s.expn_id },
103 &format!("item `{}` has a `.len(_: &Self)` method, but no \
104 `.is_empty(_: &Self)` method. Consider adding one",
112 fn is_self_sig(sig: &MethodSig) -> bool {
113 if let SelfStatic = sig.explicit_self.node {
114 false } else { sig.decl.inputs.len() == 1 }
117 fn check_cmp(cx: &LateContext, span: Span, left: &Expr, right: &Expr, op: &str) {
118 // check if we are in an is_empty() method
119 if let Some(name) = get_item_name(cx, left) {
120 if name.as_str() == "is_empty" { return; }
122 match (&left.node, &right.node) {
123 (&ExprLit(ref lit), &ExprMethodCall(ref method, _, ref args)) =>
124 check_len_zero(cx, span, &method.node, args, lit, op),
125 (&ExprMethodCall(ref method, _, ref args), &ExprLit(ref lit)) =>
126 check_len_zero(cx, span, &method.node, args, lit, op),
131 fn check_len_zero(cx: &LateContext, span: Span, name: &Name,
132 args: &[P<Expr>], lit: &Lit, op: &str) {
133 if let Spanned{node: LitInt(0, _), ..} = *lit {
134 if name.as_str() == "len" && args.len() == 1 &&
135 has_is_empty(cx, &args[0]) {
136 span_lint(cx, LEN_ZERO, span, &format!(
137 "consider replacing the len comparison with `{}{}.is_empty()`",
138 op, snippet(cx, args[0].span, "_")))
143 /// check if this type has an is_empty method
144 fn has_is_empty(cx: &LateContext, expr: &Expr) -> bool {
145 /// get a ImplOrTraitItem and return true if it matches is_empty(self)
146 fn is_is_empty(cx: &LateContext, id: &ImplOrTraitItemId) -> bool {
147 if let MethodTraitItemId(def_id) = *id {
148 if let ty::MethodTraitItem(ref method) =
149 cx.tcx.impl_or_trait_item(def_id) {
150 method.name.as_str() == "is_empty"
151 && method.fty.sig.skip_binder().inputs.len() == 1
156 /// check the inherent impl's items for an is_empty(self) method
157 fn has_is_empty_impl(cx: &LateContext, id: &DefId) -> bool {
158 let impl_items = cx.tcx.impl_items.borrow();
159 cx.tcx.inherent_impls.borrow().get(id).map_or(false,
160 |ids| ids.iter().any(|iid| impl_items.get(iid).map_or(false,
161 |iids| iids.iter().any(|i| is_is_empty(cx, i)))))
164 let ty = &walk_ptrs_ty(&cx.tcx.expr_ty(expr));
166 ty::TyTrait(_) => cx.tcx.trait_item_def_ids.borrow().get(
167 &ty.ty_to_def_id().expect("trait impl not found")).map_or(false,
168 |ids| ids.iter().any(|i| is_is_empty(cx, i))),
169 ty::TyProjection(_) => ty.ty_to_def_id().map_or(false,
170 |id| has_is_empty_impl(cx, &id)),
171 ty::TyEnum(ref id, _) | ty::TyStruct(ref id, _) =>
172 has_is_empty_impl(cx, &id.did),
173 ty::TyArray(..) => true,