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