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