]>
Commit | Line | Data |
---|---|---|
cdc7bbd5 XL |
1 | use clippy_utils::diagnostics::{span_lint, span_lint_and_sugg, span_lint_and_then}; |
2 | use clippy_utils::source::snippet_with_applicability; | |
3 | use clippy_utils::{get_item_name, get_parent_as_impl, is_allowed}; | |
f20569fa XL |
4 | use if_chain::if_chain; |
5 | use rustc_ast::ast::LitKind; | |
f20569fa | 6 | use rustc_errors::Applicability; |
cdc7bbd5 | 7 | use rustc_hir::def_id::DefIdSet; |
f20569fa XL |
8 | use rustc_hir::{ |
9 | def_id::DefId, AssocItemKind, BinOpKind, Expr, ExprKind, FnRetTy, ImplItem, ImplItemKind, ImplicitSelfKind, Item, | |
10 | ItemKind, Mutability, Node, TraitItemRef, TyKind, | |
11 | }; | |
12 | use rustc_lint::{LateContext, LateLintPass}; | |
cdc7bbd5 | 13 | use rustc_middle::ty::{self, AssocKind, FnSig, Ty, TyS}; |
f20569fa | 14 | use rustc_session::{declare_lint_pass, declare_tool_lint}; |
cdc7bbd5 XL |
15 | use rustc_span::{ |
16 | source_map::{Span, Spanned, Symbol}, | |
17 | symbol::sym, | |
18 | }; | |
f20569fa XL |
19 | |
20 | declare_clippy_lint! { | |
21 | /// **What it does:** Checks for getting the length of something via `.len()` | |
22 | /// just to compare to zero, and suggests using `.is_empty()` where applicable. | |
23 | /// | |
24 | /// **Why is this bad?** Some structures can answer `.is_empty()` much faster | |
25 | /// than calculating their length. So it is good to get into the habit of using | |
26 | /// `.is_empty()`, and having it is cheap. | |
27 | /// Besides, it makes the intent clearer than a manual comparison in some contexts. | |
28 | /// | |
29 | /// **Known problems:** None. | |
30 | /// | |
31 | /// **Example:** | |
32 | /// ```ignore | |
33 | /// if x.len() == 0 { | |
34 | /// .. | |
35 | /// } | |
36 | /// if y.len() != 0 { | |
37 | /// .. | |
38 | /// } | |
39 | /// ``` | |
40 | /// instead use | |
41 | /// ```ignore | |
42 | /// if x.is_empty() { | |
43 | /// .. | |
44 | /// } | |
45 | /// if !y.is_empty() { | |
46 | /// .. | |
47 | /// } | |
48 | /// ``` | |
49 | pub LEN_ZERO, | |
50 | style, | |
51 | "checking `.len() == 0` or `.len() > 0` (or similar) when `.is_empty()` could be used instead" | |
52 | } | |
53 | ||
54 | declare_clippy_lint! { | |
55 | /// **What it does:** Checks for items that implement `.len()` but not | |
56 | /// `.is_empty()`. | |
57 | /// | |
58 | /// **Why is this bad?** It is good custom to have both methods, because for | |
59 | /// some data structures, asking about the length will be a costly operation, | |
60 | /// whereas `.is_empty()` can usually answer in constant time. Also it used to | |
61 | /// lead to false positives on the [`len_zero`](#len_zero) lint – currently that | |
62 | /// lint will ignore such entities. | |
63 | /// | |
64 | /// **Known problems:** None. | |
65 | /// | |
66 | /// **Example:** | |
67 | /// ```ignore | |
68 | /// impl X { | |
69 | /// pub fn len(&self) -> usize { | |
70 | /// .. | |
71 | /// } | |
72 | /// } | |
73 | /// ``` | |
74 | pub LEN_WITHOUT_IS_EMPTY, | |
75 | style, | |
76 | "traits or impls with a public `len` method but no corresponding `is_empty` method" | |
77 | } | |
78 | ||
79 | declare_clippy_lint! { | |
80 | /// **What it does:** Checks for comparing to an empty slice such as `""` or `[]`, | |
81 | /// and suggests using `.is_empty()` where applicable. | |
82 | /// | |
83 | /// **Why is this bad?** Some structures can answer `.is_empty()` much faster | |
84 | /// than checking for equality. So it is good to get into the habit of using | |
85 | /// `.is_empty()`, and having it is cheap. | |
86 | /// Besides, it makes the intent clearer than a manual comparison in some contexts. | |
87 | /// | |
88 | /// **Known problems:** None. | |
89 | /// | |
90 | /// **Example:** | |
91 | /// | |
92 | /// ```ignore | |
93 | /// if s == "" { | |
94 | /// .. | |
95 | /// } | |
96 | /// | |
97 | /// if arr == [] { | |
98 | /// .. | |
99 | /// } | |
100 | /// ``` | |
101 | /// Use instead: | |
102 | /// ```ignore | |
103 | /// if s.is_empty() { | |
104 | /// .. | |
105 | /// } | |
106 | /// | |
107 | /// if arr.is_empty() { | |
108 | /// .. | |
109 | /// } | |
110 | /// ``` | |
111 | pub COMPARISON_TO_EMPTY, | |
112 | style, | |
113 | "checking `x == \"\"` or `x == []` (or similar) when `.is_empty()` could be used instead" | |
114 | } | |
115 | ||
116 | declare_lint_pass!(LenZero => [LEN_ZERO, LEN_WITHOUT_IS_EMPTY, COMPARISON_TO_EMPTY]); | |
117 | ||
118 | impl<'tcx> LateLintPass<'tcx> for LenZero { | |
119 | fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) { | |
120 | if item.span.from_expansion() { | |
121 | return; | |
122 | } | |
123 | ||
cdc7bbd5 | 124 | if let ItemKind::Trait(_, _, _, _, trait_items) = item.kind { |
f20569fa XL |
125 | check_trait_items(cx, item, trait_items); |
126 | } | |
127 | } | |
128 | ||
129 | fn check_impl_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx ImplItem<'_>) { | |
130 | if_chain! { | |
131 | if item.ident.as_str() == "len"; | |
132 | if let ImplItemKind::Fn(sig, _) = &item.kind; | |
133 | if sig.decl.implicit_self.has_implicit_self(); | |
134 | if cx.access_levels.is_exported(item.hir_id()); | |
135 | if matches!(sig.decl.output, FnRetTy::Return(_)); | |
136 | if let Some(imp) = get_parent_as_impl(cx.tcx, item.hir_id()); | |
137 | if imp.of_trait.is_none(); | |
138 | if let TyKind::Path(ty_path) = &imp.self_ty.kind; | |
139 | if let Some(ty_id) = cx.qpath_res(ty_path, imp.self_ty.hir_id).opt_def_id(); | |
140 | if let Some(local_id) = ty_id.as_local(); | |
141 | let ty_hir_id = cx.tcx.hir().local_def_id_to_hir_id(local_id); | |
142 | if !is_allowed(cx, LEN_WITHOUT_IS_EMPTY, ty_hir_id); | |
cdc7bbd5 | 143 | if let Some(output) = parse_len_output(cx, cx.tcx.fn_sig(item.def_id).skip_binder()); |
f20569fa XL |
144 | then { |
145 | let (name, kind) = match cx.tcx.hir().find(ty_hir_id) { | |
146 | Some(Node::ForeignItem(x)) => (x.ident.name, "extern type"), | |
147 | Some(Node::Item(x)) => match x.kind { | |
148 | ItemKind::Struct(..) => (x.ident.name, "struct"), | |
149 | ItemKind::Enum(..) => (x.ident.name, "enum"), | |
150 | ItemKind::Union(..) => (x.ident.name, "union"), | |
151 | _ => (x.ident.name, "type"), | |
152 | } | |
153 | _ => return, | |
154 | }; | |
cdc7bbd5 | 155 | check_for_is_empty(cx, sig.span, sig.decl.implicit_self, output, ty_id, name, kind) |
f20569fa XL |
156 | } |
157 | } | |
158 | } | |
159 | ||
160 | fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) { | |
161 | if expr.span.from_expansion() { | |
162 | return; | |
163 | } | |
164 | ||
cdc7bbd5 | 165 | if let ExprKind::Binary(Spanned { node: cmp, .. }, left, right) = expr.kind { |
f20569fa XL |
166 | match cmp { |
167 | BinOpKind::Eq => { | |
168 | check_cmp(cx, expr.span, left, right, "", 0); // len == 0 | |
169 | check_cmp(cx, expr.span, right, left, "", 0); // 0 == len | |
170 | }, | |
171 | BinOpKind::Ne => { | |
172 | check_cmp(cx, expr.span, left, right, "!", 0); // len != 0 | |
173 | check_cmp(cx, expr.span, right, left, "!", 0); // 0 != len | |
174 | }, | |
175 | BinOpKind::Gt => { | |
176 | check_cmp(cx, expr.span, left, right, "!", 0); // len > 0 | |
177 | check_cmp(cx, expr.span, right, left, "", 1); // 1 > len | |
178 | }, | |
179 | BinOpKind::Lt => { | |
180 | check_cmp(cx, expr.span, left, right, "", 1); // len < 1 | |
181 | check_cmp(cx, expr.span, right, left, "!", 0); // 0 < len | |
182 | }, | |
183 | BinOpKind::Ge => check_cmp(cx, expr.span, left, right, "!", 1), // len >= 1 | |
184 | BinOpKind::Le => check_cmp(cx, expr.span, right, left, "!", 1), // 1 <= len | |
185 | _ => (), | |
186 | } | |
187 | } | |
188 | } | |
189 | } | |
190 | ||
191 | fn check_trait_items(cx: &LateContext<'_>, visited_trait: &Item<'_>, trait_items: &[TraitItemRef]) { | |
192 | fn is_named_self(cx: &LateContext<'_>, item: &TraitItemRef, name: &str) -> bool { | |
193 | item.ident.name.as_str() == name | |
194 | && if let AssocItemKind::Fn { has_self } = item.kind { | |
195 | has_self && { cx.tcx.fn_sig(item.id.def_id).inputs().skip_binder().len() == 1 } | |
196 | } else { | |
197 | false | |
198 | } | |
199 | } | |
200 | ||
201 | // fill the set with current and super traits | |
cdc7bbd5 | 202 | fn fill_trait_set(traitt: DefId, set: &mut DefIdSet, cx: &LateContext<'_>) { |
f20569fa XL |
203 | if set.insert(traitt) { |
204 | for supertrait in rustc_trait_selection::traits::supertrait_def_ids(cx.tcx, traitt) { | |
205 | fill_trait_set(supertrait, set, cx); | |
206 | } | |
207 | } | |
208 | } | |
209 | ||
210 | if cx.access_levels.is_exported(visited_trait.hir_id()) && trait_items.iter().any(|i| is_named_self(cx, i, "len")) { | |
cdc7bbd5 | 211 | let mut current_and_super_traits = DefIdSet::default(); |
f20569fa XL |
212 | fill_trait_set(visited_trait.def_id.to_def_id(), &mut current_and_super_traits, cx); |
213 | ||
214 | let is_empty_method_found = current_and_super_traits | |
215 | .iter() | |
216 | .flat_map(|&i| cx.tcx.associated_items(i).in_definition_order()) | |
217 | .any(|i| { | |
218 | i.kind == ty::AssocKind::Fn | |
219 | && i.fn_has_self_parameter | |
220 | && i.ident.name == sym!(is_empty) | |
221 | && cx.tcx.fn_sig(i.def_id).inputs().skip_binder().len() == 1 | |
222 | }); | |
223 | ||
224 | if !is_empty_method_found { | |
225 | span_lint( | |
226 | cx, | |
227 | LEN_WITHOUT_IS_EMPTY, | |
228 | visited_trait.span, | |
229 | &format!( | |
230 | "trait `{}` has a `len` method but no (possibly inherited) `is_empty` method", | |
231 | visited_trait.ident.name | |
232 | ), | |
233 | ); | |
234 | } | |
235 | } | |
236 | } | |
237 | ||
cdc7bbd5 XL |
238 | #[derive(Debug, Clone, Copy)] |
239 | enum LenOutput<'tcx> { | |
240 | Integral, | |
241 | Option(DefId), | |
242 | Result(DefId, Ty<'tcx>), | |
243 | } | |
244 | fn parse_len_output(cx: &LateContext<'_>, sig: FnSig<'tcx>) -> Option<LenOutput<'tcx>> { | |
245 | match *sig.output().kind() { | |
246 | ty::Int(_) | ty::Uint(_) => Some(LenOutput::Integral), | |
247 | ty::Adt(adt, subs) if cx.tcx.is_diagnostic_item(sym::option_type, adt.did) => { | |
248 | subs.type_at(0).is_integral().then(|| LenOutput::Option(adt.did)) | |
249 | }, | |
250 | ty::Adt(adt, subs) if cx.tcx.is_diagnostic_item(sym::result_type, adt.did) => subs | |
251 | .type_at(0) | |
252 | .is_integral() | |
253 | .then(|| LenOutput::Result(adt.did, subs.type_at(1))), | |
254 | _ => None, | |
255 | } | |
256 | } | |
257 | ||
258 | impl LenOutput<'_> { | |
259 | fn matches_is_empty_output(self, ty: Ty<'_>) -> bool { | |
260 | match (self, ty.kind()) { | |
261 | (_, &ty::Bool) => true, | |
262 | (Self::Option(id), &ty::Adt(adt, subs)) if id == adt.did => subs.type_at(0).is_bool(), | |
263 | (Self::Result(id, err_ty), &ty::Adt(adt, subs)) if id == adt.did => { | |
264 | subs.type_at(0).is_bool() && TyS::same_type(subs.type_at(1), err_ty) | |
265 | }, | |
266 | _ => false, | |
267 | } | |
268 | } | |
269 | ||
270 | fn expected_sig(self, self_kind: ImplicitSelfKind) -> String { | |
271 | let self_ref = match self_kind { | |
272 | ImplicitSelfKind::ImmRef => "&", | |
273 | ImplicitSelfKind::MutRef => "&mut ", | |
274 | _ => "", | |
275 | }; | |
276 | match self { | |
277 | Self::Integral => format!("expected signature: `({}self) -> bool`", self_ref), | |
278 | Self::Option(_) => format!( | |
279 | "expected signature: `({}self) -> bool` or `({}self) -> Option<bool>", | |
280 | self_ref, self_ref | |
281 | ), | |
282 | Self::Result(..) => format!( | |
283 | "expected signature: `({}self) -> bool` or `({}self) -> Result<bool>", | |
284 | self_ref, self_ref | |
285 | ), | |
286 | } | |
287 | } | |
288 | } | |
289 | ||
f20569fa | 290 | /// Checks if the given signature matches the expectations for `is_empty` |
cdc7bbd5 | 291 | fn check_is_empty_sig(sig: FnSig<'_>, self_kind: ImplicitSelfKind, len_output: LenOutput<'_>) -> bool { |
f20569fa | 292 | match &**sig.inputs_and_output { |
cdc7bbd5 | 293 | [arg, res] if len_output.matches_is_empty_output(res) => { |
f20569fa XL |
294 | matches!( |
295 | (arg.kind(), self_kind), | |
296 | (ty::Ref(_, _, Mutability::Not), ImplicitSelfKind::ImmRef) | |
297 | | (ty::Ref(_, _, Mutability::Mut), ImplicitSelfKind::MutRef) | |
298 | ) || (!arg.is_ref() && matches!(self_kind, ImplicitSelfKind::Imm | ImplicitSelfKind::Mut)) | |
299 | }, | |
300 | _ => false, | |
301 | } | |
302 | } | |
303 | ||
304 | /// Checks if the given type has an `is_empty` method with the appropriate signature. | |
305 | fn check_for_is_empty( | |
306 | cx: &LateContext<'_>, | |
307 | span: Span, | |
308 | self_kind: ImplicitSelfKind, | |
cdc7bbd5 | 309 | output: LenOutput<'_>, |
f20569fa XL |
310 | impl_ty: DefId, |
311 | item_name: Symbol, | |
312 | item_kind: &str, | |
313 | ) { | |
314 | let is_empty = Symbol::intern("is_empty"); | |
315 | let is_empty = cx | |
316 | .tcx | |
317 | .inherent_impls(impl_ty) | |
318 | .iter() | |
319 | .flat_map(|&id| cx.tcx.associated_items(id).filter_by_name_unhygienic(is_empty)) | |
320 | .find(|item| item.kind == AssocKind::Fn); | |
321 | ||
322 | let (msg, is_empty_span, self_kind) = match is_empty { | |
323 | None => ( | |
324 | format!( | |
325 | "{} `{}` has a public `len` method, but no `is_empty` method", | |
326 | item_kind, | |
327 | item_name.as_str(), | |
328 | ), | |
329 | None, | |
330 | None, | |
331 | ), | |
332 | Some(is_empty) | |
333 | if !cx | |
334 | .access_levels | |
335 | .is_exported(cx.tcx.hir().local_def_id_to_hir_id(is_empty.def_id.expect_local())) => | |
336 | { | |
337 | ( | |
338 | format!( | |
339 | "{} `{}` has a public `len` method, but a private `is_empty` method", | |
340 | item_kind, | |
341 | item_name.as_str(), | |
342 | ), | |
343 | Some(cx.tcx.def_span(is_empty.def_id)), | |
344 | None, | |
345 | ) | |
346 | }, | |
347 | Some(is_empty) | |
348 | if !(is_empty.fn_has_self_parameter | |
cdc7bbd5 | 349 | && check_is_empty_sig(cx.tcx.fn_sig(is_empty.def_id).skip_binder(), self_kind, output)) => |
f20569fa XL |
350 | { |
351 | ( | |
352 | format!( | |
353 | "{} `{}` has a public `len` method, but the `is_empty` method has an unexpected signature", | |
354 | item_kind, | |
355 | item_name.as_str(), | |
356 | ), | |
357 | Some(cx.tcx.def_span(is_empty.def_id)), | |
358 | Some(self_kind), | |
359 | ) | |
360 | }, | |
361 | Some(_) => return, | |
362 | }; | |
363 | ||
364 | span_lint_and_then(cx, LEN_WITHOUT_IS_EMPTY, span, &msg, |db| { | |
365 | if let Some(span) = is_empty_span { | |
366 | db.span_note(span, "`is_empty` defined here"); | |
367 | } | |
368 | if let Some(self_kind) = self_kind { | |
cdc7bbd5 | 369 | db.note(&output.expected_sig(self_kind)); |
f20569fa XL |
370 | } |
371 | }); | |
372 | } | |
373 | ||
374 | fn check_cmp(cx: &LateContext<'_>, span: Span, method: &Expr<'_>, lit: &Expr<'_>, op: &str, compare_to: u32) { | |
cdc7bbd5 | 375 | if let (&ExprKind::MethodCall(method_path, _, args, _), &ExprKind::Lit(ref lit)) = (&method.kind, &lit.kind) { |
f20569fa XL |
376 | // check if we are in an is_empty() method |
377 | if let Some(name) = get_item_name(cx, method) { | |
378 | if name.as_str() == "is_empty" { | |
379 | return; | |
380 | } | |
381 | } | |
382 | ||
383 | check_len(cx, span, method_path.ident.name, args, &lit.node, op, compare_to) | |
384 | } else { | |
385 | check_empty_expr(cx, span, method, lit, op) | |
386 | } | |
387 | } | |
388 | ||
389 | fn check_len( | |
390 | cx: &LateContext<'_>, | |
391 | span: Span, | |
392 | method_name: Symbol, | |
393 | args: &[Expr<'_>], | |
394 | lit: &LitKind, | |
395 | op: &str, | |
396 | compare_to: u32, | |
397 | ) { | |
398 | if let LitKind::Int(lit, _) = *lit { | |
399 | // check if length is compared to the specified number | |
400 | if lit != u128::from(compare_to) { | |
401 | return; | |
402 | } | |
403 | ||
404 | if method_name.as_str() == "len" && args.len() == 1 && has_is_empty(cx, &args[0]) { | |
405 | let mut applicability = Applicability::MachineApplicable; | |
406 | span_lint_and_sugg( | |
407 | cx, | |
408 | LEN_ZERO, | |
409 | span, | |
410 | &format!("length comparison to {}", if compare_to == 0 { "zero" } else { "one" }), | |
411 | &format!("using `{}is_empty` is clearer and more explicit", op), | |
412 | format!( | |
413 | "{}{}.is_empty()", | |
414 | op, | |
415 | snippet_with_applicability(cx, args[0].span, "_", &mut applicability) | |
416 | ), | |
417 | applicability, | |
418 | ); | |
419 | } | |
420 | } | |
421 | } | |
422 | ||
423 | fn check_empty_expr(cx: &LateContext<'_>, span: Span, lit1: &Expr<'_>, lit2: &Expr<'_>, op: &str) { | |
424 | if (is_empty_array(lit2) || is_empty_string(lit2)) && has_is_empty(cx, lit1) { | |
425 | let mut applicability = Applicability::MachineApplicable; | |
426 | span_lint_and_sugg( | |
427 | cx, | |
428 | COMPARISON_TO_EMPTY, | |
429 | span, | |
430 | "comparison to empty slice", | |
431 | &format!("using `{}is_empty` is clearer and more explicit", op), | |
432 | format!( | |
433 | "{}{}.is_empty()", | |
434 | op, | |
435 | snippet_with_applicability(cx, lit1.span, "_", &mut applicability) | |
436 | ), | |
437 | applicability, | |
438 | ); | |
439 | } | |
440 | } | |
441 | ||
442 | fn is_empty_string(expr: &Expr<'_>) -> bool { | |
443 | if let ExprKind::Lit(ref lit) = expr.kind { | |
444 | if let LitKind::Str(lit, _) = lit.node { | |
445 | let lit = lit.as_str(); | |
446 | return lit == ""; | |
447 | } | |
448 | } | |
449 | false | |
450 | } | |
451 | ||
452 | fn is_empty_array(expr: &Expr<'_>) -> bool { | |
cdc7bbd5 | 453 | if let ExprKind::Array(arr) = expr.kind { |
f20569fa XL |
454 | return arr.is_empty(); |
455 | } | |
456 | false | |
457 | } | |
458 | ||
459 | /// Checks if this type has an `is_empty` method. | |
460 | fn has_is_empty(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool { | |
461 | /// Gets an `AssocItem` and return true if it matches `is_empty(self)`. | |
462 | fn is_is_empty(cx: &LateContext<'_>, item: &ty::AssocItem) -> bool { | |
463 | if let ty::AssocKind::Fn = item.kind { | |
464 | if item.ident.name.as_str() == "is_empty" { | |
465 | let sig = cx.tcx.fn_sig(item.def_id); | |
466 | let ty = sig.skip_binder(); | |
467 | ty.inputs().len() == 1 | |
468 | } else { | |
469 | false | |
470 | } | |
471 | } else { | |
472 | false | |
473 | } | |
474 | } | |
475 | ||
476 | /// Checks the inherent impl's items for an `is_empty(self)` method. | |
477 | fn has_is_empty_impl(cx: &LateContext<'_>, id: DefId) -> bool { | |
478 | cx.tcx.inherent_impls(id).iter().any(|imp| { | |
479 | cx.tcx | |
480 | .associated_items(*imp) | |
481 | .in_definition_order() | |
cdc7bbd5 | 482 | .any(|item| is_is_empty(cx, item)) |
f20569fa XL |
483 | }) |
484 | } | |
485 | ||
486 | let ty = &cx.typeck_results().expr_ty(expr).peel_refs(); | |
487 | match ty.kind() { | |
cdc7bbd5 | 488 | ty::Dynamic(tt, ..) => tt.principal().map_or(false, |principal| { |
f20569fa XL |
489 | cx.tcx |
490 | .associated_items(principal.def_id()) | |
491 | .in_definition_order() | |
cdc7bbd5 | 492 | .any(|item| is_is_empty(cx, item)) |
f20569fa XL |
493 | }), |
494 | ty::Projection(ref proj) => has_is_empty_impl(cx, proj.item_def_id), | |
495 | ty::Adt(id, _) => has_is_empty_impl(cx, id.did), | |
496 | ty::Array(..) | ty::Slice(..) | ty::Str => true, | |
497 | _ => false, | |
498 | } | |
499 | } |