]> git.lizzy.rs Git - rust.git/blob - src/len_zero.rs
rustup to 1.5.0-nightly (7bf4c885f 2015-09-26)
[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 declare_lint!(pub LEN_ZERO, Warn,
15               "checking `.len() == 0` or `.len() > 0` (or similar) when `.is_empty()` \
16                could be used instead");
17
18 declare_lint!(pub LEN_WITHOUT_IS_EMPTY, Warn,
19               "traits and impls that have `.len()` but not `.is_empty()`");
20
21 #[derive(Copy,Clone)]
22 pub struct LenZero;
23
24 impl LintPass for LenZero {
25     fn get_lints(&self) -> LintArray {
26         lint_array!(LEN_ZERO, LEN_WITHOUT_IS_EMPTY)
27     }
28 }
29
30 impl LateLintPass for LenZero {
31     fn check_item(&mut self, cx: &LateContext, item: &Item) {
32         match item.node {
33             ItemTrait(_, _, _, ref trait_items) =>
34                 check_trait_items(cx, item, trait_items),
35             ItemImpl(_, _, _, None, _, ref impl_items) => // only non-trait
36                 check_impl_items(cx, item, impl_items),
37             _ => ()
38         }
39     }
40
41     fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
42         if let ExprBinary(Spanned{node: cmp, ..}, ref left, ref right) =
43                 expr.node {
44             match cmp {
45                 BiEq => check_cmp(cx, expr.span, left, right, ""),
46                 BiGt | BiNe => check_cmp(cx, expr.span, left, right, "!"),
47                 _ => ()
48             }
49         }
50     }
51 }
52
53 fn check_trait_items(cx: &LateContext, item: &Item, trait_items: &[P<TraitItem>]) {
54     fn is_named_self(item: &TraitItem, name: &str) -> bool {
55         item.name.as_str() == name && if let MethodTraitItem(ref sig, _) =
56             item.node { is_self_sig(sig) } else { false }
57     }
58
59     if !trait_items.iter().any(|i| is_named_self(i, "is_empty")) {
60         //span_lint(cx, LEN_WITHOUT_IS_EMPTY, item.span, &format!("trait {}", item.ident));
61         for i in trait_items {
62             if is_named_self(i, "len") {
63                 span_lint(cx, LEN_WITHOUT_IS_EMPTY, i.span,
64                           &format!("trait `{}` has a `.len(_: &Self)` method, but no \
65                                     `.is_empty(_: &Self)` method. Consider adding one",
66                                    item.name));
67             }
68         };
69     }
70 }
71
72 fn check_impl_items(cx: &LateContext, item: &Item, impl_items: &[P<ImplItem>]) {
73     fn is_named_self(item: &ImplItem, name: &str) -> bool {
74         item.name.as_str() == name && if let MethodImplItem(ref sig, _) =
75             item.node { is_self_sig(sig) } else { false }
76     }
77
78     if !impl_items.iter().any(|i| is_named_self(i, "is_empty")) {
79         for i in impl_items {
80             if is_named_self(i, "len") {
81                 let s = i.span;
82                 span_lint(cx, LEN_WITHOUT_IS_EMPTY,
83                           Span{ lo: s.lo, hi: s.lo, expn_id: s.expn_id },
84                           &format!("item `{}` has a `.len(_: &Self)` method, but no \
85                                     `.is_empty(_: &Self)` method. Consider adding one",
86                                    item.name));
87                 return;
88             }
89         }
90     }
91 }
92
93 fn is_self_sig(sig: &MethodSig) -> bool {
94     if let SelfStatic = sig.explicit_self.node {
95         false } else { sig.decl.inputs.len() == 1 }
96 }
97
98 fn check_cmp(cx: &LateContext, span: Span, left: &Expr, right: &Expr, op: &str) {    
99     // check if we are in an is_empty() method 
100     if let Some(name) = get_item_name(cx, left) {
101         if name.as_str() == "is_empty" { return; }
102     }
103     match (&left.node, &right.node) {
104         (&ExprLit(ref lit), &ExprMethodCall(ref method, _, ref args)) =>
105             check_len_zero(cx, span, &method.node, args, lit, op),
106         (&ExprMethodCall(ref method, _, ref args), &ExprLit(ref lit)) =>
107             check_len_zero(cx, span, &method.node, args, lit, op),
108         _ => ()
109     }
110 }
111
112 fn check_len_zero(cx: &LateContext, span: Span, name: &Name,
113                   args: &[P<Expr>], lit: &Lit, op: &str) {
114     if let Spanned{node: LitInt(0, _), ..} = *lit {
115         if name.as_str() == "len" && args.len() == 1 &&
116             has_is_empty(cx, &args[0]) {
117                 span_lint(cx, LEN_ZERO, span, &format!(
118                     "consider replacing the len comparison with `{}{}.is_empty()`",
119                     op, snippet(cx, args[0].span, "_")))
120             }
121     }
122 }
123
124 /// check if this type has an is_empty method
125 fn has_is_empty(cx: &LateContext, expr: &Expr) -> bool {
126     /// get a ImplOrTraitItem and return true if it matches is_empty(self)
127     fn is_is_empty(cx: &LateContext, id: &ImplOrTraitItemId) -> bool {
128         if let &MethodTraitItemId(def_id) = id {
129             if let ty::MethodTraitItem(ref method) =
130                 cx.tcx.impl_or_trait_item(def_id) {
131                     method.name.as_str() == "is_empty"
132                         && method.fty.sig.skip_binder().inputs.len() == 1
133                 } else { false }
134         } else { false }
135     }
136
137     /// check the inherent impl's items for an is_empty(self) method
138     fn has_is_empty_impl(cx: &LateContext, id: &DefId) -> bool {
139         let impl_items = cx.tcx.impl_items.borrow();
140         cx.tcx.inherent_impls.borrow().get(id).map_or(false,
141             |ids| ids.iter().any(|iid| impl_items.get(iid).map_or(false,
142                 |iids| iids.iter().any(|i| is_is_empty(cx, i)))))
143     }
144
145     let ty = &walk_ptrs_ty(&cx.tcx.expr_ty(expr));
146     match ty.sty {
147         ty::TyTrait(_) => cx.tcx.trait_item_def_ids.borrow().get(
148             &ty.ty_to_def_id().expect("trait impl not found")).map_or(false,
149                 |ids| ids.iter().any(|i| is_is_empty(cx, i))),
150         ty::TyProjection(_) => ty.ty_to_def_id().map_or(false,
151             |id| has_is_empty_impl(cx, &id)),
152         ty::TyEnum(ref id, _) | ty::TyStruct(ref id, _) =>
153             has_is_empty_impl(cx, &id.did),
154         ty::TyArray(..) => true,
155         _ => false,
156     }
157 }