]>
Commit | Line | Data |
---|---|---|
cdc7bbd5 | 1 | use clippy_utils::diagnostics::{span_lint, span_lint_and_sugg, span_lint_and_then}; |
e8be2606 FG |
2 | use clippy_utils::source::{snippet_opt, snippet_with_context}; |
3 | use clippy_utils::sugg::{has_enclosing_paren, Sugg}; | |
add651ee | 4 | use clippy_utils::{get_item_name, get_parent_as_impl, is_lint_allowed, peel_ref_operators}; |
f20569fa | 5 | use rustc_ast::ast::LitKind; |
f20569fa | 6 | use rustc_errors::Applicability; |
add651ee FG |
7 | use rustc_hir::def::Res; |
8 | use rustc_hir::def_id::{DefId, DefIdSet}; | |
f20569fa | 9 | use rustc_hir::{ |
add651ee | 10 | AssocItemKind, BinOpKind, Expr, ExprKind, FnRetTy, GenericArg, GenericBound, ImplItem, ImplItemKind, |
c0240ec0 | 11 | ImplicitSelfKind, Item, ItemKind, Mutability, Node, OpaqueTyOrigin, PatKind, PathSegment, PrimTy, QPath, |
31ef2f64 | 12 | TraitItemRef, TyKind, |
f20569fa XL |
13 | }; |
14 | use rustc_lint::{LateContext, LateLintPass}; | |
5099ac24 | 15 | use rustc_middle::ty::{self, AssocKind, FnSig, Ty}; |
4b012472 | 16 | use rustc_session::declare_lint_pass; |
ed00b5ec | 17 | use rustc_span::source_map::Spanned; |
add651ee | 18 | use rustc_span::symbol::sym; |
4b012472 | 19 | use rustc_span::{Span, Symbol}; |
f20569fa XL |
20 | |
21 | declare_clippy_lint! { | |
94222f64 XL |
22 | /// ### What it does |
23 | /// Checks for getting the length of something via `.len()` | |
f20569fa XL |
24 | /// just to compare to zero, and suggests using `.is_empty()` where applicable. |
25 | /// | |
94222f64 XL |
26 | /// ### Why is this bad? |
27 | /// Some structures can answer `.is_empty()` much faster | |
f20569fa XL |
28 | /// than calculating their length. So it is good to get into the habit of using |
29 | /// `.is_empty()`, and having it is cheap. | |
30 | /// Besides, it makes the intent clearer than a manual comparison in some contexts. | |
31 | /// | |
94222f64 | 32 | /// ### Example |
f20569fa XL |
33 | /// ```ignore |
34 | /// if x.len() == 0 { | |
35 | /// .. | |
36 | /// } | |
37 | /// if y.len() != 0 { | |
38 | /// .. | |
39 | /// } | |
40 | /// ``` | |
41 | /// instead use | |
42 | /// ```ignore | |
43 | /// if x.is_empty() { | |
44 | /// .. | |
45 | /// } | |
46 | /// if !y.is_empty() { | |
47 | /// .. | |
48 | /// } | |
49 | /// ``` | |
a2a8927a | 50 | #[clippy::version = "pre 1.29.0"] |
f20569fa XL |
51 | pub LEN_ZERO, |
52 | style, | |
53 | "checking `.len() == 0` or `.len() > 0` (or similar) when `.is_empty()` could be used instead" | |
54 | } | |
55 | ||
56 | declare_clippy_lint! { | |
94222f64 XL |
57 | /// ### What it does |
58 | /// Checks for items that implement `.len()` but not | |
f20569fa XL |
59 | /// `.is_empty()`. |
60 | /// | |
94222f64 XL |
61 | /// ### Why is this bad? |
62 | /// It is good custom to have both methods, because for | |
f20569fa XL |
63 | /// some data structures, asking about the length will be a costly operation, |
64 | /// whereas `.is_empty()` can usually answer in constant time. Also it used to | |
65 | /// lead to false positives on the [`len_zero`](#len_zero) lint – currently that | |
66 | /// lint will ignore such entities. | |
67 | /// | |
94222f64 | 68 | /// ### Example |
f20569fa XL |
69 | /// ```ignore |
70 | /// impl X { | |
71 | /// pub fn len(&self) -> usize { | |
72 | /// .. | |
73 | /// } | |
74 | /// } | |
75 | /// ``` | |
a2a8927a | 76 | #[clippy::version = "pre 1.29.0"] |
f20569fa XL |
77 | pub LEN_WITHOUT_IS_EMPTY, |
78 | style, | |
79 | "traits or impls with a public `len` method but no corresponding `is_empty` method" | |
80 | } | |
81 | ||
82 | declare_clippy_lint! { | |
94222f64 XL |
83 | /// ### What it does |
84 | /// Checks for comparing to an empty slice such as `""` or `[]`, | |
f20569fa XL |
85 | /// and suggests using `.is_empty()` where applicable. |
86 | /// | |
94222f64 XL |
87 | /// ### Why is this bad? |
88 | /// Some structures can answer `.is_empty()` much faster | |
f20569fa XL |
89 | /// than checking for equality. So it is good to get into the habit of using |
90 | /// `.is_empty()`, and having it is cheap. | |
91 | /// Besides, it makes the intent clearer than a manual comparison in some contexts. | |
92 | /// | |
94222f64 | 93 | /// ### Example |
f20569fa XL |
94 | /// |
95 | /// ```ignore | |
96 | /// if s == "" { | |
97 | /// .. | |
98 | /// } | |
99 | /// | |
100 | /// if arr == [] { | |
101 | /// .. | |
102 | /// } | |
103 | /// ``` | |
104 | /// Use instead: | |
105 | /// ```ignore | |
106 | /// if s.is_empty() { | |
107 | /// .. | |
108 | /// } | |
109 | /// | |
110 | /// if arr.is_empty() { | |
111 | /// .. | |
112 | /// } | |
113 | /// ``` | |
a2a8927a | 114 | #[clippy::version = "1.49.0"] |
f20569fa XL |
115 | pub COMPARISON_TO_EMPTY, |
116 | style, | |
117 | "checking `x == \"\"` or `x == []` (or similar) when `.is_empty()` could be used instead" | |
118 | } | |
119 | ||
120 | declare_lint_pass!(LenZero => [LEN_ZERO, LEN_WITHOUT_IS_EMPTY, COMPARISON_TO_EMPTY]); | |
121 | ||
122 | impl<'tcx> LateLintPass<'tcx> for LenZero { | |
123 | fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) { | |
1f0639a9 FG |
124 | if let ItemKind::Trait(_, _, _, _, trait_items) = item.kind |
125 | && !item.span.from_expansion() | |
126 | { | |
f20569fa XL |
127 | check_trait_items(cx, item, trait_items); |
128 | } | |
129 | } | |
130 | ||
131 | fn check_impl_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx ImplItem<'_>) { | |
4b012472 FG |
132 | if item.ident.name == sym::len |
133 | && let ImplItemKind::Fn(sig, _) = &item.kind | |
134 | && sig.decl.implicit_self.has_implicit_self() | |
135 | && sig.decl.inputs.len() == 1 | |
136 | && cx.effective_visibilities.is_exported(item.owner_id.def_id) | |
137 | && matches!(sig.decl.output, FnRetTy::Return(_)) | |
138 | && let Some(imp) = get_parent_as_impl(cx.tcx, item.hir_id()) | |
139 | && imp.of_trait.is_none() | |
140 | && let TyKind::Path(ty_path) = &imp.self_ty.kind | |
141 | && let Some(ty_id) = cx.qpath_res(ty_path, imp.self_ty.hir_id).opt_def_id() | |
142 | && let Some(local_id) = ty_id.as_local() | |
143 | && let ty_hir_id = cx.tcx.local_def_id_to_hir_id(local_id) | |
144 | && !is_lint_allowed(cx, LEN_WITHOUT_IS_EMPTY, ty_hir_id) | |
145 | && let Some(output) = | |
146 | parse_len_output(cx, cx.tcx.fn_sig(item.owner_id).instantiate_identity().skip_binder()) | |
147 | { | |
c620b35d FG |
148 | let (name, kind) = match cx.tcx.hir_node(ty_hir_id) { |
149 | Node::ForeignItem(x) => (x.ident.name, "extern type"), | |
150 | Node::Item(x) => match x.kind { | |
4b012472 FG |
151 | ItemKind::Struct(..) => (x.ident.name, "struct"), |
152 | ItemKind::Enum(..) => (x.ident.name, "enum"), | |
153 | ItemKind::Union(..) => (x.ident.name, "union"), | |
154 | _ => (x.ident.name, "type"), | |
155 | }, | |
156 | _ => return, | |
157 | }; | |
158 | check_for_is_empty(cx, sig.span, sig.decl.implicit_self, output, ty_id, name, kind); | |
f20569fa XL |
159 | } |
160 | } | |
161 | ||
162 | fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) { | |
add651ee | 163 | if let ExprKind::Let(lt) = expr.kind |
add651ee FG |
164 | && match lt.pat.kind { |
165 | PatKind::Slice([], None, []) => true, | |
166 | PatKind::Lit(lit) if is_empty_string(lit) => true, | |
167 | _ => false, | |
168 | } | |
1f0639a9 FG |
169 | && !expr.span.from_expansion() |
170 | && has_is_empty(cx, lt.init) | |
add651ee FG |
171 | { |
172 | let mut applicability = Applicability::MachineApplicable; | |
173 | ||
174 | let lit1 = peel_ref_operators(cx, lt.init); | |
ed00b5ec | 175 | let lit_str = Sugg::hir_with_context(cx, lit1, lt.span.ctxt(), "_", &mut applicability).maybe_par(); |
add651ee FG |
176 | |
177 | span_lint_and_sugg( | |
178 | cx, | |
179 | COMPARISON_TO_EMPTY, | |
180 | lt.span, | |
181 | "comparison to empty slice using `if let`", | |
182 | "using `is_empty` is clearer and more explicit", | |
183 | format!("{lit_str}.is_empty()"), | |
184 | applicability, | |
185 | ); | |
186 | } | |
187 | ||
1f0639a9 FG |
188 | if let ExprKind::Binary(Spanned { node: cmp, .. }, left, right) = expr.kind |
189 | && !expr.span.from_expansion() | |
190 | { | |
49aad941 | 191 | // expr.span might contains parenthesis, see issue #10529 |
e8be2606 | 192 | let actual_span = span_without_enclosing_paren(cx, expr.span); |
f20569fa XL |
193 | match cmp { |
194 | BinOpKind::Eq => { | |
49aad941 FG |
195 | check_cmp(cx, actual_span, left, right, "", 0); // len == 0 |
196 | check_cmp(cx, actual_span, right, left, "", 0); // 0 == len | |
f20569fa XL |
197 | }, |
198 | BinOpKind::Ne => { | |
49aad941 FG |
199 | check_cmp(cx, actual_span, left, right, "!", 0); // len != 0 |
200 | check_cmp(cx, actual_span, right, left, "!", 0); // 0 != len | |
f20569fa XL |
201 | }, |
202 | BinOpKind::Gt => { | |
49aad941 FG |
203 | check_cmp(cx, actual_span, left, right, "!", 0); // len > 0 |
204 | check_cmp(cx, actual_span, right, left, "", 1); // 1 > len | |
f20569fa XL |
205 | }, |
206 | BinOpKind::Lt => { | |
49aad941 FG |
207 | check_cmp(cx, actual_span, left, right, "", 1); // len < 1 |
208 | check_cmp(cx, actual_span, right, left, "!", 0); // 0 < len | |
f20569fa | 209 | }, |
49aad941 FG |
210 | BinOpKind::Ge => check_cmp(cx, actual_span, left, right, "!", 1), // len >= 1 |
211 | BinOpKind::Le => check_cmp(cx, actual_span, right, left, "!", 1), // 1 <= len | |
f20569fa XL |
212 | _ => (), |
213 | } | |
214 | } | |
215 | } | |
216 | } | |
217 | ||
e8be2606 FG |
218 | fn span_without_enclosing_paren(cx: &LateContext<'_>, span: Span) -> Span { |
219 | let Some(snippet) = snippet_opt(cx, span) else { | |
220 | return span; | |
221 | }; | |
222 | if has_enclosing_paren(snippet) { | |
223 | let source_map = cx.tcx.sess.source_map(); | |
224 | let left_paren = source_map.start_point(span); | |
225 | let right_parent = source_map.end_point(span); | |
226 | left_paren.between(right_parent) | |
227 | } else { | |
228 | span | |
229 | } | |
230 | } | |
231 | ||
f20569fa | 232 | fn check_trait_items(cx: &LateContext<'_>, visited_trait: &Item<'_>, trait_items: &[TraitItemRef]) { |
136023e0 XL |
233 | fn is_named_self(cx: &LateContext<'_>, item: &TraitItemRef, name: Symbol) -> bool { |
234 | item.ident.name == name | |
f20569fa | 235 | && if let AssocItemKind::Fn { has_self } = item.kind { |
9ffffee4 FG |
236 | has_self && { |
237 | cx.tcx | |
238 | .fn_sig(item.id.owner_id) | |
239 | .skip_binder() | |
240 | .inputs() | |
241 | .skip_binder() | |
242 | .len() | |
243 | == 1 | |
244 | } | |
f20569fa XL |
245 | } else { |
246 | false | |
247 | } | |
248 | } | |
249 | ||
250 | // fill the set with current and super traits | |
cdc7bbd5 | 251 | fn fill_trait_set(traitt: DefId, set: &mut DefIdSet, cx: &LateContext<'_>) { |
f20569fa | 252 | if set.insert(traitt) { |
31ef2f64 | 253 | for supertrait in cx.tcx.supertrait_def_ids(traitt) { |
f20569fa XL |
254 | fill_trait_set(supertrait, set, cx); |
255 | } | |
256 | } | |
257 | } | |
258 | ||
2b03887a FG |
259 | if cx.effective_visibilities.is_exported(visited_trait.owner_id.def_id) |
260 | && trait_items.iter().any(|i| is_named_self(cx, i, sym::len)) | |
136023e0 | 261 | { |
cdc7bbd5 | 262 | let mut current_and_super_traits = DefIdSet::default(); |
2b03887a | 263 | fill_trait_set(visited_trait.owner_id.to_def_id(), &mut current_and_super_traits, cx); |
5099ac24 | 264 | let is_empty = sym!(is_empty); |
f20569fa XL |
265 | |
266 | let is_empty_method_found = current_and_super_traits | |
9c376795 | 267 | .items() |
5099ac24 | 268 | .flat_map(|&i| cx.tcx.associated_items(i).filter_by_name_unhygienic(is_empty)) |
f20569fa | 269 | .any(|i| { |
e8be2606 | 270 | i.kind == AssocKind::Fn |
f20569fa | 271 | && i.fn_has_self_parameter |
9ffffee4 | 272 | && cx.tcx.fn_sig(i.def_id).skip_binder().inputs().skip_binder().len() == 1 |
f20569fa XL |
273 | }); |
274 | ||
275 | if !is_empty_method_found { | |
276 | span_lint( | |
277 | cx, | |
278 | LEN_WITHOUT_IS_EMPTY, | |
279 | visited_trait.span, | |
e8be2606 | 280 | format!( |
f20569fa XL |
281 | "trait `{}` has a `len` method but no (possibly inherited) `is_empty` method", |
282 | visited_trait.ident.name | |
283 | ), | |
284 | ); | |
285 | } | |
286 | } | |
287 | } | |
288 | ||
cdc7bbd5 | 289 | #[derive(Debug, Clone, Copy)] |
353b0b11 | 290 | enum LenOutput { |
cdc7bbd5 XL |
291 | Integral, |
292 | Option(DefId), | |
353b0b11 | 293 | Result(DefId), |
cdc7bbd5 | 294 | } |
353b0b11 FG |
295 | |
296 | fn extract_future_output<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> Option<&'tcx PathSegment<'tcx>> { | |
ed00b5ec FG |
297 | if let ty::Alias(_, alias_ty) = ty.kind() |
298 | && let Some(Node::Item(item)) = cx.tcx.hir().get_if_local(alias_ty.def_id) | |
299 | && let Item { | |
300 | kind: ItemKind::OpaqueTy(opaque), | |
301 | .. | |
302 | } = item | |
4b012472 FG |
303 | && let OpaqueTyOrigin::AsyncFn(_) = opaque.origin |
304 | && let [GenericBound::Trait(trait_ref, _)] = &opaque.bounds | |
305 | && let Some(segment) = trait_ref.trait_ref.path.segments.last() | |
306 | && let Some(generic_args) = segment.args | |
31ef2f64 FG |
307 | && let [constraint] = generic_args.constraints |
308 | && let Some(ty) = constraint.ty() | |
309 | && let TyKind::Path(QPath::Resolved(_, path)) = ty.kind | |
310 | && let [segment] = path.segments | |
ed00b5ec | 311 | { |
31ef2f64 | 312 | return Some(segment); |
ed00b5ec | 313 | } |
353b0b11 FG |
314 | |
315 | None | |
316 | } | |
317 | ||
318 | fn is_first_generic_integral<'tcx>(segment: &'tcx PathSegment<'tcx>) -> bool { | |
319 | if let Some(generic_args) = segment.args { | |
320 | if generic_args.args.is_empty() { | |
321 | return false; | |
322 | } | |
323 | let arg = &generic_args.args[0]; | |
324 | if let GenericArg::Type(rustc_hir::Ty { | |
325 | kind: TyKind::Path(QPath::Resolved(_, path)), | |
326 | .. | |
327 | }) = arg | |
328 | { | |
329 | let segments = &path.segments; | |
330 | let segment = &segments[0]; | |
331 | let res = &segment.res; | |
332 | if matches!(res, Res::PrimTy(PrimTy::Uint(_))) || matches!(res, Res::PrimTy(PrimTy::Int(_))) { | |
333 | return true; | |
334 | } | |
335 | } | |
336 | } | |
337 | ||
338 | false | |
339 | } | |
340 | ||
341 | fn parse_len_output<'tcx>(cx: &LateContext<'tcx>, sig: FnSig<'tcx>) -> Option<LenOutput> { | |
342 | if let Some(segment) = extract_future_output(cx, sig.output()) { | |
343 | let res = segment.res; | |
344 | ||
345 | if matches!(res, Res::PrimTy(PrimTy::Uint(_))) || matches!(res, Res::PrimTy(PrimTy::Int(_))) { | |
346 | return Some(LenOutput::Integral); | |
347 | } | |
348 | ||
349 | if let Res::Def(_, def_id) = res { | |
350 | if cx.tcx.is_diagnostic_item(sym::Option, def_id) && is_first_generic_integral(segment) { | |
351 | return Some(LenOutput::Option(def_id)); | |
352 | } else if cx.tcx.is_diagnostic_item(sym::Result, def_id) && is_first_generic_integral(segment) { | |
353 | return Some(LenOutput::Result(def_id)); | |
354 | } | |
355 | } | |
356 | ||
357 | return None; | |
358 | } | |
359 | ||
cdc7bbd5 XL |
360 | match *sig.output().kind() { |
361 | ty::Int(_) | ty::Uint(_) => Some(LenOutput::Integral), | |
5e7ed085 FG |
362 | ty::Adt(adt, subs) if cx.tcx.is_diagnostic_item(sym::Option, adt.did()) => { |
363 | subs.type_at(0).is_integral().then(|| LenOutput::Option(adt.did())) | |
cdc7bbd5 | 364 | }, |
353b0b11 FG |
365 | ty::Adt(adt, subs) if cx.tcx.is_diagnostic_item(sym::Result, adt.did()) => { |
366 | subs.type_at(0).is_integral().then(|| LenOutput::Result(adt.did())) | |
367 | }, | |
cdc7bbd5 XL |
368 | _ => None, |
369 | } | |
370 | } | |
371 | ||
353b0b11 FG |
372 | impl LenOutput { |
373 | fn matches_is_empty_output<'tcx>(self, cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool { | |
374 | if let Some(segment) = extract_future_output(cx, ty) { | |
375 | return match (self, segment.res) { | |
376 | (_, Res::PrimTy(PrimTy::Bool)) => true, | |
377 | (Self::Option(_), Res::Def(_, def_id)) if cx.tcx.is_diagnostic_item(sym::Option, def_id) => true, | |
378 | (Self::Result(_), Res::Def(_, def_id)) if cx.tcx.is_diagnostic_item(sym::Result, def_id) => true, | |
379 | _ => false, | |
380 | }; | |
381 | } | |
382 | ||
cdc7bbd5 XL |
383 | match (self, ty.kind()) { |
384 | (_, &ty::Bool) => true, | |
5e7ed085 | 385 | (Self::Option(id), &ty::Adt(adt, subs)) if id == adt.did() => subs.type_at(0).is_bool(), |
353b0b11 | 386 | (Self::Result(id), &ty::Adt(adt, subs)) if id == adt.did() => subs.type_at(0).is_bool(), |
cdc7bbd5 XL |
387 | _ => false, |
388 | } | |
389 | } | |
390 | ||
391 | fn expected_sig(self, self_kind: ImplicitSelfKind) -> String { | |
392 | let self_ref = match self_kind { | |
e8be2606 FG |
393 | ImplicitSelfKind::RefImm => "&", |
394 | ImplicitSelfKind::RefMut => "&mut ", | |
cdc7bbd5 XL |
395 | _ => "", |
396 | }; | |
397 | match self { | |
2b03887a FG |
398 | Self::Integral => format!("expected signature: `({self_ref}self) -> bool`"), |
399 | Self::Option(_) => { | |
400 | format!("expected signature: `({self_ref}self) -> bool` or `({self_ref}self) -> Option<bool>") | |
401 | }, | |
402 | Self::Result(..) => { | |
403 | format!("expected signature: `({self_ref}self) -> bool` or `({self_ref}self) -> Result<bool>") | |
404 | }, | |
cdc7bbd5 XL |
405 | } |
406 | } | |
407 | } | |
408 | ||
f20569fa | 409 | /// Checks if the given signature matches the expectations for `is_empty` |
353b0b11 FG |
410 | fn check_is_empty_sig<'tcx>( |
411 | cx: &LateContext<'tcx>, | |
412 | sig: FnSig<'tcx>, | |
413 | self_kind: ImplicitSelfKind, | |
414 | len_output: LenOutput, | |
415 | ) -> bool { | |
f20569fa | 416 | match &**sig.inputs_and_output { |
353b0b11 | 417 | [arg, res] if len_output.matches_is_empty_output(cx, *res) => { |
f20569fa XL |
418 | matches!( |
419 | (arg.kind(), self_kind), | |
e8be2606 FG |
420 | (ty::Ref(_, _, Mutability::Not), ImplicitSelfKind::RefImm) |
421 | | (ty::Ref(_, _, Mutability::Mut), ImplicitSelfKind::RefMut) | |
f20569fa XL |
422 | ) || (!arg.is_ref() && matches!(self_kind, ImplicitSelfKind::Imm | ImplicitSelfKind::Mut)) |
423 | }, | |
424 | _ => false, | |
425 | } | |
426 | } | |
427 | ||
428 | /// Checks if the given type has an `is_empty` method with the appropriate signature. | |
353b0b11 FG |
429 | fn check_for_is_empty( |
430 | cx: &LateContext<'_>, | |
f20569fa XL |
431 | span: Span, |
432 | self_kind: ImplicitSelfKind, | |
353b0b11 | 433 | output: LenOutput, |
f20569fa XL |
434 | impl_ty: DefId, |
435 | item_name: Symbol, | |
436 | item_kind: &str, | |
437 | ) { | |
781aab86 FG |
438 | // Implementor may be a type alias, in which case we need to get the `DefId` of the aliased type to |
439 | // find the correct inherent impls. | |
440 | let impl_ty = if let Some(adt) = cx.tcx.type_of(impl_ty).skip_binder().ty_adt_def() { | |
441 | adt.did() | |
442 | } else { | |
443 | return; | |
444 | }; | |
445 | ||
f20569fa XL |
446 | let is_empty = Symbol::intern("is_empty"); |
447 | let is_empty = cx | |
448 | .tcx | |
449 | .inherent_impls(impl_ty) | |
c0240ec0 FG |
450 | .into_iter() |
451 | .flatten() | |
f20569fa XL |
452 | .flat_map(|&id| cx.tcx.associated_items(id).filter_by_name_unhygienic(is_empty)) |
453 | .find(|item| item.kind == AssocKind::Fn); | |
454 | ||
455 | let (msg, is_empty_span, self_kind) = match is_empty { | |
456 | None => ( | |
457 | format!( | |
2b03887a | 458 | "{item_kind} `{}` has a public `len` method, but no `is_empty` method", |
f20569fa XL |
459 | item_name.as_str(), |
460 | ), | |
461 | None, | |
462 | None, | |
463 | ), | |
2b03887a | 464 | Some(is_empty) if !cx.effective_visibilities.is_exported(is_empty.def_id.expect_local()) => ( |
94222f64 | 465 | format!( |
2b03887a | 466 | "{item_kind} `{}` has a public `len` method, but a private `is_empty` method", |
94222f64 XL |
467 | item_name.as_str(), |
468 | ), | |
469 | Some(cx.tcx.def_span(is_empty.def_id)), | |
470 | None, | |
471 | ), | |
f20569fa XL |
472 | Some(is_empty) |
473 | if !(is_empty.fn_has_self_parameter | |
9ffffee4 | 474 | && check_is_empty_sig( |
353b0b11 | 475 | cx, |
add651ee | 476 | cx.tcx.fn_sig(is_empty.def_id).instantiate_identity().skip_binder(), |
9ffffee4 FG |
477 | self_kind, |
478 | output, | |
479 | )) => | |
f20569fa XL |
480 | { |
481 | ( | |
482 | format!( | |
2b03887a | 483 | "{item_kind} `{}` has a public `len` method, but the `is_empty` method has an unexpected signature", |
f20569fa XL |
484 | item_name.as_str(), |
485 | ), | |
486 | Some(cx.tcx.def_span(is_empty.def_id)), | |
487 | Some(self_kind), | |
488 | ) | |
489 | }, | |
490 | Some(_) => return, | |
491 | }; | |
492 | ||
e8be2606 | 493 | span_lint_and_then(cx, LEN_WITHOUT_IS_EMPTY, span, msg, |db| { |
f20569fa XL |
494 | if let Some(span) = is_empty_span { |
495 | db.span_note(span, "`is_empty` defined here"); | |
496 | } | |
497 | if let Some(self_kind) = self_kind { | |
9c376795 | 498 | db.note(output.expected_sig(self_kind)); |
f20569fa XL |
499 | } |
500 | }); | |
501 | } | |
502 | ||
503 | fn check_cmp(cx: &LateContext<'_>, span: Span, method: &Expr<'_>, lit: &Expr<'_>, op: &str, compare_to: u32) { | |
e8be2606 FG |
504 | if method.span.from_expansion() { |
505 | return; | |
506 | } | |
507 | ||
487cf647 | 508 | if let (&ExprKind::MethodCall(method_path, receiver, args, _), ExprKind::Lit(lit)) = (&method.kind, &lit.kind) { |
f20569fa XL |
509 | // check if we are in an is_empty() method |
510 | if let Some(name) = get_item_name(cx, method) { | |
511 | if name.as_str() == "is_empty" { | |
512 | return; | |
513 | } | |
514 | } | |
515 | ||
f2b60f7d FG |
516 | check_len( |
517 | cx, | |
518 | span, | |
519 | method_path.ident.name, | |
520 | receiver, | |
521 | args, | |
522 | &lit.node, | |
523 | op, | |
524 | compare_to, | |
525 | ); | |
f20569fa | 526 | } else { |
17df50a5 | 527 | check_empty_expr(cx, span, method, lit, op); |
f20569fa XL |
528 | } |
529 | } | |
530 | ||
f2b60f7d FG |
531 | // FIXME(flip1995): Figure out how to reduce the number of arguments |
532 | #[allow(clippy::too_many_arguments)] | |
f20569fa XL |
533 | fn check_len( |
534 | cx: &LateContext<'_>, | |
535 | span: Span, | |
536 | method_name: Symbol, | |
f2b60f7d | 537 | receiver: &Expr<'_>, |
f20569fa XL |
538 | args: &[Expr<'_>], |
539 | lit: &LitKind, | |
540 | op: &str, | |
541 | compare_to: u32, | |
542 | ) { | |
543 | if let LitKind::Int(lit, _) = *lit { | |
544 | // check if length is compared to the specified number | |
545 | if lit != u128::from(compare_to) { | |
546 | return; | |
547 | } | |
548 | ||
f2b60f7d | 549 | if method_name == sym::len && args.is_empty() && has_is_empty(cx, receiver) { |
f20569fa XL |
550 | let mut applicability = Applicability::MachineApplicable; |
551 | span_lint_and_sugg( | |
552 | cx, | |
553 | LEN_ZERO, | |
554 | span, | |
e8be2606 FG |
555 | format!("length comparison to {}", if compare_to == 0 { "zero" } else { "one" }), |
556 | format!("using `{op}is_empty` is clearer and more explicit"), | |
f20569fa | 557 | format!( |
2b03887a | 558 | "{op}{}.is_empty()", |
353b0b11 | 559 | snippet_with_context(cx, receiver.span, span.ctxt(), "_", &mut applicability).0, |
f20569fa XL |
560 | ), |
561 | applicability, | |
562 | ); | |
563 | } | |
564 | } | |
565 | } | |
566 | ||
567 | fn check_empty_expr(cx: &LateContext<'_>, span: Span, lit1: &Expr<'_>, lit2: &Expr<'_>, op: &str) { | |
568 | if (is_empty_array(lit2) || is_empty_string(lit2)) && has_is_empty(cx, lit1) { | |
569 | let mut applicability = Applicability::MachineApplicable; | |
9c376795 FG |
570 | |
571 | let lit1 = peel_ref_operators(cx, lit1); | |
353b0b11 | 572 | let lit_str = Sugg::hir_with_context(cx, lit1, span.ctxt(), "_", &mut applicability).maybe_par(); |
9c376795 | 573 | |
f20569fa XL |
574 | span_lint_and_sugg( |
575 | cx, | |
576 | COMPARISON_TO_EMPTY, | |
577 | span, | |
578 | "comparison to empty slice", | |
e8be2606 | 579 | format!("using `{op}is_empty` is clearer and more explicit"), |
9c376795 | 580 | format!("{op}{lit_str}.is_empty()"), |
f20569fa XL |
581 | applicability, |
582 | ); | |
583 | } | |
584 | } | |
585 | ||
586 | fn is_empty_string(expr: &Expr<'_>) -> bool { | |
49aad941 | 587 | if let ExprKind::Lit(lit) = expr.kind { |
f20569fa XL |
588 | if let LitKind::Str(lit, _) = lit.node { |
589 | let lit = lit.as_str(); | |
a2a8927a | 590 | return lit.is_empty(); |
f20569fa XL |
591 | } |
592 | } | |
593 | false | |
594 | } | |
595 | ||
596 | fn is_empty_array(expr: &Expr<'_>) -> bool { | |
cdc7bbd5 | 597 | if let ExprKind::Array(arr) = expr.kind { |
f20569fa XL |
598 | return arr.is_empty(); |
599 | } | |
600 | false | |
601 | } | |
602 | ||
603 | /// Checks if this type has an `is_empty` method. | |
604 | fn has_is_empty(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool { | |
605 | /// Gets an `AssocItem` and return true if it matches `is_empty(self)`. | |
606 | fn is_is_empty(cx: &LateContext<'_>, item: &ty::AssocItem) -> bool { | |
e8be2606 | 607 | if item.kind == AssocKind::Fn { |
9ffffee4 | 608 | let sig = cx.tcx.fn_sig(item.def_id).skip_binder(); |
c295e0f8 XL |
609 | let ty = sig.skip_binder(); |
610 | ty.inputs().len() == 1 | |
f20569fa XL |
611 | } else { |
612 | false | |
613 | } | |
614 | } | |
615 | ||
616 | /// Checks the inherent impl's items for an `is_empty(self)` method. | |
617 | fn has_is_empty_impl(cx: &LateContext<'_>, id: DefId) -> bool { | |
5099ac24 | 618 | let is_empty = sym!(is_empty); |
c0240ec0 | 619 | cx.tcx.inherent_impls(id).into_iter().flatten().any(|imp| { |
f20569fa XL |
620 | cx.tcx |
621 | .associated_items(*imp) | |
5099ac24 | 622 | .filter_by_name_unhygienic(is_empty) |
cdc7bbd5 | 623 | .any(|item| is_is_empty(cx, item)) |
f20569fa XL |
624 | }) |
625 | } | |
626 | ||
627 | let ty = &cx.typeck_results().expr_ty(expr).peel_refs(); | |
628 | match ty.kind() { | |
cdc7bbd5 | 629 | ty::Dynamic(tt, ..) => tt.principal().map_or(false, |principal| { |
5099ac24 | 630 | let is_empty = sym!(is_empty); |
f20569fa XL |
631 | cx.tcx |
632 | .associated_items(principal.def_id()) | |
5099ac24 | 633 | .filter_by_name_unhygienic(is_empty) |
cdc7bbd5 | 634 | .any(|item| is_is_empty(cx, item)) |
f20569fa | 635 | }), |
9c376795 | 636 | ty::Alias(ty::Projection, ref proj) => has_is_empty_impl(cx, proj.def_id), |
5e7ed085 | 637 | ty::Adt(id, _) => has_is_empty_impl(cx, id.did()), |
f20569fa XL |
638 | ty::Array(..) | ty::Slice(..) | ty::Str => true, |
639 | _ => false, | |
640 | } | |
641 | } |