]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/len_zero.rs
Remove empty lines in doc comment
[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         } else {
226             "a private"
227         }
228     } else {
229         "no corresponding"
230     };
231
232     if let Some(i) = impl_items.iter().find(|i| is_named_self(cx, i, "len")) {
233         if cx.access_levels.is_exported(i.id.hir_id) {
234             let def_id = cx.tcx.hir().local_def_id(item.hir_id);
235             let ty = cx.tcx.type_of(def_id);
236
237             span_lint(
238                 cx,
239                 LEN_WITHOUT_IS_EMPTY,
240                 item.span,
241                 &format!(
242                     "item `{}` has a public `len` method but {} `is_empty` method",
243                     ty, is_empty
244                 ),
245             );
246         }
247     }
248 }
249
250 fn check_cmp(cx: &LateContext<'_>, span: Span, method: &Expr<'_>, lit: &Expr<'_>, op: &str, compare_to: u32) {
251     if let (&ExprKind::MethodCall(ref method_path, _, ref args, _), &ExprKind::Lit(ref lit)) = (&method.kind, &lit.kind)
252     {
253         // check if we are in an is_empty() method
254         if let Some(name) = get_item_name(cx, method) {
255             if name.as_str() == "is_empty" {
256                 return;
257             }
258         }
259
260         check_len(cx, span, method_path.ident.name, args, &lit.node, op, compare_to)
261     } else {
262         check_empty_expr(cx, span, method, lit, op)
263     }
264 }
265
266 fn check_len(
267     cx: &LateContext<'_>,
268     span: Span,
269     method_name: Symbol,
270     args: &[Expr<'_>],
271     lit: &LitKind,
272     op: &str,
273     compare_to: u32,
274 ) {
275     if let LitKind::Int(lit, _) = *lit {
276         // check if length is compared to the specified number
277         if lit != u128::from(compare_to) {
278             return;
279         }
280
281         if method_name.as_str() == "len" && args.len() == 1 && has_is_empty(cx, &args[0]) {
282             let mut applicability = Applicability::MachineApplicable;
283             span_lint_and_sugg(
284                 cx,
285                 LEN_ZERO,
286                 span,
287                 &format!("length comparison to {}", if compare_to == 0 { "zero" } else { "one" }),
288                 &format!("using `{}is_empty` is clearer and more explicit", op),
289                 format!(
290                     "{}{}.is_empty()",
291                     op,
292                     snippet_with_applicability(cx, args[0].span, "_", &mut applicability)
293                 ),
294                 applicability,
295             );
296         }
297     }
298 }
299
300 fn check_empty_expr(cx: &LateContext<'_>, span: Span, lit1: &Expr<'_>, lit2: &Expr<'_>, op: &str) {
301     if (is_empty_array(lit2) || is_empty_string(lit2)) && has_is_empty(cx, lit1) {
302         let mut applicability = Applicability::MachineApplicable;
303         span_lint_and_sugg(
304             cx,
305             COMPARISON_TO_EMPTY,
306             span,
307             "comparison to empty slice",
308             &format!("using `{}is_empty` is clearer and more explicit", op),
309             format!(
310                 "{}{}.is_empty()",
311                 op,
312                 snippet_with_applicability(cx, lit1.span, "_", &mut applicability)
313             ),
314             applicability,
315         );
316     }
317 }
318
319 fn is_empty_string(expr: &Expr<'_>) -> bool {
320     if let ExprKind::Lit(ref lit) = expr.kind {
321         if let LitKind::Str(lit, _) = lit.node {
322             let lit = lit.as_str();
323             return lit == "";
324         }
325     }
326     false
327 }
328
329 fn is_empty_array(expr: &Expr<'_>) -> bool {
330     if let ExprKind::Array(ref arr) = expr.kind {
331         return arr.is_empty();
332     }
333     false
334 }
335
336 /// Checks if this type has an `is_empty` method.
337 fn has_is_empty(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
338     /// Gets an `AssocItem` and return true if it matches `is_empty(self)`.
339     fn is_is_empty(cx: &LateContext<'_>, item: &ty::AssocItem) -> bool {
340         if let ty::AssocKind::Fn = item.kind {
341             if item.ident.name.as_str() == "is_empty" {
342                 let sig = cx.tcx.fn_sig(item.def_id);
343                 let ty = sig.skip_binder();
344                 ty.inputs().len() == 1
345             } else {
346                 false
347             }
348         } else {
349             false
350         }
351     }
352
353     /// Checks the inherent impl's items for an `is_empty(self)` method.
354     fn has_is_empty_impl(cx: &LateContext<'_>, id: DefId) -> bool {
355         cx.tcx.inherent_impls(id).iter().any(|imp| {
356             cx.tcx
357                 .associated_items(*imp)
358                 .in_definition_order()
359                 .any(|item| is_is_empty(cx, &item))
360         })
361     }
362
363     let ty = &cx.typeck_results().expr_ty(expr).peel_refs();
364     match ty.kind() {
365         ty::Dynamic(ref tt, ..) => tt.principal().map_or(false, |principal| {
366             cx.tcx
367                 .associated_items(principal.def_id())
368                 .in_definition_order()
369                 .any(|item| is_is_empty(cx, &item))
370         }),
371         ty::Projection(ref proj) => has_is_empty_impl(cx, proj.item_def_id),
372         ty::Adt(id, _) => has_is_empty_impl(cx, id.did),
373         ty::Array(..) | ty::Slice(..) | ty::Str => true,
374         _ => false,
375     }
376 }