]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/len_zero.rs
Fix false positive in `string_add`.
[rust.git] / clippy_lints / src / len_zero.rs
1 use crate::utils::{get_item_name, snippet_with_applicability, span_lint, span_lint_and_sugg, walk_ptrs_ty};
2 use rustc::declare_lint_pass;
3 use rustc::hir::def_id::DefId;
4 use rustc::hir::*;
5 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
6 use rustc::ty;
7 use rustc_data_structures::fx::FxHashSet;
8 use rustc_errors::Applicability;
9 use rustc_session::declare_tool_lint;
10 use syntax::ast::{LitKind, Name};
11 use syntax::source_map::{Span, Spanned};
12
13 declare_clippy_lint! {
14     /// **What it does:** Checks for getting the length of something via `.len()`
15     /// just to compare to zero, and suggests using `.is_empty()` where applicable.
16     ///
17     /// **Why is this bad?** Some structures can answer `.is_empty()` much faster
18     /// than calculating their length. Notably, for slices, getting the length
19     /// requires a subtraction whereas `.is_empty()` is just a comparison. So it is
20     /// good to get into the habit of using `.is_empty()`, and having it is cheap.
21     /// Besides, it makes the intent clearer than a manual comparison.
22     ///
23     /// **Known problems:** None.
24     ///
25     /// **Example:**
26     /// ```ignore
27     /// if x.len() == 0 {
28     ///     ..
29     /// }
30     /// if y.len() != 0 {
31     ///     ..
32     /// }
33     /// ```
34     /// instead use
35     /// ```ignore
36     /// if x.is_empty() {
37     ///     ..
38     /// }
39     /// if !y.is_empty() {
40     ///     ..
41     /// }
42     /// ```
43     pub LEN_ZERO,
44     style,
45     "checking `.len() == 0` or `.len() > 0` (or similar) when `.is_empty()` could be used instead"
46 }
47
48 declare_clippy_lint! {
49     /// **What it does:** Checks for items that implement `.len()` but not
50     /// `.is_empty()`.
51     ///
52     /// **Why is this bad?** It is good custom to have both methods, because for
53     /// some data structures, asking about the length will be a costly operation,
54     /// whereas `.is_empty()` can usually answer in constant time. Also it used to
55     /// lead to false positives on the [`len_zero`](#len_zero) lint – currently that
56     /// lint will ignore such entities.
57     ///
58     /// **Known problems:** None.
59     ///
60     /// **Example:**
61     /// ```ignore
62     /// impl X {
63     ///     pub fn len(&self) -> usize {
64     ///         ..
65     ///     }
66     /// }
67     /// ```
68     pub LEN_WITHOUT_IS_EMPTY,
69     style,
70     "traits or impls with a public `len` method but no corresponding `is_empty` method"
71 }
72
73 declare_lint_pass!(LenZero => [LEN_ZERO, LEN_WITHOUT_IS_EMPTY]);
74
75 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for LenZero {
76     fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item) {
77         if item.span.from_expansion() {
78             return;
79         }
80
81         match item.kind {
82             ItemKind::Trait(_, _, _, _, ref trait_items) => check_trait_items(cx, item, trait_items),
83             ItemKind::Impl(_, _, _, _, None, _, ref impl_items) => check_impl_items(cx, item, impl_items),
84             _ => (),
85         }
86     }
87
88     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
89         if expr.span.from_expansion() {
90             return;
91         }
92
93         if let ExprKind::Binary(Spanned { node: cmp, .. }, ref left, ref right) = expr.kind {
94             match cmp {
95                 BinOpKind::Eq => {
96                     check_cmp(cx, expr.span, left, right, "", 0); // len == 0
97                     check_cmp(cx, expr.span, right, left, "", 0); // 0 == len
98                 },
99                 BinOpKind::Ne => {
100                     check_cmp(cx, expr.span, left, right, "!", 0); // len != 0
101                     check_cmp(cx, expr.span, right, left, "!", 0); // 0 != len
102                 },
103                 BinOpKind::Gt => {
104                     check_cmp(cx, expr.span, left, right, "!", 0); // len > 0
105                     check_cmp(cx, expr.span, right, left, "", 1); // 1 > len
106                 },
107                 BinOpKind::Lt => {
108                     check_cmp(cx, expr.span, left, right, "", 1); // len < 1
109                     check_cmp(cx, expr.span, right, left, "!", 0); // 0 < len
110                 },
111                 BinOpKind::Ge => check_cmp(cx, expr.span, left, right, "!", 1), // len >= 1
112                 BinOpKind::Le => check_cmp(cx, expr.span, right, left, "!", 1), // 1 <= len
113                 _ => (),
114             }
115         }
116     }
117 }
118
119 fn check_trait_items(cx: &LateContext<'_, '_>, visited_trait: &Item, trait_items: &[TraitItemRef]) {
120     fn is_named_self(cx: &LateContext<'_, '_>, item: &TraitItemRef, name: &str) -> bool {
121         item.ident.name.as_str() == name
122             && if let AssocItemKind::Method { has_self } = item.kind {
123                 has_self && {
124                     let did = cx.tcx.hir().local_def_id(item.id.hir_id);
125                     cx.tcx.fn_sig(did).inputs().skip_binder().len() == 1
126                 }
127             } else {
128                 false
129             }
130     }
131
132     // fill the set with current and super traits
133     fn fill_trait_set(traitt: DefId, set: &mut FxHashSet<DefId>, cx: &LateContext<'_, '_>) {
134         if set.insert(traitt) {
135             for supertrait in rustc::traits::supertrait_def_ids(cx.tcx, traitt) {
136                 fill_trait_set(supertrait, set, cx);
137             }
138         }
139     }
140
141     if cx.access_levels.is_exported(visited_trait.hir_id) && trait_items.iter().any(|i| is_named_self(cx, i, "len")) {
142         let mut current_and_super_traits = FxHashSet::default();
143         let visited_trait_def_id = cx.tcx.hir().local_def_id(visited_trait.hir_id);
144         fill_trait_set(visited_trait_def_id, &mut current_and_super_traits, cx);
145
146         let is_empty_method_found = current_and_super_traits
147             .iter()
148             .flat_map(|&i| cx.tcx.associated_items(i))
149             .any(|i| {
150                 i.kind == ty::AssocKind::Method
151                     && i.method_has_self_argument
152                     && i.ident.name == sym!(is_empty)
153                     && cx.tcx.fn_sig(i.def_id).inputs().skip_binder().len() == 1
154             });
155
156         if !is_empty_method_found {
157             span_lint(
158                 cx,
159                 LEN_WITHOUT_IS_EMPTY,
160                 visited_trait.span,
161                 &format!(
162                     "trait `{}` has a `len` method but no (possibly inherited) `is_empty` method",
163                     visited_trait.ident.name
164                 ),
165             );
166         }
167     }
168 }
169
170 fn check_impl_items(cx: &LateContext<'_, '_>, item: &Item, impl_items: &[ImplItemRef]) {
171     fn is_named_self(cx: &LateContext<'_, '_>, item: &ImplItemRef, name: &str) -> bool {
172         item.ident.name.as_str() == name
173             && if let AssocItemKind::Method { has_self } = item.kind {
174                 has_self && {
175                     let did = cx.tcx.hir().local_def_id(item.id.hir_id);
176                     cx.tcx.fn_sig(did).inputs().skip_binder().len() == 1
177                 }
178             } else {
179                 false
180             }
181     }
182
183     let is_empty = if let Some(is_empty) = impl_items.iter().find(|i| is_named_self(cx, i, "is_empty")) {
184         if cx.access_levels.is_exported(is_empty.id.hir_id) {
185             return;
186         } else {
187             "a private"
188         }
189     } else {
190         "no corresponding"
191     };
192
193     if let Some(i) = impl_items.iter().find(|i| is_named_self(cx, i, "len")) {
194         if cx.access_levels.is_exported(i.id.hir_id) {
195             let def_id = cx.tcx.hir().local_def_id(item.hir_id);
196             let ty = cx.tcx.type_of(def_id);
197
198             span_lint(
199                 cx,
200                 LEN_WITHOUT_IS_EMPTY,
201                 item.span,
202                 &format!(
203                     "item `{}` has a public `len` method but {} `is_empty` method",
204                     ty, is_empty
205                 ),
206             );
207         }
208     }
209 }
210
211 fn check_cmp(cx: &LateContext<'_, '_>, span: Span, method: &Expr, lit: &Expr, op: &str, compare_to: u32) {
212     if let (&ExprKind::MethodCall(ref method_path, _, ref args), &ExprKind::Lit(ref lit)) = (&method.kind, &lit.kind) {
213         // check if we are in an is_empty() method
214         if let Some(name) = get_item_name(cx, method) {
215             if name.as_str() == "is_empty" {
216                 return;
217             }
218         }
219
220         check_len(cx, span, method_path.ident.name, args, &lit.node, op, compare_to)
221     }
222 }
223
224 fn check_len(
225     cx: &LateContext<'_, '_>,
226     span: Span,
227     method_name: Name,
228     args: &[Expr],
229     lit: &LitKind,
230     op: &str,
231     compare_to: u32,
232 ) {
233     if let LitKind::Int(lit, _) = *lit {
234         // check if length is compared to the specified number
235         if lit != u128::from(compare_to) {
236             return;
237         }
238
239         if method_name.as_str() == "len" && args.len() == 1 && has_is_empty(cx, &args[0]) {
240             let mut applicability = Applicability::MachineApplicable;
241             span_lint_and_sugg(
242                 cx,
243                 LEN_ZERO,
244                 span,
245                 &format!("length comparison to {}", if compare_to == 0 { "zero" } else { "one" }),
246                 &format!("using `{}is_empty` is clearer and more explicit", op),
247                 format!(
248                     "{}{}.is_empty()",
249                     op,
250                     snippet_with_applicability(cx, args[0].span, "_", &mut applicability)
251                 ),
252                 applicability,
253             );
254         }
255     }
256 }
257
258 /// Checks if this type has an `is_empty` method.
259 fn has_is_empty(cx: &LateContext<'_, '_>, expr: &Expr) -> bool {
260     /// Gets an `AssocItem` and return true if it matches `is_empty(self)`.
261     fn is_is_empty(cx: &LateContext<'_, '_>, item: &ty::AssocItem) -> bool {
262         if let ty::AssocKind::Method = item.kind {
263             if item.ident.name.as_str() == "is_empty" {
264                 let sig = cx.tcx.fn_sig(item.def_id);
265                 let ty = sig.skip_binder();
266                 ty.inputs().len() == 1
267             } else {
268                 false
269             }
270         } else {
271             false
272         }
273     }
274
275     /// Checks the inherent impl's items for an `is_empty(self)` method.
276     fn has_is_empty_impl(cx: &LateContext<'_, '_>, id: DefId) -> bool {
277         cx.tcx
278             .inherent_impls(id)
279             .iter()
280             .any(|imp| cx.tcx.associated_items(*imp).any(|item| is_is_empty(cx, &item)))
281     }
282
283     let ty = &walk_ptrs_ty(cx.tables.expr_ty(expr));
284     match ty.kind {
285         ty::Dynamic(ref tt, ..) => {
286             if let Some(principal) = tt.principal() {
287                 cx.tcx
288                     .associated_items(principal.def_id())
289                     .any(|item| is_is_empty(cx, &item))
290             } else {
291                 false
292             }
293         },
294         ty::Projection(ref proj) => has_is_empty_impl(cx, proj.item_def_id),
295         ty::Adt(id, _) => has_is_empty_impl(cx, id.did),
296         ty::Array(..) | ty::Slice(..) | ty::Str => true,
297         _ => false,
298     }
299 }