]> git.lizzy.rs Git - rust.git/blob - src/len_zero.rs
added wiki comments + wiki-generating python script
[rust.git] / src / len_zero.rs
1 use rustc::lint::*;
2 use rustc_front::hir::*;
3 use syntax::ast::Name;
4 use syntax::ptr::P;
5 use syntax::codemap::{Span, Spanned};
6 use rustc::middle::def_id::DefId;
7 use rustc::middle::ty::{self, MethodTraitItemId, ImplOrTraitItemId};
8
9 use syntax::ast::Lit_::*;
10 use syntax::ast::Lit;
11
12 use utils::{get_item_name, snippet, span_lint, walk_ptrs_ty};
13
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.
15 ///
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.
17 ///
18 /// **Known problems:** None
19 ///
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");
24
25 /// **What it does:** This lint checks for items that implement `.len()` but not `.is_empty()`. It is `Warn` by default.
26 ///
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.
28 ///
29 /// **Known problems:** None
30 ///
31 /// **Example:**
32 /// ```
33 /// impl X {
34 ///     fn len(&self) -> usize { .. }
35 /// }
36 /// ```
37 declare_lint!(pub LEN_WITHOUT_IS_EMPTY, Warn,
38               "traits and impls that have `.len()` but not `.is_empty()`");
39
40 #[derive(Copy,Clone)]
41 pub struct LenZero;
42
43 impl LintPass for LenZero {
44     fn get_lints(&self) -> LintArray {
45         lint_array!(LEN_ZERO, LEN_WITHOUT_IS_EMPTY)
46     }
47 }
48
49 impl LateLintPass for LenZero {
50     fn check_item(&mut self, cx: &LateContext, item: &Item) {
51         match item.node {
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),
56             _ => ()
57         }
58     }
59
60     fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
61         if let ExprBinary(Spanned{node: cmp, ..}, ref left, ref right) =
62                 expr.node {
63             match cmp {
64                 BiEq => check_cmp(cx, expr.span, left, right, ""),
65                 BiGt | BiNe => check_cmp(cx, expr.span, left, right, "!"),
66                 _ => ()
67             }
68         }
69     }
70 }
71
72 fn check_trait_items(cx: &LateContext, item: &Item, trait_items: &[P<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 }
76     }
77
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",
85                                    item.name));
86             }
87         };
88     }
89 }
90
91 fn check_impl_items(cx: &LateContext, item: &Item, impl_items: &[P<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 }
95     }
96
97     if !impl_items.iter().any(|i| is_named_self(i, "is_empty")) {
98         for i in impl_items {
99             if is_named_self(i, "len") {
100                 let s = i.span;
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",
105                                    item.name));
106                 return;
107             }
108         }
109     }
110 }
111
112 fn is_self_sig(sig: &MethodSig) -> bool {
113     if let SelfStatic = sig.explicit_self.node {
114         false } else { sig.decl.inputs.len() == 1 }
115 }
116
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; }
121     }
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),
127         _ => ()
128     }
129 }
130
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, "_")))
139             }
140     }
141 }
142
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
152                 } else { false }
153         } else { false }
154     }
155
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)))))
162     }
163
164     let ty = &walk_ptrs_ty(&cx.tcx.expr_ty(expr));
165     match ty.sty {
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,
174         _ => false,
175     }
176 }