]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/len_zero.rs
Auto merge of #81993 - flip1995:clippyup, r=Manishearth
[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, Impl, 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(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 && { cx.tcx.fn_sig(item.id.def_id).inputs().skip_binder().len() == 1 }
163             } else {
164                 false
165             }
166     }
167
168     // fill the set with current and super traits
169     fn fill_trait_set(traitt: DefId, set: &mut FxHashSet<DefId>, cx: &LateContext<'_>) {
170         if set.insert(traitt) {
171             for supertrait in rustc_trait_selection::traits::supertrait_def_ids(cx.tcx, traitt) {
172                 fill_trait_set(supertrait, set, cx);
173             }
174         }
175     }
176
177     if cx.access_levels.is_exported(visited_trait.hir_id()) && trait_items.iter().any(|i| is_named_self(cx, i, "len")) {
178         let mut current_and_super_traits = FxHashSet::default();
179         fill_trait_set(visited_trait.def_id.to_def_id(), &mut current_and_super_traits, cx);
180
181         let is_empty_method_found = current_and_super_traits
182             .iter()
183             .flat_map(|&i| cx.tcx.associated_items(i).in_definition_order())
184             .any(|i| {
185                 i.kind == ty::AssocKind::Fn
186                     && i.fn_has_self_parameter
187                     && i.ident.name == sym!(is_empty)
188                     && cx.tcx.fn_sig(i.def_id).inputs().skip_binder().len() == 1
189             });
190
191         if !is_empty_method_found {
192             span_lint(
193                 cx,
194                 LEN_WITHOUT_IS_EMPTY,
195                 visited_trait.span,
196                 &format!(
197                     "trait `{}` has a `len` method but no (possibly inherited) `is_empty` method",
198                     visited_trait.ident.name
199                 ),
200             );
201         }
202     }
203 }
204
205 fn check_impl_items(cx: &LateContext<'_>, item: &Item<'_>, impl_items: &[ImplItemRef<'_>]) {
206     fn is_named_self(cx: &LateContext<'_>, item: &ImplItemRef<'_>, name: &str) -> bool {
207         item.ident.name.as_str() == name
208             && if let AssocItemKind::Fn { has_self } = item.kind {
209                 has_self && cx.tcx.fn_sig(item.id.def_id).inputs().skip_binder().len() == 1
210             } else {
211                 false
212             }
213     }
214
215     let is_empty = if let Some(is_empty) = impl_items.iter().find(|i| is_named_self(cx, i, "is_empty")) {
216         if cx.access_levels.is_exported(is_empty.id.hir_id()) {
217             return;
218         }
219         "a private"
220     } else {
221         "no corresponding"
222     };
223
224     if let Some(i) = impl_items.iter().find(|i| is_named_self(cx, i, "len")) {
225         if cx.access_levels.is_exported(i.id.hir_id()) {
226             let ty = cx.tcx.type_of(item.def_id);
227
228             span_lint(
229                 cx,
230                 LEN_WITHOUT_IS_EMPTY,
231                 item.span,
232                 &format!(
233                     "item `{}` has a public `len` method but {} `is_empty` method",
234                     ty, is_empty
235                 ),
236             );
237         }
238     }
239 }
240
241 fn check_cmp(cx: &LateContext<'_>, span: Span, method: &Expr<'_>, lit: &Expr<'_>, op: &str, compare_to: u32) {
242     if let (&ExprKind::MethodCall(ref method_path, _, ref args, _), &ExprKind::Lit(ref lit)) = (&method.kind, &lit.kind)
243     {
244         // check if we are in an is_empty() method
245         if let Some(name) = get_item_name(cx, method) {
246             if name.as_str() == "is_empty" {
247                 return;
248             }
249         }
250
251         check_len(cx, span, method_path.ident.name, args, &lit.node, op, compare_to)
252     } else {
253         check_empty_expr(cx, span, method, lit, op)
254     }
255 }
256
257 fn check_len(
258     cx: &LateContext<'_>,
259     span: Span,
260     method_name: Symbol,
261     args: &[Expr<'_>],
262     lit: &LitKind,
263     op: &str,
264     compare_to: u32,
265 ) {
266     if let LitKind::Int(lit, _) = *lit {
267         // check if length is compared to the specified number
268         if lit != u128::from(compare_to) {
269             return;
270         }
271
272         if method_name.as_str() == "len" && args.len() == 1 && has_is_empty(cx, &args[0]) {
273             let mut applicability = Applicability::MachineApplicable;
274             span_lint_and_sugg(
275                 cx,
276                 LEN_ZERO,
277                 span,
278                 &format!("length comparison to {}", if compare_to == 0 { "zero" } else { "one" }),
279                 &format!("using `{}is_empty` is clearer and more explicit", op),
280                 format!(
281                     "{}{}.is_empty()",
282                     op,
283                     snippet_with_applicability(cx, args[0].span, "_", &mut applicability)
284                 ),
285                 applicability,
286             );
287         }
288     }
289 }
290
291 fn check_empty_expr(cx: &LateContext<'_>, span: Span, lit1: &Expr<'_>, lit2: &Expr<'_>, op: &str) {
292     if (is_empty_array(lit2) || is_empty_string(lit2)) && has_is_empty(cx, lit1) {
293         let mut applicability = Applicability::MachineApplicable;
294         span_lint_and_sugg(
295             cx,
296             COMPARISON_TO_EMPTY,
297             span,
298             "comparison to empty slice",
299             &format!("using `{}is_empty` is clearer and more explicit", op),
300             format!(
301                 "{}{}.is_empty()",
302                 op,
303                 snippet_with_applicability(cx, lit1.span, "_", &mut applicability)
304             ),
305             applicability,
306         );
307     }
308 }
309
310 fn is_empty_string(expr: &Expr<'_>) -> bool {
311     if let ExprKind::Lit(ref lit) = expr.kind {
312         if let LitKind::Str(lit, _) = lit.node {
313             let lit = lit.as_str();
314             return lit == "";
315         }
316     }
317     false
318 }
319
320 fn is_empty_array(expr: &Expr<'_>) -> bool {
321     if let ExprKind::Array(ref arr) = expr.kind {
322         return arr.is_empty();
323     }
324     false
325 }
326
327 /// Checks if this type has an `is_empty` method.
328 fn has_is_empty(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
329     /// Gets an `AssocItem` and return true if it matches `is_empty(self)`.
330     fn is_is_empty(cx: &LateContext<'_>, item: &ty::AssocItem) -> bool {
331         if let ty::AssocKind::Fn = item.kind {
332             if item.ident.name.as_str() == "is_empty" {
333                 let sig = cx.tcx.fn_sig(item.def_id);
334                 let ty = sig.skip_binder();
335                 ty.inputs().len() == 1
336             } else {
337                 false
338             }
339         } else {
340             false
341         }
342     }
343
344     /// Checks the inherent impl's items for an `is_empty(self)` method.
345     fn has_is_empty_impl(cx: &LateContext<'_>, id: DefId) -> bool {
346         cx.tcx.inherent_impls(id).iter().any(|imp| {
347             cx.tcx
348                 .associated_items(*imp)
349                 .in_definition_order()
350                 .any(|item| is_is_empty(cx, &item))
351         })
352     }
353
354     let ty = &cx.typeck_results().expr_ty(expr).peel_refs();
355     match ty.kind() {
356         ty::Dynamic(ref tt, ..) => tt.principal().map_or(false, |principal| {
357             cx.tcx
358                 .associated_items(principal.def_id())
359                 .in_definition_order()
360                 .any(|item| is_is_empty(cx, &item))
361         }),
362         ty::Projection(ref proj) => has_is_empty_impl(cx, proj.item_def_id),
363         ty::Adt(id, _) => has_is_empty_impl(cx, id.did),
364         ty::Array(..) | ty::Slice(..) | ty::Str => true,
365         _ => false,
366     }
367 }