]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/methods/mod.rs
Fixed Typo
[rust.git] / clippy_lints / src / methods / mod.rs
1 mod bind_instead_of_map;
2 mod bytecount;
3 mod bytes_count_to_len;
4 mod bytes_nth;
5 mod case_sensitive_file_extension_comparisons;
6 mod chars_cmp;
7 mod chars_cmp_with_unwrap;
8 mod chars_last_cmp;
9 mod chars_last_cmp_with_unwrap;
10 mod chars_next_cmp;
11 mod chars_next_cmp_with_unwrap;
12 mod clone_on_copy;
13 mod clone_on_ref_ptr;
14 mod cloned_instead_of_copied;
15 mod collapsible_str_replace;
16 mod err_expect;
17 mod expect_fun_call;
18 mod expect_used;
19 mod extend_with_drain;
20 mod filetype_is_file;
21 mod filter_map;
22 mod filter_map_identity;
23 mod filter_map_next;
24 mod filter_next;
25 mod flat_map_identity;
26 mod flat_map_option;
27 mod from_iter_instead_of_collect;
28 mod get_first;
29 mod get_last_with_len;
30 mod get_unwrap;
31 mod implicit_clone;
32 mod inefficient_to_string;
33 mod inspect_for_each;
34 mod into_iter_on_ref;
35 mod is_digit_ascii_radix;
36 mod iter_cloned_collect;
37 mod iter_count;
38 mod iter_kv_map;
39 mod iter_next_slice;
40 mod iter_nth;
41 mod iter_nth_zero;
42 mod iter_on_single_or_empty_collections;
43 mod iter_overeager_cloned;
44 mod iter_skip_next;
45 mod iter_with_drain;
46 mod iterator_step_by_zero;
47 mod manual_ok_or;
48 mod manual_saturating_arithmetic;
49 mod manual_str_repeat;
50 mod map_clone;
51 mod map_collect_result_unit;
52 mod map_err_ignore;
53 mod map_flatten;
54 mod map_identity;
55 mod map_unwrap_or;
56 mod mut_mutex_lock;
57 mod needless_collect;
58 mod needless_option_as_deref;
59 mod needless_option_take;
60 mod no_effect_replace;
61 mod obfuscated_if_else;
62 mod ok_expect;
63 mod open_options;
64 mod option_as_ref_deref;
65 mod option_map_or_none;
66 mod option_map_unwrap_or;
67 mod or_fun_call;
68 mod or_then_unwrap;
69 mod path_buf_push_overwrite;
70 mod range_zip_with_len;
71 mod repeat_once;
72 mod search_is_some;
73 mod seek_from_current;
74 mod seek_to_start_instead_of_rewind;
75 mod single_char_add_str;
76 mod single_char_insert_string;
77 mod single_char_pattern;
78 mod single_char_push_string;
79 mod skip_while_next;
80 mod stable_sort_primitive;
81 mod str_splitn;
82 mod string_extend_chars;
83 mod suspicious_map;
84 mod suspicious_splitn;
85 mod suspicious_to_owned;
86 mod uninit_assumed_init;
87 mod unit_hash;
88 mod unnecessary_filter_map;
89 mod unnecessary_fold;
90 mod unnecessary_iter_cloned;
91 mod unnecessary_join;
92 mod unnecessary_lazy_eval;
93 mod unnecessary_sort_by;
94 mod unnecessary_to_owned;
95 mod unwrap_or_else_default;
96 mod unwrap_used;
97 mod useless_asref;
98 mod utils;
99 mod vec_resize_to_zero;
100 mod verbose_file_reads;
101 mod wrong_self_convention;
102 mod zst_offset;
103
104 use bind_instead_of_map::BindInsteadOfMap;
105 use clippy_utils::consts::{constant, Constant};
106 use clippy_utils::diagnostics::{span_lint, span_lint_and_help};
107 use clippy_utils::ty::{contains_ty_adt_constructor_opaque, implements_trait, is_copy, is_type_diagnostic_item};
108 use clippy_utils::{contains_return, is_trait_method, iter_input_pats, meets_msrv, msrvs, return_ty};
109 use if_chain::if_chain;
110 use rustc_hir as hir;
111 use rustc_hir::def::Res;
112 use rustc_hir::{Expr, ExprKind, PrimTy, QPath, TraitItem, TraitItemKind};
113 use rustc_hir_analysis::hir_ty_to_ty;
114 use rustc_lint::{LateContext, LateLintPass, LintContext};
115 use rustc_middle::lint::in_external_macro;
116 use rustc_middle::ty::{self, TraitRef, Ty};
117 use rustc_semver::RustcVersion;
118 use rustc_session::{declare_tool_lint, impl_lint_pass};
119 use rustc_span::{sym, Span};
120
121 declare_clippy_lint! {
122     /// ### What it does
123     /// Checks for usages of `cloned()` on an `Iterator` or `Option` where
124     /// `copied()` could be used instead.
125     ///
126     /// ### Why is this bad?
127     /// `copied()` is better because it guarantees that the type being cloned
128     /// implements `Copy`.
129     ///
130     /// ### Example
131     /// ```rust
132     /// [1, 2, 3].iter().cloned();
133     /// ```
134     /// Use instead:
135     /// ```rust
136     /// [1, 2, 3].iter().copied();
137     /// ```
138     #[clippy::version = "1.53.0"]
139     pub CLONED_INSTEAD_OF_COPIED,
140     pedantic,
141     "used `cloned` where `copied` could be used instead"
142 }
143
144 declare_clippy_lint! {
145     /// ### What it does
146     /// Checks for consecutive calls to `str::replace` (2 or more)
147     /// that can be collapsed into a single call.
148     ///
149     /// ### Why is this bad?
150     /// Consecutive `str::replace` calls scan the string multiple times
151     /// with repetitive code.
152     ///
153     /// ### Example
154     /// ```rust
155     /// let hello = "hesuo worpd"
156     ///     .replace('s', "l")
157     ///     .replace("u", "l")
158     ///     .replace('p', "l");
159     /// ```
160     /// Use instead:
161     /// ```rust
162     /// let hello = "hesuo worpd".replace(&['s', 'u', 'p'], "l");
163     /// ```
164     #[clippy::version = "1.65.0"]
165     pub COLLAPSIBLE_STR_REPLACE,
166     perf,
167     "collapse consecutive calls to str::replace (2 or more) into a single call"
168 }
169
170 declare_clippy_lint! {
171     /// ### What it does
172     /// Checks for usage of `_.cloned().<func>()` where call to `.cloned()` can be postponed.
173     ///
174     /// ### Why is this bad?
175     /// It's often inefficient to clone all elements of an iterator, when eventually, only some
176     /// of them will be consumed.
177     ///
178     /// ### Known Problems
179     /// This `lint` removes the side of effect of cloning items in the iterator.
180     /// A code that relies on that side-effect could fail.
181     ///
182     /// ### Examples
183     /// ```rust
184     /// # let vec = vec!["string".to_string()];
185     /// vec.iter().cloned().take(10);
186     /// vec.iter().cloned().last();
187     /// ```
188     ///
189     /// Use instead:
190     /// ```rust
191     /// # let vec = vec!["string".to_string()];
192     /// vec.iter().take(10).cloned();
193     /// vec.iter().last().cloned();
194     /// ```
195     #[clippy::version = "1.60.0"]
196     pub ITER_OVEREAGER_CLONED,
197     perf,
198     "using `cloned()` early with `Iterator::iter()` can lead to some performance inefficiencies"
199 }
200
201 declare_clippy_lint! {
202     /// ### What it does
203     /// Checks for usages of `Iterator::flat_map()` where `filter_map()` could be
204     /// used instead.
205     ///
206     /// ### Why is this bad?
207     /// When applicable, `filter_map()` is more clear since it shows that
208     /// `Option` is used to produce 0 or 1 items.
209     ///
210     /// ### Example
211     /// ```rust
212     /// let nums: Vec<i32> = ["1", "2", "whee!"].iter().flat_map(|x| x.parse().ok()).collect();
213     /// ```
214     /// Use instead:
215     /// ```rust
216     /// let nums: Vec<i32> = ["1", "2", "whee!"].iter().filter_map(|x| x.parse().ok()).collect();
217     /// ```
218     #[clippy::version = "1.53.0"]
219     pub FLAT_MAP_OPTION,
220     pedantic,
221     "used `flat_map` where `filter_map` could be used instead"
222 }
223
224 declare_clippy_lint! {
225     /// ### What it does
226     /// Checks for `.unwrap()` or `.unwrap_err()` calls on `Result`s and `.unwrap()` call on `Option`s.
227     ///
228     /// ### Why is this bad?
229     /// It is better to handle the `None` or `Err` case,
230     /// or at least call `.expect(_)` with a more helpful message. Still, for a lot of
231     /// quick-and-dirty code, `unwrap` is a good choice, which is why this lint is
232     /// `Allow` by default.
233     ///
234     /// `result.unwrap()` will let the thread panic on `Err` values.
235     /// Normally, you want to implement more sophisticated error handling,
236     /// and propagate errors upwards with `?` operator.
237     ///
238     /// Even if you want to panic on errors, not all `Error`s implement good
239     /// messages on display. Therefore, it may be beneficial to look at the places
240     /// where they may get displayed. Activate this lint to do just that.
241     ///
242     /// ### Examples
243     /// ```rust
244     /// # let option = Some(1);
245     /// # let result: Result<usize, ()> = Ok(1);
246     /// option.unwrap();
247     /// result.unwrap();
248     /// ```
249     ///
250     /// Use instead:
251     /// ```rust
252     /// # let option = Some(1);
253     /// # let result: Result<usize, ()> = Ok(1);
254     /// option.expect("more helpful message");
255     /// result.expect("more helpful message");
256     /// ```
257     ///
258     /// If [expect_used](#expect_used) is enabled, instead:
259     /// ```rust,ignore
260     /// # let option = Some(1);
261     /// # let result: Result<usize, ()> = Ok(1);
262     /// option?;
263     ///
264     /// // or
265     ///
266     /// result?;
267     /// ```
268     #[clippy::version = "1.45.0"]
269     pub UNWRAP_USED,
270     restriction,
271     "using `.unwrap()` on `Result` or `Option`, which should at least get a better message using `expect()`"
272 }
273
274 declare_clippy_lint! {
275     /// ### What it does
276     /// Checks for `.expect()` or `.expect_err()` calls on `Result`s and `.expect()` call on `Option`s.
277     ///
278     /// ### Why is this bad?
279     /// Usually it is better to handle the `None` or `Err` case.
280     /// Still, for a lot of quick-and-dirty code, `expect` is a good choice, which is why
281     /// this lint is `Allow` by default.
282     ///
283     /// `result.expect()` will let the thread panic on `Err`
284     /// values. Normally, you want to implement more sophisticated error handling,
285     /// and propagate errors upwards with `?` operator.
286     ///
287     /// ### Examples
288     /// ```rust,ignore
289     /// # let option = Some(1);
290     /// # let result: Result<usize, ()> = Ok(1);
291     /// option.expect("one");
292     /// result.expect("one");
293     /// ```
294     ///
295     /// Use instead:
296     /// ```rust,ignore
297     /// # let option = Some(1);
298     /// # let result: Result<usize, ()> = Ok(1);
299     /// option?;
300     ///
301     /// // or
302     ///
303     /// result?;
304     /// ```
305     #[clippy::version = "1.45.0"]
306     pub EXPECT_USED,
307     restriction,
308     "using `.expect()` on `Result` or `Option`, which might be better handled"
309 }
310
311 declare_clippy_lint! {
312     /// ### What it does
313     /// Checks for methods that should live in a trait
314     /// implementation of a `std` trait (see [llogiq's blog
315     /// post](http://llogiq.github.io/2015/07/30/traits.html) for further
316     /// information) instead of an inherent implementation.
317     ///
318     /// ### Why is this bad?
319     /// Implementing the traits improve ergonomics for users of
320     /// the code, often with very little cost. Also people seeing a `mul(...)`
321     /// method
322     /// may expect `*` to work equally, so you should have good reason to disappoint
323     /// them.
324     ///
325     /// ### Example
326     /// ```rust
327     /// struct X;
328     /// impl X {
329     ///     fn add(&self, other: &X) -> X {
330     ///         // ..
331     /// # X
332     ///     }
333     /// }
334     /// ```
335     #[clippy::version = "pre 1.29.0"]
336     pub SHOULD_IMPLEMENT_TRAIT,
337     style,
338     "defining a method that should be implementing a std trait"
339 }
340
341 declare_clippy_lint! {
342     /// ### What it does
343     /// Checks for methods with certain name prefixes and which
344     /// doesn't match how self is taken. The actual rules are:
345     ///
346     /// |Prefix |Postfix     |`self` taken                   | `self` type  |
347     /// |-------|------------|-------------------------------|--------------|
348     /// |`as_`  | none       |`&self` or `&mut self`         | any          |
349     /// |`from_`| none       | none                          | any          |
350     /// |`into_`| none       |`self`                         | any          |
351     /// |`is_`  | none       |`&mut self` or `&self` or none | any          |
352     /// |`to_`  | `_mut`     |`&mut self`                    | any          |
353     /// |`to_`  | not `_mut` |`self`                         | `Copy`       |
354     /// |`to_`  | not `_mut` |`&self`                        | not `Copy`   |
355     ///
356     /// Note: Clippy doesn't trigger methods with `to_` prefix in:
357     /// - Traits definition.
358     /// Clippy can not tell if a type that implements a trait is `Copy` or not.
359     /// - Traits implementation, when `&self` is taken.
360     /// The method signature is controlled by the trait and often `&self` is required for all types that implement the trait
361     /// (see e.g. the `std::string::ToString` trait).
362     ///
363     /// Clippy allows `Pin<&Self>` and `Pin<&mut Self>` if `&self` and `&mut self` is required.
364     ///
365     /// Please find more info here:
366     /// https://rust-lang.github.io/api-guidelines/naming.html#ad-hoc-conversions-follow-as_-to_-into_-conventions-c-conv
367     ///
368     /// ### Why is this bad?
369     /// Consistency breeds readability. If you follow the
370     /// conventions, your users won't be surprised that they, e.g., need to supply a
371     /// mutable reference to a `as_..` function.
372     ///
373     /// ### Example
374     /// ```rust
375     /// # struct X;
376     /// impl X {
377     ///     fn as_str(self) -> &'static str {
378     ///         // ..
379     /// # ""
380     ///     }
381     /// }
382     /// ```
383     #[clippy::version = "pre 1.29.0"]
384     pub WRONG_SELF_CONVENTION,
385     style,
386     "defining a method named with an established prefix (like \"into_\") that takes `self` with the wrong convention"
387 }
388
389 declare_clippy_lint! {
390     /// ### What it does
391     /// Checks for usage of `ok().expect(..)`.
392     ///
393     /// ### Why is this bad?
394     /// Because you usually call `expect()` on the `Result`
395     /// directly to get a better error message.
396     ///
397     /// ### Known problems
398     /// The error type needs to implement `Debug`
399     ///
400     /// ### Example
401     /// ```rust
402     /// # let x = Ok::<_, ()>(());
403     /// x.ok().expect("why did I do this again?");
404     /// ```
405     ///
406     /// Use instead:
407     /// ```rust
408     /// # let x = Ok::<_, ()>(());
409     /// x.expect("why did I do this again?");
410     /// ```
411     #[clippy::version = "pre 1.29.0"]
412     pub OK_EXPECT,
413     style,
414     "using `ok().expect()`, which gives worse error messages than calling `expect` directly on the Result"
415 }
416
417 declare_clippy_lint! {
418     /// ### What it does
419     /// Checks for `.err().expect()` calls on the `Result` type.
420     ///
421     /// ### Why is this bad?
422     /// `.expect_err()` can be called directly to avoid the extra type conversion from `err()`.
423     ///
424     /// ### Example
425     /// ```should_panic
426     /// let x: Result<u32, &str> = Ok(10);
427     /// x.err().expect("Testing err().expect()");
428     /// ```
429     /// Use instead:
430     /// ```should_panic
431     /// let x: Result<u32, &str> = Ok(10);
432     /// x.expect_err("Testing expect_err");
433     /// ```
434     #[clippy::version = "1.62.0"]
435     pub ERR_EXPECT,
436     style,
437     r#"using `.err().expect("")` when `.expect_err("")` can be used"#
438 }
439
440 declare_clippy_lint! {
441     /// ### What it does
442     /// Checks for usages of `_.unwrap_or_else(Default::default)` on `Option` and
443     /// `Result` values.
444     ///
445     /// ### Why is this bad?
446     /// Readability, these can be written as `_.unwrap_or_default`, which is
447     /// simpler and more concise.
448     ///
449     /// ### Examples
450     /// ```rust
451     /// # let x = Some(1);
452     /// x.unwrap_or_else(Default::default);
453     /// x.unwrap_or_else(u32::default);
454     /// ```
455     ///
456     /// Use instead:
457     /// ```rust
458     /// # let x = Some(1);
459     /// x.unwrap_or_default();
460     /// ```
461     #[clippy::version = "1.56.0"]
462     pub UNWRAP_OR_ELSE_DEFAULT,
463     style,
464     "using `.unwrap_or_else(Default::default)`, which is more succinctly expressed as `.unwrap_or_default()`"
465 }
466
467 declare_clippy_lint! {
468     /// ### What it does
469     /// Checks for usage of `option.map(_).unwrap_or(_)` or `option.map(_).unwrap_or_else(_)` or
470     /// `result.map(_).unwrap_or_else(_)`.
471     ///
472     /// ### Why is this bad?
473     /// Readability, these can be written more concisely (resp.) as
474     /// `option.map_or(_, _)`, `option.map_or_else(_, _)` and `result.map_or_else(_, _)`.
475     ///
476     /// ### Known problems
477     /// The order of the arguments is not in execution order
478     ///
479     /// ### Examples
480     /// ```rust
481     /// # let option = Some(1);
482     /// # let result: Result<usize, ()> = Ok(1);
483     /// # fn some_function(foo: ()) -> usize { 1 }
484     /// option.map(|a| a + 1).unwrap_or(0);
485     /// result.map(|a| a + 1).unwrap_or_else(some_function);
486     /// ```
487     ///
488     /// Use instead:
489     /// ```rust
490     /// # let option = Some(1);
491     /// # let result: Result<usize, ()> = Ok(1);
492     /// # fn some_function(foo: ()) -> usize { 1 }
493     /// option.map_or(0, |a| a + 1);
494     /// result.map_or_else(some_function, |a| a + 1);
495     /// ```
496     #[clippy::version = "1.45.0"]
497     pub MAP_UNWRAP_OR,
498     pedantic,
499     "using `.map(f).unwrap_or(a)` or `.map(f).unwrap_or_else(func)`, which are more succinctly expressed as `map_or(a, f)` or `map_or_else(a, f)`"
500 }
501
502 declare_clippy_lint! {
503     /// ### What it does
504     /// Checks for usage of `_.map_or(None, _)`.
505     ///
506     /// ### Why is this bad?
507     /// Readability, this can be written more concisely as
508     /// `_.and_then(_)`.
509     ///
510     /// ### Known problems
511     /// The order of the arguments is not in execution order.
512     ///
513     /// ### Example
514     /// ```rust
515     /// # let opt = Some(1);
516     /// opt.map_or(None, |a| Some(a + 1));
517     /// ```
518     ///
519     /// Use instead:
520     /// ```rust
521     /// # let opt = Some(1);
522     /// opt.and_then(|a| Some(a + 1));
523     /// ```
524     #[clippy::version = "pre 1.29.0"]
525     pub OPTION_MAP_OR_NONE,
526     style,
527     "using `Option.map_or(None, f)`, which is more succinctly expressed as `and_then(f)`"
528 }
529
530 declare_clippy_lint! {
531     /// ### What it does
532     /// Checks for usage of `_.map_or(None, Some)`.
533     ///
534     /// ### Why is this bad?
535     /// Readability, this can be written more concisely as
536     /// `_.ok()`.
537     ///
538     /// ### Example
539     /// ```rust
540     /// # let r: Result<u32, &str> = Ok(1);
541     /// assert_eq!(Some(1), r.map_or(None, Some));
542     /// ```
543     ///
544     /// Use instead:
545     /// ```rust
546     /// # let r: Result<u32, &str> = Ok(1);
547     /// assert_eq!(Some(1), r.ok());
548     /// ```
549     #[clippy::version = "1.44.0"]
550     pub RESULT_MAP_OR_INTO_OPTION,
551     style,
552     "using `Result.map_or(None, Some)`, which is more succinctly expressed as `ok()`"
553 }
554
555 declare_clippy_lint! {
556     /// ### What it does
557     /// Checks for usage of `_.and_then(|x| Some(y))`, `_.and_then(|x| Ok(y))` or
558     /// `_.or_else(|x| Err(y))`.
559     ///
560     /// ### Why is this bad?
561     /// Readability, this can be written more concisely as
562     /// `_.map(|x| y)` or `_.map_err(|x| y)`.
563     ///
564     /// ### Example
565     /// ```rust
566     /// # fn opt() -> Option<&'static str> { Some("42") }
567     /// # fn res() -> Result<&'static str, &'static str> { Ok("42") }
568     /// let _ = opt().and_then(|s| Some(s.len()));
569     /// let _ = res().and_then(|s| if s.len() == 42 { Ok(10) } else { Ok(20) });
570     /// let _ = res().or_else(|s| if s.len() == 42 { Err(10) } else { Err(20) });
571     /// ```
572     ///
573     /// The correct use would be:
574     ///
575     /// ```rust
576     /// # fn opt() -> Option<&'static str> { Some("42") }
577     /// # fn res() -> Result<&'static str, &'static str> { Ok("42") }
578     /// let _ = opt().map(|s| s.len());
579     /// let _ = res().map(|s| if s.len() == 42 { 10 } else { 20 });
580     /// let _ = res().map_err(|s| if s.len() == 42 { 10 } else { 20 });
581     /// ```
582     #[clippy::version = "1.45.0"]
583     pub BIND_INSTEAD_OF_MAP,
584     complexity,
585     "using `Option.and_then(|x| Some(y))`, which is more succinctly expressed as `map(|x| y)`"
586 }
587
588 declare_clippy_lint! {
589     /// ### What it does
590     /// Checks for usage of `_.filter(_).next()`.
591     ///
592     /// ### Why is this bad?
593     /// Readability, this can be written more concisely as
594     /// `_.find(_)`.
595     ///
596     /// ### Example
597     /// ```rust
598     /// # let vec = vec![1];
599     /// vec.iter().filter(|x| **x == 0).next();
600     /// ```
601     ///
602     /// Use instead:
603     /// ```rust
604     /// # let vec = vec![1];
605     /// vec.iter().find(|x| **x == 0);
606     /// ```
607     #[clippy::version = "pre 1.29.0"]
608     pub FILTER_NEXT,
609     complexity,
610     "using `filter(p).next()`, which is more succinctly expressed as `.find(p)`"
611 }
612
613 declare_clippy_lint! {
614     /// ### What it does
615     /// Checks for usage of `_.skip_while(condition).next()`.
616     ///
617     /// ### Why is this bad?
618     /// Readability, this can be written more concisely as
619     /// `_.find(!condition)`.
620     ///
621     /// ### Example
622     /// ```rust
623     /// # let vec = vec![1];
624     /// vec.iter().skip_while(|x| **x == 0).next();
625     /// ```
626     ///
627     /// Use instead:
628     /// ```rust
629     /// # let vec = vec![1];
630     /// vec.iter().find(|x| **x != 0);
631     /// ```
632     #[clippy::version = "1.42.0"]
633     pub SKIP_WHILE_NEXT,
634     complexity,
635     "using `skip_while(p).next()`, which is more succinctly expressed as `.find(!p)`"
636 }
637
638 declare_clippy_lint! {
639     /// ### What it does
640     /// Checks for usage of `_.map(_).flatten(_)` on `Iterator` and `Option`
641     ///
642     /// ### Why is this bad?
643     /// Readability, this can be written more concisely as
644     /// `_.flat_map(_)` for `Iterator` or `_.and_then(_)` for `Option`
645     ///
646     /// ### Example
647     /// ```rust
648     /// let vec = vec![vec![1]];
649     /// let opt = Some(5);
650     ///
651     /// vec.iter().map(|x| x.iter()).flatten();
652     /// opt.map(|x| Some(x * 2)).flatten();
653     /// ```
654     ///
655     /// Use instead:
656     /// ```rust
657     /// # let vec = vec![vec![1]];
658     /// # let opt = Some(5);
659     /// vec.iter().flat_map(|x| x.iter());
660     /// opt.and_then(|x| Some(x * 2));
661     /// ```
662     #[clippy::version = "1.31.0"]
663     pub MAP_FLATTEN,
664     complexity,
665     "using combinations of `flatten` and `map` which can usually be written as a single method call"
666 }
667
668 declare_clippy_lint! {
669     /// ### What it does
670     /// Checks for usage of `_.filter(_).map(_)` that can be written more simply
671     /// as `filter_map(_)`.
672     ///
673     /// ### Why is this bad?
674     /// Redundant code in the `filter` and `map` operations is poor style and
675     /// less performant.
676     ///
677      /// ### Example
678     /// ```rust
679     /// # #![allow(unused)]
680     /// (0_i32..10)
681     ///     .filter(|n| n.checked_add(1).is_some())
682     ///     .map(|n| n.checked_add(1).unwrap());
683     /// ```
684     ///
685     /// Use instead:
686     /// ```rust
687     /// # #[allow(unused)]
688     /// (0_i32..10).filter_map(|n| n.checked_add(1));
689     /// ```
690     #[clippy::version = "1.51.0"]
691     pub MANUAL_FILTER_MAP,
692     complexity,
693     "using `_.filter(_).map(_)` in a way that can be written more simply as `filter_map(_)`"
694 }
695
696 declare_clippy_lint! {
697     /// ### What it does
698     /// Checks for usage of `_.find(_).map(_)` that can be written more simply
699     /// as `find_map(_)`.
700     ///
701     /// ### Why is this bad?
702     /// Redundant code in the `find` and `map` operations is poor style and
703     /// less performant.
704     ///
705      /// ### Example
706     /// ```rust
707     /// (0_i32..10)
708     ///     .find(|n| n.checked_add(1).is_some())
709     ///     .map(|n| n.checked_add(1).unwrap());
710     /// ```
711     ///
712     /// Use instead:
713     /// ```rust
714     /// (0_i32..10).find_map(|n| n.checked_add(1));
715     /// ```
716     #[clippy::version = "1.51.0"]
717     pub MANUAL_FIND_MAP,
718     complexity,
719     "using `_.find(_).map(_)` in a way that can be written more simply as `find_map(_)`"
720 }
721
722 declare_clippy_lint! {
723     /// ### What it does
724     /// Checks for usage of `_.filter_map(_).next()`.
725     ///
726     /// ### Why is this bad?
727     /// Readability, this can be written more concisely as
728     /// `_.find_map(_)`.
729     ///
730     /// ### Example
731     /// ```rust
732     ///  (0..3).filter_map(|x| if x == 2 { Some(x) } else { None }).next();
733     /// ```
734     /// Can be written as
735     ///
736     /// ```rust
737     ///  (0..3).find_map(|x| if x == 2 { Some(x) } else { None });
738     /// ```
739     #[clippy::version = "1.36.0"]
740     pub FILTER_MAP_NEXT,
741     pedantic,
742     "using combination of `filter_map` and `next` which can usually be written as a single method call"
743 }
744
745 declare_clippy_lint! {
746     /// ### What it does
747     /// Checks for usage of `flat_map(|x| x)`.
748     ///
749     /// ### Why is this bad?
750     /// Readability, this can be written more concisely by using `flatten`.
751     ///
752     /// ### Example
753     /// ```rust
754     /// # let iter = vec![vec![0]].into_iter();
755     /// iter.flat_map(|x| x);
756     /// ```
757     /// Can be written as
758     /// ```rust
759     /// # let iter = vec![vec![0]].into_iter();
760     /// iter.flatten();
761     /// ```
762     #[clippy::version = "1.39.0"]
763     pub FLAT_MAP_IDENTITY,
764     complexity,
765     "call to `flat_map` where `flatten` is sufficient"
766 }
767
768 declare_clippy_lint! {
769     /// ### What it does
770     /// Checks for an iterator or string search (such as `find()`,
771     /// `position()`, or `rposition()`) followed by a call to `is_some()` or `is_none()`.
772     ///
773     /// ### Why is this bad?
774     /// Readability, this can be written more concisely as:
775     /// * `_.any(_)`, or `_.contains(_)` for `is_some()`,
776     /// * `!_.any(_)`, or `!_.contains(_)` for `is_none()`.
777     ///
778     /// ### Example
779     /// ```rust
780     /// # #![allow(unused)]
781     /// let vec = vec![1];
782     /// vec.iter().find(|x| **x == 0).is_some();
783     ///
784     /// "hello world".find("world").is_none();
785     /// ```
786     ///
787     /// Use instead:
788     /// ```rust
789     /// let vec = vec![1];
790     /// vec.iter().any(|x| *x == 0);
791     ///
792     /// # #[allow(unused)]
793     /// !"hello world".contains("world");
794     /// ```
795     #[clippy::version = "pre 1.29.0"]
796     pub SEARCH_IS_SOME,
797     complexity,
798     "using an iterator or string search followed by `is_some()` or `is_none()`, which is more succinctly expressed as a call to `any()` or `contains()` (with negation in case of `is_none()`)"
799 }
800
801 declare_clippy_lint! {
802     /// ### What it does
803     /// Checks for usage of `.chars().next()` on a `str` to check
804     /// if it starts with a given char.
805     ///
806     /// ### Why is this bad?
807     /// Readability, this can be written more concisely as
808     /// `_.starts_with(_)`.
809     ///
810     /// ### Example
811     /// ```rust
812     /// let name = "foo";
813     /// if name.chars().next() == Some('_') {};
814     /// ```
815     ///
816     /// Use instead:
817     /// ```rust
818     /// let name = "foo";
819     /// if name.starts_with('_') {};
820     /// ```
821     #[clippy::version = "pre 1.29.0"]
822     pub CHARS_NEXT_CMP,
823     style,
824     "using `.chars().next()` to check if a string starts with a char"
825 }
826
827 declare_clippy_lint! {
828     /// ### What it does
829     /// Checks for calls to `.or(foo(..))`, `.unwrap_or(foo(..))`,
830     /// `.or_insert(foo(..))` etc., and suggests to use `.or_else(|| foo(..))`,
831     /// `.unwrap_or_else(|| foo(..))`, `.unwrap_or_default()` or `.or_default()`
832     /// etc. instead.
833     ///
834     /// ### Why is this bad?
835     /// The function will always be called and potentially
836     /// allocate an object acting as the default.
837     ///
838     /// ### Known problems
839     /// If the function has side-effects, not calling it will
840     /// change the semantic of the program, but you shouldn't rely on that anyway.
841     ///
842     /// ### Example
843     /// ```rust
844     /// # let foo = Some(String::new());
845     /// foo.unwrap_or(String::new());
846     /// ```
847     ///
848     /// Use instead:
849     /// ```rust
850     /// # let foo = Some(String::new());
851     /// foo.unwrap_or_else(String::new);
852     ///
853     /// // or
854     ///
855     /// # let foo = Some(String::new());
856     /// foo.unwrap_or_default();
857     /// ```
858     #[clippy::version = "pre 1.29.0"]
859     pub OR_FUN_CALL,
860     perf,
861     "using any `*or` method with a function call, which suggests `*or_else`"
862 }
863
864 declare_clippy_lint! {
865     /// ### What it does
866     /// Checks for `.or(…).unwrap()` calls to Options and Results.
867     ///
868     /// ### Why is this bad?
869     /// You should use `.unwrap_or(…)` instead for clarity.
870     ///
871     /// ### Example
872     /// ```rust
873     /// # let fallback = "fallback";
874     /// // Result
875     /// # type Error = &'static str;
876     /// # let result: Result<&str, Error> = Err("error");
877     /// let value = result.or::<Error>(Ok(fallback)).unwrap();
878     ///
879     /// // Option
880     /// # let option: Option<&str> = None;
881     /// let value = option.or(Some(fallback)).unwrap();
882     /// ```
883     /// Use instead:
884     /// ```rust
885     /// # let fallback = "fallback";
886     /// // Result
887     /// # let result: Result<&str, &str> = Err("error");
888     /// let value = result.unwrap_or(fallback);
889     ///
890     /// // Option
891     /// # let option: Option<&str> = None;
892     /// let value = option.unwrap_or(fallback);
893     /// ```
894     #[clippy::version = "1.61.0"]
895     pub OR_THEN_UNWRAP,
896     complexity,
897     "checks for `.or(…).unwrap()` calls to Options and Results."
898 }
899
900 declare_clippy_lint! {
901     /// ### What it does
902     /// Checks for calls to `.expect(&format!(...))`, `.expect(foo(..))`,
903     /// etc., and suggests to use `unwrap_or_else` instead
904     ///
905     /// ### Why is this bad?
906     /// The function will always be called.
907     ///
908     /// ### Known problems
909     /// If the function has side-effects, not calling it will
910     /// change the semantics of the program, but you shouldn't rely on that anyway.
911     ///
912     /// ### Example
913     /// ```rust
914     /// # let foo = Some(String::new());
915     /// # let err_code = "418";
916     /// # let err_msg = "I'm a teapot";
917     /// foo.expect(&format!("Err {}: {}", err_code, err_msg));
918     ///
919     /// // or
920     ///
921     /// # let foo = Some(String::new());
922     /// foo.expect(format!("Err {}: {}", err_code, err_msg).as_str());
923     /// ```
924     ///
925     /// Use instead:
926     /// ```rust
927     /// # let foo = Some(String::new());
928     /// # let err_code = "418";
929     /// # let err_msg = "I'm a teapot";
930     /// foo.unwrap_or_else(|| panic!("Err {}: {}", err_code, err_msg));
931     /// ```
932     #[clippy::version = "pre 1.29.0"]
933     pub EXPECT_FUN_CALL,
934     perf,
935     "using any `expect` method with a function call"
936 }
937
938 declare_clippy_lint! {
939     /// ### What it does
940     /// Checks for usage of `.clone()` on a `Copy` type.
941     ///
942     /// ### Why is this bad?
943     /// The only reason `Copy` types implement `Clone` is for
944     /// generics, not for using the `clone` method on a concrete type.
945     ///
946     /// ### Example
947     /// ```rust
948     /// 42u64.clone();
949     /// ```
950     #[clippy::version = "pre 1.29.0"]
951     pub CLONE_ON_COPY,
952     complexity,
953     "using `clone` on a `Copy` type"
954 }
955
956 declare_clippy_lint! {
957     /// ### What it does
958     /// Checks for usage of `.clone()` on a ref-counted pointer,
959     /// (`Rc`, `Arc`, `rc::Weak`, or `sync::Weak`), and suggests calling Clone via unified
960     /// function syntax instead (e.g., `Rc::clone(foo)`).
961     ///
962     /// ### Why is this bad?
963     /// Calling '.clone()' on an Rc, Arc, or Weak
964     /// can obscure the fact that only the pointer is being cloned, not the underlying
965     /// data.
966     ///
967     /// ### Example
968     /// ```rust
969     /// # use std::rc::Rc;
970     /// let x = Rc::new(1);
971     ///
972     /// x.clone();
973     /// ```
974     ///
975     /// Use instead:
976     /// ```rust
977     /// # use std::rc::Rc;
978     /// # let x = Rc::new(1);
979     /// Rc::clone(&x);
980     /// ```
981     #[clippy::version = "pre 1.29.0"]
982     pub CLONE_ON_REF_PTR,
983     restriction,
984     "using 'clone' on a ref-counted pointer"
985 }
986
987 declare_clippy_lint! {
988     /// ### What it does
989     /// Checks for usage of `.clone()` on an `&&T`.
990     ///
991     /// ### Why is this bad?
992     /// Cloning an `&&T` copies the inner `&T`, instead of
993     /// cloning the underlying `T`.
994     ///
995     /// ### Example
996     /// ```rust
997     /// fn main() {
998     ///     let x = vec![1];
999     ///     let y = &&x;
1000     ///     let z = y.clone();
1001     ///     println!("{:p} {:p}", *y, z); // prints out the same pointer
1002     /// }
1003     /// ```
1004     #[clippy::version = "pre 1.29.0"]
1005     pub CLONE_DOUBLE_REF,
1006     correctness,
1007     "using `clone` on `&&T`"
1008 }
1009
1010 declare_clippy_lint! {
1011     /// ### What it does
1012     /// Checks for usage of `.to_string()` on an `&&T` where
1013     /// `T` implements `ToString` directly (like `&&str` or `&&String`).
1014     ///
1015     /// ### Why is this bad?
1016     /// This bypasses the specialized implementation of
1017     /// `ToString` and instead goes through the more expensive string formatting
1018     /// facilities.
1019     ///
1020     /// ### Example
1021     /// ```rust
1022     /// // Generic implementation for `T: Display` is used (slow)
1023     /// ["foo", "bar"].iter().map(|s| s.to_string());
1024     ///
1025     /// // OK, the specialized impl is used
1026     /// ["foo", "bar"].iter().map(|&s| s.to_string());
1027     /// ```
1028     #[clippy::version = "1.40.0"]
1029     pub INEFFICIENT_TO_STRING,
1030     pedantic,
1031     "using `to_string` on `&&T` where `T: ToString`"
1032 }
1033
1034 declare_clippy_lint! {
1035     /// ### What it does
1036     /// Checks for `new` not returning a type that contains `Self`.
1037     ///
1038     /// ### Why is this bad?
1039     /// As a convention, `new` methods are used to make a new
1040     /// instance of a type.
1041     ///
1042     /// ### Example
1043     /// In an impl block:
1044     /// ```rust
1045     /// # struct Foo;
1046     /// # struct NotAFoo;
1047     /// impl Foo {
1048     ///     fn new() -> NotAFoo {
1049     /// # NotAFoo
1050     ///     }
1051     /// }
1052     /// ```
1053     ///
1054     /// ```rust
1055     /// # struct Foo;
1056     /// struct Bar(Foo);
1057     /// impl Foo {
1058     ///     // Bad. The type name must contain `Self`
1059     ///     fn new() -> Bar {
1060     /// # Bar(Foo)
1061     ///     }
1062     /// }
1063     /// ```
1064     ///
1065     /// ```rust
1066     /// # struct Foo;
1067     /// # struct FooError;
1068     /// impl Foo {
1069     ///     // Good. Return type contains `Self`
1070     ///     fn new() -> Result<Foo, FooError> {
1071     /// # Ok(Foo)
1072     ///     }
1073     /// }
1074     /// ```
1075     ///
1076     /// Or in a trait definition:
1077     /// ```rust
1078     /// pub trait Trait {
1079     ///     // Bad. The type name must contain `Self`
1080     ///     fn new();
1081     /// }
1082     /// ```
1083     ///
1084     /// ```rust
1085     /// pub trait Trait {
1086     ///     // Good. Return type contains `Self`
1087     ///     fn new() -> Self;
1088     /// }
1089     /// ```
1090     #[clippy::version = "pre 1.29.0"]
1091     pub NEW_RET_NO_SELF,
1092     style,
1093     "not returning type containing `Self` in a `new` method"
1094 }
1095
1096 declare_clippy_lint! {
1097     /// ### What it does
1098     /// Checks for string methods that receive a single-character
1099     /// `str` as an argument, e.g., `_.split("x")`.
1100     ///
1101     /// ### Why is this bad?
1102     /// Performing these methods using a `char` is faster than
1103     /// using a `str`.
1104     ///
1105     /// ### Known problems
1106     /// Does not catch multi-byte unicode characters.
1107     ///
1108     /// ### Example
1109     /// ```rust,ignore
1110     /// _.split("x");
1111     /// ```
1112     ///
1113     /// Use instead:
1114     /// ```rust,ignore
1115     /// _.split('x');
1116     /// ```
1117     #[clippy::version = "pre 1.29.0"]
1118     pub SINGLE_CHAR_PATTERN,
1119     perf,
1120     "using a single-character str where a char could be used, e.g., `_.split(\"x\")`"
1121 }
1122
1123 declare_clippy_lint! {
1124     /// ### What it does
1125     /// Checks for calling `.step_by(0)` on iterators which panics.
1126     ///
1127     /// ### Why is this bad?
1128     /// This very much looks like an oversight. Use `panic!()` instead if you
1129     /// actually intend to panic.
1130     ///
1131     /// ### Example
1132     /// ```rust,should_panic
1133     /// for x in (0..100).step_by(0) {
1134     ///     //..
1135     /// }
1136     /// ```
1137     #[clippy::version = "pre 1.29.0"]
1138     pub ITERATOR_STEP_BY_ZERO,
1139     correctness,
1140     "using `Iterator::step_by(0)`, which will panic at runtime"
1141 }
1142
1143 declare_clippy_lint! {
1144     /// ### What it does
1145     /// Checks for indirect collection of populated `Option`
1146     ///
1147     /// ### Why is this bad?
1148     /// `Option` is like a collection of 0-1 things, so `flatten`
1149     /// automatically does this without suspicious-looking `unwrap` calls.
1150     ///
1151     /// ### Example
1152     /// ```rust
1153     /// let _ = std::iter::empty::<Option<i32>>().filter(Option::is_some).map(Option::unwrap);
1154     /// ```
1155     /// Use instead:
1156     /// ```rust
1157     /// let _ = std::iter::empty::<Option<i32>>().flatten();
1158     /// ```
1159     #[clippy::version = "1.53.0"]
1160     pub OPTION_FILTER_MAP,
1161     complexity,
1162     "filtering `Option` for `Some` then force-unwrapping, which can be one type-safe operation"
1163 }
1164
1165 declare_clippy_lint! {
1166     /// ### What it does
1167     /// Checks for the use of `iter.nth(0)`.
1168     ///
1169     /// ### Why is this bad?
1170     /// `iter.next()` is equivalent to
1171     /// `iter.nth(0)`, as they both consume the next element,
1172     ///  but is more readable.
1173     ///
1174     /// ### Example
1175     /// ```rust
1176     /// # use std::collections::HashSet;
1177     /// # let mut s = HashSet::new();
1178     /// # s.insert(1);
1179     /// let x = s.iter().nth(0);
1180     /// ```
1181     ///
1182     /// Use instead:
1183     /// ```rust
1184     /// # use std::collections::HashSet;
1185     /// # let mut s = HashSet::new();
1186     /// # s.insert(1);
1187     /// let x = s.iter().next();
1188     /// ```
1189     #[clippy::version = "1.42.0"]
1190     pub ITER_NTH_ZERO,
1191     style,
1192     "replace `iter.nth(0)` with `iter.next()`"
1193 }
1194
1195 declare_clippy_lint! {
1196     /// ### What it does
1197     /// Checks for use of `.iter().nth()` (and the related
1198     /// `.iter_mut().nth()`) on standard library types with *O*(1) element access.
1199     ///
1200     /// ### Why is this bad?
1201     /// `.get()` and `.get_mut()` are more efficient and more
1202     /// readable.
1203     ///
1204     /// ### Example
1205     /// ```rust
1206     /// let some_vec = vec![0, 1, 2, 3];
1207     /// let bad_vec = some_vec.iter().nth(3);
1208     /// let bad_slice = &some_vec[..].iter().nth(3);
1209     /// ```
1210     /// The correct use would be:
1211     /// ```rust
1212     /// let some_vec = vec![0, 1, 2, 3];
1213     /// let bad_vec = some_vec.get(3);
1214     /// let bad_slice = &some_vec[..].get(3);
1215     /// ```
1216     #[clippy::version = "pre 1.29.0"]
1217     pub ITER_NTH,
1218     perf,
1219     "using `.iter().nth()` on a standard library type with O(1) element access"
1220 }
1221
1222 declare_clippy_lint! {
1223     /// ### What it does
1224     /// Checks for use of `.skip(x).next()` on iterators.
1225     ///
1226     /// ### Why is this bad?
1227     /// `.nth(x)` is cleaner
1228     ///
1229     /// ### Example
1230     /// ```rust
1231     /// let some_vec = vec![0, 1, 2, 3];
1232     /// let bad_vec = some_vec.iter().skip(3).next();
1233     /// let bad_slice = &some_vec[..].iter().skip(3).next();
1234     /// ```
1235     /// The correct use would be:
1236     /// ```rust
1237     /// let some_vec = vec![0, 1, 2, 3];
1238     /// let bad_vec = some_vec.iter().nth(3);
1239     /// let bad_slice = &some_vec[..].iter().nth(3);
1240     /// ```
1241     #[clippy::version = "pre 1.29.0"]
1242     pub ITER_SKIP_NEXT,
1243     style,
1244     "using `.skip(x).next()` on an iterator"
1245 }
1246
1247 declare_clippy_lint! {
1248     /// ### What it does
1249     /// Checks for use of `.drain(..)` on `Vec` and `VecDeque` for iteration.
1250     ///
1251     /// ### Why is this bad?
1252     /// `.into_iter()` is simpler with better performance.
1253     ///
1254     /// ### Example
1255     /// ```rust
1256     /// # use std::collections::HashSet;
1257     /// let mut foo = vec![0, 1, 2, 3];
1258     /// let bar: HashSet<usize> = foo.drain(..).collect();
1259     /// ```
1260     /// Use instead:
1261     /// ```rust
1262     /// # use std::collections::HashSet;
1263     /// let foo = vec![0, 1, 2, 3];
1264     /// let bar: HashSet<usize> = foo.into_iter().collect();
1265     /// ```
1266     #[clippy::version = "1.61.0"]
1267     pub ITER_WITH_DRAIN,
1268     nursery,
1269     "replace `.drain(..)` with `.into_iter()`"
1270 }
1271
1272 declare_clippy_lint! {
1273     /// ### What it does
1274     /// Checks for using `x.get(x.len() - 1)` instead of
1275     /// `x.last()`.
1276     ///
1277     /// ### Why is this bad?
1278     /// Using `x.last()` is easier to read and has the same
1279     /// result.
1280     ///
1281     /// Note that using `x[x.len() - 1]` is semantically different from
1282     /// `x.last()`.  Indexing into the array will panic on out-of-bounds
1283     /// accesses, while `x.get()` and `x.last()` will return `None`.
1284     ///
1285     /// There is another lint (get_unwrap) that covers the case of using
1286     /// `x.get(index).unwrap()` instead of `x[index]`.
1287     ///
1288     /// ### Example
1289     /// ```rust
1290     /// let x = vec![2, 3, 5];
1291     /// let last_element = x.get(x.len() - 1);
1292     /// ```
1293     ///
1294     /// Use instead:
1295     /// ```rust
1296     /// let x = vec![2, 3, 5];
1297     /// let last_element = x.last();
1298     /// ```
1299     #[clippy::version = "1.37.0"]
1300     pub GET_LAST_WITH_LEN,
1301     complexity,
1302     "Using `x.get(x.len() - 1)` when `x.last()` is correct and simpler"
1303 }
1304
1305 declare_clippy_lint! {
1306     /// ### What it does
1307     /// Checks for use of `.get().unwrap()` (or
1308     /// `.get_mut().unwrap`) on a standard library type which implements `Index`
1309     ///
1310     /// ### Why is this bad?
1311     /// Using the Index trait (`[]`) is more clear and more
1312     /// concise.
1313     ///
1314     /// ### Known problems
1315     /// Not a replacement for error handling: Using either
1316     /// `.unwrap()` or the Index trait (`[]`) carries the risk of causing a `panic`
1317     /// if the value being accessed is `None`. If the use of `.get().unwrap()` is a
1318     /// temporary placeholder for dealing with the `Option` type, then this does
1319     /// not mitigate the need for error handling. If there is a chance that `.get()`
1320     /// will be `None` in your program, then it is advisable that the `None` case
1321     /// is handled in a future refactor instead of using `.unwrap()` or the Index
1322     /// trait.
1323     ///
1324     /// ### Example
1325     /// ```rust
1326     /// let mut some_vec = vec![0, 1, 2, 3];
1327     /// let last = some_vec.get(3).unwrap();
1328     /// *some_vec.get_mut(0).unwrap() = 1;
1329     /// ```
1330     /// The correct use would be:
1331     /// ```rust
1332     /// let mut some_vec = vec![0, 1, 2, 3];
1333     /// let last = some_vec[3];
1334     /// some_vec[0] = 1;
1335     /// ```
1336     #[clippy::version = "pre 1.29.0"]
1337     pub GET_UNWRAP,
1338     restriction,
1339     "using `.get().unwrap()` or `.get_mut().unwrap()` when using `[]` would work instead"
1340 }
1341
1342 declare_clippy_lint! {
1343     /// ### What it does
1344     /// Checks for occurrences where one vector gets extended instead of append
1345     ///
1346     /// ### Why is this bad?
1347     /// Using `append` instead of `extend` is more concise and faster
1348     ///
1349     /// ### Example
1350     /// ```rust
1351     /// let mut a = vec![1, 2, 3];
1352     /// let mut b = vec![4, 5, 6];
1353     ///
1354     /// a.extend(b.drain(..));
1355     /// ```
1356     ///
1357     /// Use instead:
1358     /// ```rust
1359     /// let mut a = vec![1, 2, 3];
1360     /// let mut b = vec![4, 5, 6];
1361     ///
1362     /// a.append(&mut b);
1363     /// ```
1364     #[clippy::version = "1.55.0"]
1365     pub EXTEND_WITH_DRAIN,
1366     perf,
1367     "using vec.append(&mut vec) to move the full range of a vector to another"
1368 }
1369
1370 declare_clippy_lint! {
1371     /// ### What it does
1372     /// Checks for the use of `.extend(s.chars())` where s is a
1373     /// `&str` or `String`.
1374     ///
1375     /// ### Why is this bad?
1376     /// `.push_str(s)` is clearer
1377     ///
1378     /// ### Example
1379     /// ```rust
1380     /// let abc = "abc";
1381     /// let def = String::from("def");
1382     /// let mut s = String::new();
1383     /// s.extend(abc.chars());
1384     /// s.extend(def.chars());
1385     /// ```
1386     /// The correct use would be:
1387     /// ```rust
1388     /// let abc = "abc";
1389     /// let def = String::from("def");
1390     /// let mut s = String::new();
1391     /// s.push_str(abc);
1392     /// s.push_str(&def);
1393     /// ```
1394     #[clippy::version = "pre 1.29.0"]
1395     pub STRING_EXTEND_CHARS,
1396     style,
1397     "using `x.extend(s.chars())` where s is a `&str` or `String`"
1398 }
1399
1400 declare_clippy_lint! {
1401     /// ### What it does
1402     /// Checks for the use of `.cloned().collect()` on slice to
1403     /// create a `Vec`.
1404     ///
1405     /// ### Why is this bad?
1406     /// `.to_vec()` is clearer
1407     ///
1408     /// ### Example
1409     /// ```rust
1410     /// let s = [1, 2, 3, 4, 5];
1411     /// let s2: Vec<isize> = s[..].iter().cloned().collect();
1412     /// ```
1413     /// The better use would be:
1414     /// ```rust
1415     /// let s = [1, 2, 3, 4, 5];
1416     /// let s2: Vec<isize> = s.to_vec();
1417     /// ```
1418     #[clippy::version = "pre 1.29.0"]
1419     pub ITER_CLONED_COLLECT,
1420     style,
1421     "using `.cloned().collect()` on slice to create a `Vec`"
1422 }
1423
1424 declare_clippy_lint! {
1425     /// ### What it does
1426     /// Checks for usage of `_.chars().last()` or
1427     /// `_.chars().next_back()` on a `str` to check if it ends with a given char.
1428     ///
1429     /// ### Why is this bad?
1430     /// Readability, this can be written more concisely as
1431     /// `_.ends_with(_)`.
1432     ///
1433     /// ### Example
1434     /// ```rust
1435     /// # let name = "_";
1436     /// name.chars().last() == Some('_') || name.chars().next_back() == Some('-');
1437     /// ```
1438     ///
1439     /// Use instead:
1440     /// ```rust
1441     /// # let name = "_";
1442     /// name.ends_with('_') || name.ends_with('-');
1443     /// ```
1444     #[clippy::version = "pre 1.29.0"]
1445     pub CHARS_LAST_CMP,
1446     style,
1447     "using `.chars().last()` or `.chars().next_back()` to check if a string ends with a char"
1448 }
1449
1450 declare_clippy_lint! {
1451     /// ### What it does
1452     /// Checks for usage of `.as_ref()` or `.as_mut()` where the
1453     /// types before and after the call are the same.
1454     ///
1455     /// ### Why is this bad?
1456     /// The call is unnecessary.
1457     ///
1458     /// ### Example
1459     /// ```rust
1460     /// # fn do_stuff(x: &[i32]) {}
1461     /// let x: &[i32] = &[1, 2, 3, 4, 5];
1462     /// do_stuff(x.as_ref());
1463     /// ```
1464     /// The correct use would be:
1465     /// ```rust
1466     /// # fn do_stuff(x: &[i32]) {}
1467     /// let x: &[i32] = &[1, 2, 3, 4, 5];
1468     /// do_stuff(x);
1469     /// ```
1470     #[clippy::version = "pre 1.29.0"]
1471     pub USELESS_ASREF,
1472     complexity,
1473     "using `as_ref` where the types before and after the call are the same"
1474 }
1475
1476 declare_clippy_lint! {
1477     /// ### What it does
1478     /// Checks for using `fold` when a more succinct alternative exists.
1479     /// Specifically, this checks for `fold`s which could be replaced by `any`, `all`,
1480     /// `sum` or `product`.
1481     ///
1482     /// ### Why is this bad?
1483     /// Readability.
1484     ///
1485     /// ### Example
1486     /// ```rust
1487     /// # #[allow(unused)]
1488     /// (0..3).fold(false, |acc, x| acc || x > 2);
1489     /// ```
1490     ///
1491     /// Use instead:
1492     /// ```rust
1493     /// (0..3).any(|x| x > 2);
1494     /// ```
1495     #[clippy::version = "pre 1.29.0"]
1496     pub UNNECESSARY_FOLD,
1497     style,
1498     "using `fold` when a more succinct alternative exists"
1499 }
1500
1501 declare_clippy_lint! {
1502     /// ### What it does
1503     /// Checks for `filter_map` calls that could be replaced by `filter` or `map`.
1504     /// More specifically it checks if the closure provided is only performing one of the
1505     /// filter or map operations and suggests the appropriate option.
1506     ///
1507     /// ### Why is this bad?
1508     /// Complexity. The intent is also clearer if only a single
1509     /// operation is being performed.
1510     ///
1511     /// ### Example
1512     /// ```rust
1513     /// let _ = (0..3).filter_map(|x| if x > 2 { Some(x) } else { None });
1514     ///
1515     /// // As there is no transformation of the argument this could be written as:
1516     /// let _ = (0..3).filter(|&x| x > 2);
1517     /// ```
1518     ///
1519     /// ```rust
1520     /// let _ = (0..4).filter_map(|x| Some(x + 1));
1521     ///
1522     /// // As there is no conditional check on the argument this could be written as:
1523     /// let _ = (0..4).map(|x| x + 1);
1524     /// ```
1525     #[clippy::version = "1.31.0"]
1526     pub UNNECESSARY_FILTER_MAP,
1527     complexity,
1528     "using `filter_map` when a more succinct alternative exists"
1529 }
1530
1531 declare_clippy_lint! {
1532     /// ### What it does
1533     /// Checks for `find_map` calls that could be replaced by `find` or `map`. More
1534     /// specifically it checks if the closure provided is only performing one of the
1535     /// find or map operations and suggests the appropriate option.
1536     ///
1537     /// ### Why is this bad?
1538     /// Complexity. The intent is also clearer if only a single
1539     /// operation is being performed.
1540     ///
1541     /// ### Example
1542     /// ```rust
1543     /// let _ = (0..3).find_map(|x| if x > 2 { Some(x) } else { None });
1544     ///
1545     /// // As there is no transformation of the argument this could be written as:
1546     /// let _ = (0..3).find(|&x| x > 2);
1547     /// ```
1548     ///
1549     /// ```rust
1550     /// let _ = (0..4).find_map(|x| Some(x + 1));
1551     ///
1552     /// // As there is no conditional check on the argument this could be written as:
1553     /// let _ = (0..4).map(|x| x + 1).next();
1554     /// ```
1555     #[clippy::version = "1.61.0"]
1556     pub UNNECESSARY_FIND_MAP,
1557     complexity,
1558     "using `find_map` when a more succinct alternative exists"
1559 }
1560
1561 declare_clippy_lint! {
1562     /// ### What it does
1563     /// Checks for `into_iter` calls on references which should be replaced by `iter`
1564     /// or `iter_mut`.
1565     ///
1566     /// ### Why is this bad?
1567     /// Readability. Calling `into_iter` on a reference will not move out its
1568     /// content into the resulting iterator, which is confusing. It is better just call `iter` or
1569     /// `iter_mut` directly.
1570     ///
1571     /// ### Example
1572     /// ```rust
1573     /// # let vec = vec![3, 4, 5];
1574     /// (&vec).into_iter();
1575     /// ```
1576     ///
1577     /// Use instead:
1578     /// ```rust
1579     /// # let vec = vec![3, 4, 5];
1580     /// (&vec).iter();
1581     /// ```
1582     #[clippy::version = "1.32.0"]
1583     pub INTO_ITER_ON_REF,
1584     style,
1585     "using `.into_iter()` on a reference"
1586 }
1587
1588 declare_clippy_lint! {
1589     /// ### What it does
1590     /// Checks for calls to `map` followed by a `count`.
1591     ///
1592     /// ### Why is this bad?
1593     /// It looks suspicious. Maybe `map` was confused with `filter`.
1594     /// If the `map` call is intentional, this should be rewritten
1595     /// using `inspect`. Or, if you intend to drive the iterator to
1596     /// completion, you can just use `for_each` instead.
1597     ///
1598     /// ### Example
1599     /// ```rust
1600     /// let _ = (0..3).map(|x| x + 2).count();
1601     /// ```
1602     #[clippy::version = "1.39.0"]
1603     pub SUSPICIOUS_MAP,
1604     suspicious,
1605     "suspicious usage of map"
1606 }
1607
1608 declare_clippy_lint! {
1609     /// ### What it does
1610     /// Checks for `MaybeUninit::uninit().assume_init()`.
1611     ///
1612     /// ### Why is this bad?
1613     /// For most types, this is undefined behavior.
1614     ///
1615     /// ### Known problems
1616     /// For now, we accept empty tuples and tuples / arrays
1617     /// of `MaybeUninit`. There may be other types that allow uninitialized
1618     /// data, but those are not yet rigorously defined.
1619     ///
1620     /// ### Example
1621     /// ```rust
1622     /// // Beware the UB
1623     /// use std::mem::MaybeUninit;
1624     ///
1625     /// let _: usize = unsafe { MaybeUninit::uninit().assume_init() };
1626     /// ```
1627     ///
1628     /// Note that the following is OK:
1629     ///
1630     /// ```rust
1631     /// use std::mem::MaybeUninit;
1632     ///
1633     /// let _: [MaybeUninit<bool>; 5] = unsafe {
1634     ///     MaybeUninit::uninit().assume_init()
1635     /// };
1636     /// ```
1637     #[clippy::version = "1.39.0"]
1638     pub UNINIT_ASSUMED_INIT,
1639     correctness,
1640     "`MaybeUninit::uninit().assume_init()`"
1641 }
1642
1643 declare_clippy_lint! {
1644     /// ### What it does
1645     /// Checks for `.checked_add/sub(x).unwrap_or(MAX/MIN)`.
1646     ///
1647     /// ### Why is this bad?
1648     /// These can be written simply with `saturating_add/sub` methods.
1649     ///
1650     /// ### Example
1651     /// ```rust
1652     /// # let y: u32 = 0;
1653     /// # let x: u32 = 100;
1654     /// let add = x.checked_add(y).unwrap_or(u32::MAX);
1655     /// let sub = x.checked_sub(y).unwrap_or(u32::MIN);
1656     /// ```
1657     ///
1658     /// can be written using dedicated methods for saturating addition/subtraction as:
1659     ///
1660     /// ```rust
1661     /// # let y: u32 = 0;
1662     /// # let x: u32 = 100;
1663     /// let add = x.saturating_add(y);
1664     /// let sub = x.saturating_sub(y);
1665     /// ```
1666     #[clippy::version = "1.39.0"]
1667     pub MANUAL_SATURATING_ARITHMETIC,
1668     style,
1669     "`.checked_add/sub(x).unwrap_or(MAX/MIN)`"
1670 }
1671
1672 declare_clippy_lint! {
1673     /// ### What it does
1674     /// Checks for `offset(_)`, `wrapping_`{`add`, `sub`}, etc. on raw pointers to
1675     /// zero-sized types
1676     ///
1677     /// ### Why is this bad?
1678     /// This is a no-op, and likely unintended
1679     ///
1680     /// ### Example
1681     /// ```rust
1682     /// unsafe { (&() as *const ()).offset(1) };
1683     /// ```
1684     #[clippy::version = "1.41.0"]
1685     pub ZST_OFFSET,
1686     correctness,
1687     "Check for offset calculations on raw pointers to zero-sized types"
1688 }
1689
1690 declare_clippy_lint! {
1691     /// ### What it does
1692     /// Checks for `FileType::is_file()`.
1693     ///
1694     /// ### Why is this bad?
1695     /// When people testing a file type with `FileType::is_file`
1696     /// they are testing whether a path is something they can get bytes from. But
1697     /// `is_file` doesn't cover special file types in unix-like systems, and doesn't cover
1698     /// symlink in windows. Using `!FileType::is_dir()` is a better way to that intention.
1699     ///
1700     /// ### Example
1701     /// ```rust
1702     /// # || {
1703     /// let metadata = std::fs::metadata("foo.txt")?;
1704     /// let filetype = metadata.file_type();
1705     ///
1706     /// if filetype.is_file() {
1707     ///     // read file
1708     /// }
1709     /// # Ok::<_, std::io::Error>(())
1710     /// # };
1711     /// ```
1712     ///
1713     /// should be written as:
1714     ///
1715     /// ```rust
1716     /// # || {
1717     /// let metadata = std::fs::metadata("foo.txt")?;
1718     /// let filetype = metadata.file_type();
1719     ///
1720     /// if !filetype.is_dir() {
1721     ///     // read file
1722     /// }
1723     /// # Ok::<_, std::io::Error>(())
1724     /// # };
1725     /// ```
1726     #[clippy::version = "1.42.0"]
1727     pub FILETYPE_IS_FILE,
1728     restriction,
1729     "`FileType::is_file` is not recommended to test for readable file type"
1730 }
1731
1732 declare_clippy_lint! {
1733     /// ### What it does
1734     /// Checks for usage of `_.as_ref().map(Deref::deref)` or its aliases (such as String::as_str).
1735     ///
1736     /// ### Why is this bad?
1737     /// Readability, this can be written more concisely as
1738     /// `_.as_deref()`.
1739     ///
1740     /// ### Example
1741     /// ```rust
1742     /// # let opt = Some("".to_string());
1743     /// opt.as_ref().map(String::as_str)
1744     /// # ;
1745     /// ```
1746     /// Can be written as
1747     /// ```rust
1748     /// # let opt = Some("".to_string());
1749     /// opt.as_deref()
1750     /// # ;
1751     /// ```
1752     #[clippy::version = "1.42.0"]
1753     pub OPTION_AS_REF_DEREF,
1754     complexity,
1755     "using `as_ref().map(Deref::deref)`, which is more succinctly expressed as `as_deref()`"
1756 }
1757
1758 declare_clippy_lint! {
1759     /// ### What it does
1760     /// Checks for usage of `iter().next()` on a Slice or an Array
1761     ///
1762     /// ### Why is this bad?
1763     /// These can be shortened into `.get()`
1764     ///
1765     /// ### Example
1766     /// ```rust
1767     /// # let a = [1, 2, 3];
1768     /// # let b = vec![1, 2, 3];
1769     /// a[2..].iter().next();
1770     /// b.iter().next();
1771     /// ```
1772     /// should be written as:
1773     /// ```rust
1774     /// # let a = [1, 2, 3];
1775     /// # let b = vec![1, 2, 3];
1776     /// a.get(2);
1777     /// b.get(0);
1778     /// ```
1779     #[clippy::version = "1.46.0"]
1780     pub ITER_NEXT_SLICE,
1781     style,
1782     "using `.iter().next()` on a sliced array, which can be shortened to just `.get()`"
1783 }
1784
1785 declare_clippy_lint! {
1786     /// ### What it does
1787     /// Warns when using `push_str`/`insert_str` with a single-character string literal
1788     /// where `push`/`insert` with a `char` would work fine.
1789     ///
1790     /// ### Why is this bad?
1791     /// It's less clear that we are pushing a single character.
1792     ///
1793     /// ### Example
1794     /// ```rust
1795     /// # let mut string = String::new();
1796     /// string.insert_str(0, "R");
1797     /// string.push_str("R");
1798     /// ```
1799     ///
1800     /// Use instead:
1801     /// ```rust
1802     /// # let mut string = String::new();
1803     /// string.insert(0, 'R');
1804     /// string.push('R');
1805     /// ```
1806     #[clippy::version = "1.49.0"]
1807     pub SINGLE_CHAR_ADD_STR,
1808     style,
1809     "`push_str()` or `insert_str()` used with a single-character string literal as parameter"
1810 }
1811
1812 declare_clippy_lint! {
1813     /// ### What it does
1814     /// As the counterpart to `or_fun_call`, this lint looks for unnecessary
1815     /// lazily evaluated closures on `Option` and `Result`.
1816     ///
1817     /// This lint suggests changing the following functions, when eager evaluation results in
1818     /// simpler code:
1819     ///  - `unwrap_or_else` to `unwrap_or`
1820     ///  - `and_then` to `and`
1821     ///  - `or_else` to `or`
1822     ///  - `get_or_insert_with` to `get_or_insert`
1823     ///  - `ok_or_else` to `ok_or`
1824     ///
1825     /// ### Why is this bad?
1826     /// Using eager evaluation is shorter and simpler in some cases.
1827     ///
1828     /// ### Known problems
1829     /// It is possible, but not recommended for `Deref` and `Index` to have
1830     /// side effects. Eagerly evaluating them can change the semantics of the program.
1831     ///
1832     /// ### Example
1833     /// ```rust
1834     /// // example code where clippy issues a warning
1835     /// let opt: Option<u32> = None;
1836     ///
1837     /// opt.unwrap_or_else(|| 42);
1838     /// ```
1839     /// Use instead:
1840     /// ```rust
1841     /// let opt: Option<u32> = None;
1842     ///
1843     /// opt.unwrap_or(42);
1844     /// ```
1845     #[clippy::version = "1.48.0"]
1846     pub UNNECESSARY_LAZY_EVALUATIONS,
1847     style,
1848     "using unnecessary lazy evaluation, which can be replaced with simpler eager evaluation"
1849 }
1850
1851 declare_clippy_lint! {
1852     /// ### What it does
1853     /// Checks for usage of `_.map(_).collect::<Result<(), _>()`.
1854     ///
1855     /// ### Why is this bad?
1856     /// Using `try_for_each` instead is more readable and idiomatic.
1857     ///
1858     /// ### Example
1859     /// ```rust
1860     /// (0..3).map(|t| Err(t)).collect::<Result<(), _>>();
1861     /// ```
1862     /// Use instead:
1863     /// ```rust
1864     /// (0..3).try_for_each(|t| Err(t));
1865     /// ```
1866     #[clippy::version = "1.49.0"]
1867     pub MAP_COLLECT_RESULT_UNIT,
1868     style,
1869     "using `.map(_).collect::<Result<(),_>()`, which can be replaced with `try_for_each`"
1870 }
1871
1872 declare_clippy_lint! {
1873     /// ### What it does
1874     /// Checks for `from_iter()` function calls on types that implement the `FromIterator`
1875     /// trait.
1876     ///
1877     /// ### Why is this bad?
1878     /// It is recommended style to use collect. See
1879     /// [FromIterator documentation](https://doc.rust-lang.org/std/iter/trait.FromIterator.html)
1880     ///
1881     /// ### Example
1882     /// ```rust
1883     /// let five_fives = std::iter::repeat(5).take(5);
1884     ///
1885     /// let v = Vec::from_iter(five_fives);
1886     ///
1887     /// assert_eq!(v, vec![5, 5, 5, 5, 5]);
1888     /// ```
1889     /// Use instead:
1890     /// ```rust
1891     /// let five_fives = std::iter::repeat(5).take(5);
1892     ///
1893     /// let v: Vec<i32> = five_fives.collect();
1894     ///
1895     /// assert_eq!(v, vec![5, 5, 5, 5, 5]);
1896     /// ```
1897     #[clippy::version = "1.49.0"]
1898     pub FROM_ITER_INSTEAD_OF_COLLECT,
1899     pedantic,
1900     "use `.collect()` instead of `::from_iter()`"
1901 }
1902
1903 declare_clippy_lint! {
1904     /// ### What it does
1905     /// Checks for usage of `inspect().for_each()`.
1906     ///
1907     /// ### Why is this bad?
1908     /// It is the same as performing the computation
1909     /// inside `inspect` at the beginning of the closure in `for_each`.
1910     ///
1911     /// ### Example
1912     /// ```rust
1913     /// [1,2,3,4,5].iter()
1914     /// .inspect(|&x| println!("inspect the number: {}", x))
1915     /// .for_each(|&x| {
1916     ///     assert!(x >= 0);
1917     /// });
1918     /// ```
1919     /// Can be written as
1920     /// ```rust
1921     /// [1,2,3,4,5].iter()
1922     /// .for_each(|&x| {
1923     ///     println!("inspect the number: {}", x);
1924     ///     assert!(x >= 0);
1925     /// });
1926     /// ```
1927     #[clippy::version = "1.51.0"]
1928     pub INSPECT_FOR_EACH,
1929     complexity,
1930     "using `.inspect().for_each()`, which can be replaced with `.for_each()`"
1931 }
1932
1933 declare_clippy_lint! {
1934     /// ### What it does
1935     /// Checks for usage of `filter_map(|x| x)`.
1936     ///
1937     /// ### Why is this bad?
1938     /// Readability, this can be written more concisely by using `flatten`.
1939     ///
1940     /// ### Example
1941     /// ```rust
1942     /// # let iter = vec![Some(1)].into_iter();
1943     /// iter.filter_map(|x| x);
1944     /// ```
1945     /// Use instead:
1946     /// ```rust
1947     /// # let iter = vec![Some(1)].into_iter();
1948     /// iter.flatten();
1949     /// ```
1950     #[clippy::version = "1.52.0"]
1951     pub FILTER_MAP_IDENTITY,
1952     complexity,
1953     "call to `filter_map` where `flatten` is sufficient"
1954 }
1955
1956 declare_clippy_lint! {
1957     /// ### What it does
1958     /// Checks for instances of `map(f)` where `f` is the identity function.
1959     ///
1960     /// ### Why is this bad?
1961     /// It can be written more concisely without the call to `map`.
1962     ///
1963     /// ### Example
1964     /// ```rust
1965     /// let x = [1, 2, 3];
1966     /// let y: Vec<_> = x.iter().map(|x| x).map(|x| 2*x).collect();
1967     /// ```
1968     /// Use instead:
1969     /// ```rust
1970     /// let x = [1, 2, 3];
1971     /// let y: Vec<_> = x.iter().map(|x| 2*x).collect();
1972     /// ```
1973     #[clippy::version = "1.47.0"]
1974     pub MAP_IDENTITY,
1975     complexity,
1976     "using iterator.map(|x| x)"
1977 }
1978
1979 declare_clippy_lint! {
1980     /// ### What it does
1981     /// Checks for the use of `.bytes().nth()`.
1982     ///
1983     /// ### Why is this bad?
1984     /// `.as_bytes().get()` is more efficient and more
1985     /// readable.
1986     ///
1987     /// ### Example
1988     /// ```rust
1989     /// # #[allow(unused)]
1990     /// "Hello".bytes().nth(3);
1991     /// ```
1992     ///
1993     /// Use instead:
1994     /// ```rust
1995     /// # #[allow(unused)]
1996     /// "Hello".as_bytes().get(3);
1997     /// ```
1998     #[clippy::version = "1.52.0"]
1999     pub BYTES_NTH,
2000     style,
2001     "replace `.bytes().nth()` with `.as_bytes().get()`"
2002 }
2003
2004 declare_clippy_lint! {
2005     /// ### What it does
2006     /// Checks for the usage of `_.to_owned()`, `vec.to_vec()`, or similar when calling `_.clone()` would be clearer.
2007     ///
2008     /// ### Why is this bad?
2009     /// These methods do the same thing as `_.clone()` but may be confusing as
2010     /// to why we are calling `to_vec` on something that is already a `Vec` or calling `to_owned` on something that is already owned.
2011     ///
2012     /// ### Example
2013     /// ```rust
2014     /// let a = vec![1, 2, 3];
2015     /// let b = a.to_vec();
2016     /// let c = a.to_owned();
2017     /// ```
2018     /// Use instead:
2019     /// ```rust
2020     /// let a = vec![1, 2, 3];
2021     /// let b = a.clone();
2022     /// let c = a.clone();
2023     /// ```
2024     #[clippy::version = "1.52.0"]
2025     pub IMPLICIT_CLONE,
2026     pedantic,
2027     "implicitly cloning a value by invoking a function on its dereferenced type"
2028 }
2029
2030 declare_clippy_lint! {
2031     /// ### What it does
2032     /// Checks for the use of `.iter().count()`.
2033     ///
2034     /// ### Why is this bad?
2035     /// `.len()` is more efficient and more
2036     /// readable.
2037     ///
2038     /// ### Example
2039     /// ```rust
2040     /// # #![allow(unused)]
2041     /// let some_vec = vec![0, 1, 2, 3];
2042     ///
2043     /// some_vec.iter().count();
2044     /// &some_vec[..].iter().count();
2045     /// ```
2046     ///
2047     /// Use instead:
2048     /// ```rust
2049     /// let some_vec = vec![0, 1, 2, 3];
2050     ///
2051     /// some_vec.len();
2052     /// &some_vec[..].len();
2053     /// ```
2054     #[clippy::version = "1.52.0"]
2055     pub ITER_COUNT,
2056     complexity,
2057     "replace `.iter().count()` with `.len()`"
2058 }
2059
2060 declare_clippy_lint! {
2061     /// ### What it does
2062     /// Checks for the usage of `_.to_owned()`, on a `Cow<'_, _>`.
2063     ///
2064     /// ### Why is this bad?
2065     /// Calling `to_owned()` on a `Cow` creates a clone of the `Cow`
2066     /// itself, without taking ownership of the `Cow` contents (i.e.
2067     /// it's equivalent to calling `Cow::clone`).
2068     /// The similarly named `into_owned` method, on the other hand,
2069     /// clones the `Cow` contents, effectively turning any `Cow::Borrowed`
2070     /// into a `Cow::Owned`.
2071     ///
2072     /// Given the potential ambiguity, consider replacing `to_owned`
2073     /// with `clone` for better readability or, if getting a `Cow::Owned`
2074     /// was the original intent, using `into_owned` instead.
2075     ///
2076     /// ### Example
2077     /// ```rust
2078     /// # use std::borrow::Cow;
2079     /// let s = "Hello world!";
2080     /// let cow = Cow::Borrowed(s);
2081     ///
2082     /// let data = cow.to_owned();
2083     /// assert!(matches!(data, Cow::Borrowed(_)))
2084     /// ```
2085     /// Use instead:
2086     /// ```rust
2087     /// # use std::borrow::Cow;
2088     /// let s = "Hello world!";
2089     /// let cow = Cow::Borrowed(s);
2090     ///
2091     /// let data = cow.clone();
2092     /// assert!(matches!(data, Cow::Borrowed(_)))
2093     /// ```
2094     /// or
2095     /// ```rust
2096     /// # use std::borrow::Cow;
2097     /// let s = "Hello world!";
2098     /// let cow = Cow::Borrowed(s);
2099     ///
2100     /// let _data: String = cow.into_owned();
2101     /// ```
2102     #[clippy::version = "1.65.0"]
2103     pub SUSPICIOUS_TO_OWNED,
2104     suspicious,
2105     "calls to `to_owned` on a `Cow<'_, _>` might not do what they are expected"
2106 }
2107
2108 declare_clippy_lint! {
2109     /// ### What it does
2110     /// Checks for calls to [`splitn`]
2111     /// (https://doc.rust-lang.org/std/primitive.str.html#method.splitn) and
2112     /// related functions with either zero or one splits.
2113     ///
2114     /// ### Why is this bad?
2115     /// These calls don't actually split the value and are
2116     /// likely to be intended as a different number.
2117     ///
2118     /// ### Example
2119     /// ```rust
2120     /// # let s = "";
2121     /// for x in s.splitn(1, ":") {
2122     ///     // ..
2123     /// }
2124     /// ```
2125     ///
2126     /// Use instead:
2127     /// ```rust
2128     /// # let s = "";
2129     /// for x in s.splitn(2, ":") {
2130     ///     // ..
2131     /// }
2132     /// ```
2133     #[clippy::version = "1.54.0"]
2134     pub SUSPICIOUS_SPLITN,
2135     correctness,
2136     "checks for `.splitn(0, ..)` and `.splitn(1, ..)`"
2137 }
2138
2139 declare_clippy_lint! {
2140     /// ### What it does
2141     /// Checks for manual implementations of `str::repeat`
2142     ///
2143     /// ### Why is this bad?
2144     /// These are both harder to read, as well as less performant.
2145     ///
2146     /// ### Example
2147     /// ```rust
2148     /// let x: String = std::iter::repeat('x').take(10).collect();
2149     /// ```
2150     ///
2151     /// Use instead:
2152     /// ```rust
2153     /// let x: String = "x".repeat(10);
2154     /// ```
2155     #[clippy::version = "1.54.0"]
2156     pub MANUAL_STR_REPEAT,
2157     perf,
2158     "manual implementation of `str::repeat`"
2159 }
2160
2161 declare_clippy_lint! {
2162     /// ### What it does
2163     /// Checks for usages of `str::splitn(2, _)`
2164     ///
2165     /// ### Why is this bad?
2166     /// `split_once` is both clearer in intent and slightly more efficient.
2167     ///
2168     /// ### Example
2169     /// ```rust,ignore
2170     /// let s = "key=value=add";
2171     /// let (key, value) = s.splitn(2, '=').next_tuple()?;
2172     /// let value = s.splitn(2, '=').nth(1)?;
2173     ///
2174     /// let mut parts = s.splitn(2, '=');
2175     /// let key = parts.next()?;
2176     /// let value = parts.next()?;
2177     /// ```
2178     ///
2179     /// Use instead:
2180     /// ```rust,ignore
2181     /// let s = "key=value=add";
2182     /// let (key, value) = s.split_once('=')?;
2183     /// let value = s.split_once('=')?.1;
2184     ///
2185     /// let (key, value) = s.split_once('=')?;
2186     /// ```
2187     ///
2188     /// ### Limitations
2189     /// The multiple statement variant currently only detects `iter.next()?`/`iter.next().unwrap()`
2190     /// in two separate `let` statements that immediately follow the `splitn()`
2191     #[clippy::version = "1.57.0"]
2192     pub MANUAL_SPLIT_ONCE,
2193     complexity,
2194     "replace `.splitn(2, pat)` with `.split_once(pat)`"
2195 }
2196
2197 declare_clippy_lint! {
2198     /// ### What it does
2199     /// Checks for usages of `str::splitn` (or `str::rsplitn`) where using `str::split` would be the same.
2200     /// ### Why is this bad?
2201     /// The function `split` is simpler and there is no performance difference in these cases, considering
2202     /// that both functions return a lazy iterator.
2203     /// ### Example
2204     /// ```rust
2205     /// let str = "key=value=add";
2206     /// let _ = str.splitn(3, '=').next().unwrap();
2207     /// ```
2208     ///
2209     /// Use instead:
2210     /// ```rust
2211     /// let str = "key=value=add";
2212     /// let _ = str.split('=').next().unwrap();
2213     /// ```
2214     #[clippy::version = "1.59.0"]
2215     pub NEEDLESS_SPLITN,
2216     complexity,
2217     "usages of `str::splitn` that can be replaced with `str::split`"
2218 }
2219
2220 declare_clippy_lint! {
2221     /// ### What it does
2222     /// Checks for unnecessary calls to [`ToOwned::to_owned`](https://doc.rust-lang.org/std/borrow/trait.ToOwned.html#tymethod.to_owned)
2223     /// and other `to_owned`-like functions.
2224     ///
2225     /// ### Why is this bad?
2226     /// The unnecessary calls result in useless allocations.
2227     ///
2228     /// ### Known problems
2229     /// `unnecessary_to_owned` can falsely trigger if `IntoIterator::into_iter` is applied to an
2230     /// owned copy of a resource and the resource is later used mutably. See
2231     /// [#8148](https://github.com/rust-lang/rust-clippy/issues/8148).
2232     ///
2233     /// ### Example
2234     /// ```rust
2235     /// let path = std::path::Path::new("x");
2236     /// foo(&path.to_string_lossy().to_string());
2237     /// fn foo(s: &str) {}
2238     /// ```
2239     /// Use instead:
2240     /// ```rust
2241     /// let path = std::path::Path::new("x");
2242     /// foo(&path.to_string_lossy());
2243     /// fn foo(s: &str) {}
2244     /// ```
2245     #[clippy::version = "1.59.0"]
2246     pub UNNECESSARY_TO_OWNED,
2247     perf,
2248     "unnecessary calls to `to_owned`-like functions"
2249 }
2250
2251 declare_clippy_lint! {
2252     /// ### What it does
2253     /// Checks for use of `.collect::<Vec<String>>().join("")` on iterators.
2254     ///
2255     /// ### Why is this bad?
2256     /// `.collect::<String>()` is more concise and might be more performant
2257     ///
2258     /// ### Example
2259     /// ```rust
2260     /// let vector = vec!["hello",  "world"];
2261     /// let output = vector.iter().map(|item| item.to_uppercase()).collect::<Vec<String>>().join("");
2262     /// println!("{}", output);
2263     /// ```
2264     /// The correct use would be:
2265     /// ```rust
2266     /// let vector = vec!["hello",  "world"];
2267     /// let output = vector.iter().map(|item| item.to_uppercase()).collect::<String>();
2268     /// println!("{}", output);
2269     /// ```
2270     /// ### Known problems
2271     /// While `.collect::<String>()` is sometimes more performant, there are cases where
2272     /// using `.collect::<String>()` over `.collect::<Vec<String>>().join("")`
2273     /// will prevent loop unrolling and will result in a negative performance impact.
2274     ///
2275     /// Additionally, differences have been observed between aarch64 and x86_64 assembly output,
2276     /// with aarch64 tending to producing faster assembly in more cases when using `.collect::<String>()`
2277     #[clippy::version = "1.61.0"]
2278     pub UNNECESSARY_JOIN,
2279     pedantic,
2280     "using `.collect::<Vec<String>>().join(\"\")` on an iterator"
2281 }
2282
2283 declare_clippy_lint! {
2284     /// ### What it does
2285     /// Checks for no-op uses of `Option::{as_deref, as_deref_mut}`,
2286     /// for example, `Option<&T>::as_deref()` returns the same type.
2287     ///
2288     /// ### Why is this bad?
2289     /// Redundant code and improving readability.
2290     ///
2291     /// ### Example
2292     /// ```rust
2293     /// let a = Some(&1);
2294     /// let b = a.as_deref(); // goes from Option<&i32> to Option<&i32>
2295     /// ```
2296     ///
2297     /// Use instead:
2298     /// ```rust
2299     /// let a = Some(&1);
2300     /// let b = a;
2301     /// ```
2302     #[clippy::version = "1.57.0"]
2303     pub NEEDLESS_OPTION_AS_DEREF,
2304     complexity,
2305     "no-op use of `deref` or `deref_mut` method to `Option`."
2306 }
2307
2308 declare_clippy_lint! {
2309     /// ### What it does
2310     /// Finds usages of [`char::is_digit`](https://doc.rust-lang.org/stable/std/primitive.char.html#method.is_digit) that
2311     /// can be replaced with [`is_ascii_digit`](https://doc.rust-lang.org/stable/std/primitive.char.html#method.is_ascii_digit) or
2312     /// [`is_ascii_hexdigit`](https://doc.rust-lang.org/stable/std/primitive.char.html#method.is_ascii_hexdigit).
2313     ///
2314     /// ### Why is this bad?
2315     /// `is_digit(..)` is slower and requires specifying the radix.
2316     ///
2317     /// ### Example
2318     /// ```rust
2319     /// let c: char = '6';
2320     /// c.is_digit(10);
2321     /// c.is_digit(16);
2322     /// ```
2323     /// Use instead:
2324     /// ```rust
2325     /// let c: char = '6';
2326     /// c.is_ascii_digit();
2327     /// c.is_ascii_hexdigit();
2328     /// ```
2329     #[clippy::version = "1.62.0"]
2330     pub IS_DIGIT_ASCII_RADIX,
2331     style,
2332     "use of `char::is_digit(..)` with literal radix of 10 or 16"
2333 }
2334
2335 declare_clippy_lint! {
2336     /// ### What it does
2337     /// Checks for calling `take` function after `as_ref`.
2338     ///
2339     /// ### Why is this bad?
2340     /// Redundant code. `take` writes `None` to its argument.
2341     /// In this case the modification is useless as it's a temporary that cannot be read from afterwards.
2342     ///
2343     /// ### Example
2344     /// ```rust
2345     /// let x = Some(3);
2346     /// x.as_ref().take();
2347     /// ```
2348     /// Use instead:
2349     /// ```rust
2350     /// let x = Some(3);
2351     /// x.as_ref();
2352     /// ```
2353     #[clippy::version = "1.62.0"]
2354     pub NEEDLESS_OPTION_TAKE,
2355     complexity,
2356     "using `.as_ref().take()` on a temporary value"
2357 }
2358
2359 declare_clippy_lint! {
2360     /// ### What it does
2361     /// Checks for `replace` statements which have no effect.
2362     ///
2363     /// ### Why is this bad?
2364     /// It's either a mistake or confusing.
2365     ///
2366     /// ### Example
2367     /// ```rust
2368     /// "1234".replace("12", "12");
2369     /// "1234".replacen("12", "12", 1);
2370     /// ```
2371     #[clippy::version = "1.63.0"]
2372     pub NO_EFFECT_REPLACE,
2373     suspicious,
2374     "replace with no effect"
2375 }
2376
2377 declare_clippy_lint! {
2378     /// ### What it does
2379     /// Checks for usages of `.then_some(..).unwrap_or(..)`
2380     ///
2381     /// ### Why is this bad?
2382     /// This can be written more clearly with `if .. else ..`
2383     ///
2384     /// ### Limitations
2385     /// This lint currently only looks for usages of
2386     /// `.then_some(..).unwrap_or(..)`, but will be expanded
2387     /// to account for similar patterns.
2388     ///
2389     /// ### Example
2390     /// ```rust
2391     /// let x = true;
2392     /// x.then_some("a").unwrap_or("b");
2393     /// ```
2394     /// Use instead:
2395     /// ```rust
2396     /// let x = true;
2397     /// if x { "a" } else { "b" };
2398     /// ```
2399     #[clippy::version = "1.64.0"]
2400     pub OBFUSCATED_IF_ELSE,
2401     style,
2402     "use of `.then_some(..).unwrap_or(..)` can be written \
2403     more clearly with `if .. else ..`"
2404 }
2405
2406 declare_clippy_lint! {
2407     /// ### What it does
2408     ///
2409     /// Checks for calls to `iter`, `iter_mut` or `into_iter` on collections containing a single item
2410     ///
2411     /// ### Why is this bad?
2412     ///
2413     /// It is simpler to use the once function from the standard library:
2414     ///
2415     /// ### Example
2416     ///
2417     /// ```rust
2418     /// let a = [123].iter();
2419     /// let b = Some(123).into_iter();
2420     /// ```
2421     /// Use instead:
2422     /// ```rust
2423     /// use std::iter;
2424     /// let a = iter::once(&123);
2425     /// let b = iter::once(123);
2426     /// ```
2427     ///
2428     /// ### Known problems
2429     ///
2430     /// The type of the resulting iterator might become incompatible with its usage
2431     #[clippy::version = "1.65.0"]
2432     pub ITER_ON_SINGLE_ITEMS,
2433     nursery,
2434     "Iterator for array of length 1"
2435 }
2436
2437 declare_clippy_lint! {
2438     /// ### What it does
2439     ///
2440     /// Checks for calls to `iter`, `iter_mut` or `into_iter` on empty collections
2441     ///
2442     /// ### Why is this bad?
2443     ///
2444     /// It is simpler to use the empty function from the standard library:
2445     ///
2446     /// ### Example
2447     ///
2448     /// ```rust
2449     /// use std::{slice, option};
2450     /// let a: slice::Iter<i32> = [].iter();
2451     /// let f: option::IntoIter<i32> = None.into_iter();
2452     /// ```
2453     /// Use instead:
2454     /// ```rust
2455     /// use std::iter;
2456     /// let a: iter::Empty<i32> = iter::empty();
2457     /// let b: iter::Empty<i32> = iter::empty();
2458     /// ```
2459     ///
2460     /// ### Known problems
2461     ///
2462     /// The type of the resulting iterator might become incompatible with its usage
2463     #[clippy::version = "1.65.0"]
2464     pub ITER_ON_EMPTY_COLLECTIONS,
2465     nursery,
2466     "Iterator for empty array"
2467 }
2468
2469 declare_clippy_lint! {
2470     /// ### What it does
2471     /// Checks for naive byte counts
2472     ///
2473     /// ### Why is this bad?
2474     /// The [`bytecount`](https://crates.io/crates/bytecount)
2475     /// crate has methods to count your bytes faster, especially for large slices.
2476     ///
2477     /// ### Known problems
2478     /// If you have predominantly small slices, the
2479     /// `bytecount::count(..)` method may actually be slower. However, if you can
2480     /// ensure that less than 2³²-1 matches arise, the `naive_count_32(..)` can be
2481     /// faster in those cases.
2482     ///
2483     /// ### Example
2484     /// ```rust
2485     /// # let vec = vec![1_u8];
2486     /// let count = vec.iter().filter(|x| **x == 0u8).count();
2487     /// ```
2488     ///
2489     /// Use instead:
2490     /// ```rust,ignore
2491     /// # let vec = vec![1_u8];
2492     /// let count = bytecount::count(&vec, 0u8);
2493     /// ```
2494     #[clippy::version = "pre 1.29.0"]
2495     pub NAIVE_BYTECOUNT,
2496     pedantic,
2497     "use of naive `<slice>.filter(|&x| x == y).count()` to count byte values"
2498 }
2499
2500 declare_clippy_lint! {
2501     /// ### What it does
2502     /// It checks for `str::bytes().count()` and suggests replacing it with
2503     /// `str::len()`.
2504     ///
2505     /// ### Why is this bad?
2506     /// `str::bytes().count()` is longer and may not be as performant as using
2507     /// `str::len()`.
2508     ///
2509     /// ### Example
2510     /// ```rust
2511     /// "hello".bytes().count();
2512     /// String::from("hello").bytes().count();
2513     /// ```
2514     /// Use instead:
2515     /// ```rust
2516     /// "hello".len();
2517     /// String::from("hello").len();
2518     /// ```
2519     #[clippy::version = "1.62.0"]
2520     pub BYTES_COUNT_TO_LEN,
2521     complexity,
2522     "Using `bytes().count()` when `len()` performs the same functionality"
2523 }
2524
2525 declare_clippy_lint! {
2526     /// ### What it does
2527     /// Checks for calls to `ends_with` with possible file extensions
2528     /// and suggests to use a case-insensitive approach instead.
2529     ///
2530     /// ### Why is this bad?
2531     /// `ends_with` is case-sensitive and may not detect files with a valid extension.
2532     ///
2533     /// ### Example
2534     /// ```rust
2535     /// fn is_rust_file(filename: &str) -> bool {
2536     ///     filename.ends_with(".rs")
2537     /// }
2538     /// ```
2539     /// Use instead:
2540     /// ```rust
2541     /// fn is_rust_file(filename: &str) -> bool {
2542     ///     let filename = std::path::Path::new(filename);
2543     ///     filename.extension()
2544     ///         .map_or(false, |ext| ext.eq_ignore_ascii_case("rs"))
2545     /// }
2546     /// ```
2547     #[clippy::version = "1.51.0"]
2548     pub CASE_SENSITIVE_FILE_EXTENSION_COMPARISONS,
2549     pedantic,
2550     "Checks for calls to ends_with with case-sensitive file extensions"
2551 }
2552
2553 declare_clippy_lint! {
2554     /// ### What it does
2555     /// Checks for using `x.get(0)` instead of
2556     /// `x.first()`.
2557     ///
2558     /// ### Why is this bad?
2559     /// Using `x.first()` is easier to read and has the same
2560     /// result.
2561     ///
2562     /// ### Example
2563     /// ```rust
2564     /// let x = vec![2, 3, 5];
2565     /// let first_element = x.get(0);
2566     /// ```
2567     ///
2568     /// Use instead:
2569     /// ```rust
2570     /// let x = vec![2, 3, 5];
2571     /// let first_element = x.first();
2572     /// ```
2573     #[clippy::version = "1.63.0"]
2574     pub GET_FIRST,
2575     style,
2576     "Using `x.get(0)` when `x.first()` is simpler"
2577 }
2578
2579 declare_clippy_lint! {
2580     /// ### What it does
2581     ///
2582     /// Finds patterns that reimplement `Option::ok_or`.
2583     ///
2584     /// ### Why is this bad?
2585     ///
2586     /// Concise code helps focusing on behavior instead of boilerplate.
2587     ///
2588     /// ### Examples
2589     /// ```rust
2590     /// let foo: Option<i32> = None;
2591     /// foo.map_or(Err("error"), |v| Ok(v));
2592     /// ```
2593     ///
2594     /// Use instead:
2595     /// ```rust
2596     /// let foo: Option<i32> = None;
2597     /// foo.ok_or("error");
2598     /// ```
2599     #[clippy::version = "1.49.0"]
2600     pub MANUAL_OK_OR,
2601     pedantic,
2602     "finds patterns that can be encoded more concisely with `Option::ok_or`"
2603 }
2604
2605 declare_clippy_lint! {
2606     /// ### What it does
2607     /// Checks for usage of `map(|x| x.clone())` or
2608     /// dereferencing closures for `Copy` types, on `Iterator` or `Option`,
2609     /// and suggests `cloned()` or `copied()` instead
2610     ///
2611     /// ### Why is this bad?
2612     /// Readability, this can be written more concisely
2613     ///
2614     /// ### Example
2615     /// ```rust
2616     /// let x = vec![42, 43];
2617     /// let y = x.iter();
2618     /// let z = y.map(|i| *i);
2619     /// ```
2620     ///
2621     /// The correct use would be:
2622     ///
2623     /// ```rust
2624     /// let x = vec![42, 43];
2625     /// let y = x.iter();
2626     /// let z = y.cloned();
2627     /// ```
2628     #[clippy::version = "pre 1.29.0"]
2629     pub MAP_CLONE,
2630     style,
2631     "using `iterator.map(|x| x.clone())`, or dereferencing closures for `Copy` types"
2632 }
2633
2634 declare_clippy_lint! {
2635     /// ### What it does
2636     /// Checks for instances of `map_err(|_| Some::Enum)`
2637     ///
2638     /// ### Why is this bad?
2639     /// This `map_err` throws away the original error rather than allowing the enum to contain and report the cause of the error
2640     ///
2641     /// ### Example
2642     /// Before:
2643     /// ```rust
2644     /// use std::fmt;
2645     ///
2646     /// #[derive(Debug)]
2647     /// enum Error {
2648     ///     Indivisible,
2649     ///     Remainder(u8),
2650     /// }
2651     ///
2652     /// impl fmt::Display for Error {
2653     ///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2654     ///         match self {
2655     ///             Error::Indivisible => write!(f, "could not divide input by three"),
2656     ///             Error::Remainder(remainder) => write!(
2657     ///                 f,
2658     ///                 "input is not divisible by three, remainder = {}",
2659     ///                 remainder
2660     ///             ),
2661     ///         }
2662     ///     }
2663     /// }
2664     ///
2665     /// impl std::error::Error for Error {}
2666     ///
2667     /// fn divisible_by_3(input: &str) -> Result<(), Error> {
2668     ///     input
2669     ///         .parse::<i32>()
2670     ///         .map_err(|_| Error::Indivisible)
2671     ///         .map(|v| v % 3)
2672     ///         .and_then(|remainder| {
2673     ///             if remainder == 0 {
2674     ///                 Ok(())
2675     ///             } else {
2676     ///                 Err(Error::Remainder(remainder as u8))
2677     ///             }
2678     ///         })
2679     /// }
2680     ///  ```
2681     ///
2682     ///  After:
2683     ///  ```rust
2684     /// use std::{fmt, num::ParseIntError};
2685     ///
2686     /// #[derive(Debug)]
2687     /// enum Error {
2688     ///     Indivisible(ParseIntError),
2689     ///     Remainder(u8),
2690     /// }
2691     ///
2692     /// impl fmt::Display for Error {
2693     ///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2694     ///         match self {
2695     ///             Error::Indivisible(_) => write!(f, "could not divide input by three"),
2696     ///             Error::Remainder(remainder) => write!(
2697     ///                 f,
2698     ///                 "input is not divisible by three, remainder = {}",
2699     ///                 remainder
2700     ///             ),
2701     ///         }
2702     ///     }
2703     /// }
2704     ///
2705     /// impl std::error::Error for Error {
2706     ///     fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
2707     ///         match self {
2708     ///             Error::Indivisible(source) => Some(source),
2709     ///             _ => None,
2710     ///         }
2711     ///     }
2712     /// }
2713     ///
2714     /// fn divisible_by_3(input: &str) -> Result<(), Error> {
2715     ///     input
2716     ///         .parse::<i32>()
2717     ///         .map_err(Error::Indivisible)
2718     ///         .map(|v| v % 3)
2719     ///         .and_then(|remainder| {
2720     ///             if remainder == 0 {
2721     ///                 Ok(())
2722     ///             } else {
2723     ///                 Err(Error::Remainder(remainder as u8))
2724     ///             }
2725     ///         })
2726     /// }
2727     /// ```
2728     #[clippy::version = "1.48.0"]
2729     pub MAP_ERR_IGNORE,
2730     restriction,
2731     "`map_err` should not ignore the original error"
2732 }
2733
2734 declare_clippy_lint! {
2735     /// ### What it does
2736     /// Checks for `&mut Mutex::lock` calls
2737     ///
2738     /// ### Why is this bad?
2739     /// `Mutex::lock` is less efficient than
2740     /// calling `Mutex::get_mut`. In addition you also have a statically
2741     /// guarantee that the mutex isn't locked, instead of just a runtime
2742     /// guarantee.
2743     ///
2744     /// ### Example
2745     /// ```rust
2746     /// use std::sync::{Arc, Mutex};
2747     ///
2748     /// let mut value_rc = Arc::new(Mutex::new(42_u8));
2749     /// let value_mutex = Arc::get_mut(&mut value_rc).unwrap();
2750     ///
2751     /// let mut value = value_mutex.lock().unwrap();
2752     /// *value += 1;
2753     /// ```
2754     /// Use instead:
2755     /// ```rust
2756     /// use std::sync::{Arc, Mutex};
2757     ///
2758     /// let mut value_rc = Arc::new(Mutex::new(42_u8));
2759     /// let value_mutex = Arc::get_mut(&mut value_rc).unwrap();
2760     ///
2761     /// let value = value_mutex.get_mut().unwrap();
2762     /// *value += 1;
2763     /// ```
2764     #[clippy::version = "1.49.0"]
2765     pub MUT_MUTEX_LOCK,
2766     style,
2767     "`&mut Mutex::lock` does unnecessary locking"
2768 }
2769
2770 declare_clippy_lint! {
2771     /// ### What it does
2772     /// Checks for duplicate open options as well as combinations
2773     /// that make no sense.
2774     ///
2775     /// ### Why is this bad?
2776     /// In the best case, the code will be harder to read than
2777     /// necessary. I don't know the worst case.
2778     ///
2779     /// ### Example
2780     /// ```rust
2781     /// use std::fs::OpenOptions;
2782     ///
2783     /// OpenOptions::new().read(true).truncate(true);
2784     /// ```
2785     #[clippy::version = "pre 1.29.0"]
2786     pub NONSENSICAL_OPEN_OPTIONS,
2787     correctness,
2788     "nonsensical combination of options for opening a file"
2789 }
2790
2791 declare_clippy_lint! {
2792     /// ### What it does
2793     ///* Checks for [push](https://doc.rust-lang.org/std/path/struct.PathBuf.html#method.push)
2794     /// calls on `PathBuf` that can cause overwrites.
2795     ///
2796     /// ### Why is this bad?
2797     /// Calling `push` with a root path at the start can overwrite the
2798     /// previous defined path.
2799     ///
2800     /// ### Example
2801     /// ```rust
2802     /// use std::path::PathBuf;
2803     ///
2804     /// let mut x = PathBuf::from("/foo");
2805     /// x.push("/bar");
2806     /// assert_eq!(x, PathBuf::from("/bar"));
2807     /// ```
2808     /// Could be written:
2809     ///
2810     /// ```rust
2811     /// use std::path::PathBuf;
2812     ///
2813     /// let mut x = PathBuf::from("/foo");
2814     /// x.push("bar");
2815     /// assert_eq!(x, PathBuf::from("/foo/bar"));
2816     /// ```
2817     #[clippy::version = "1.36.0"]
2818     pub PATH_BUF_PUSH_OVERWRITE,
2819     nursery,
2820     "calling `push` with file system root on `PathBuf` can overwrite it"
2821 }
2822
2823 declare_clippy_lint! {
2824     /// ### What it does
2825     /// Checks for zipping a collection with the range of
2826     /// `0.._.len()`.
2827     ///
2828     /// ### Why is this bad?
2829     /// The code is better expressed with `.enumerate()`.
2830     ///
2831     /// ### Example
2832     /// ```rust
2833     /// # let x = vec![1];
2834     /// let _ = x.iter().zip(0..x.len());
2835     /// ```
2836     ///
2837     /// Use instead:
2838     /// ```rust
2839     /// # let x = vec![1];
2840     /// let _ = x.iter().enumerate();
2841     /// ```
2842     #[clippy::version = "pre 1.29.0"]
2843     pub RANGE_ZIP_WITH_LEN,
2844     complexity,
2845     "zipping iterator with a range when `enumerate()` would do"
2846 }
2847
2848 declare_clippy_lint! {
2849     /// ### What it does
2850     /// Checks for usage of `.repeat(1)` and suggest the following method for each types.
2851     /// - `.to_string()` for `str`
2852     /// - `.clone()` for `String`
2853     /// - `.to_vec()` for `slice`
2854     ///
2855     /// The lint will evaluate constant expressions and values as arguments of `.repeat(..)` and emit a message if
2856     /// they are equivalent to `1`. (Related discussion in [rust-clippy#7306](https://github.com/rust-lang/rust-clippy/issues/7306))
2857     ///
2858     /// ### Why is this bad?
2859     /// For example, `String.repeat(1)` is equivalent to `.clone()`. If cloning
2860     /// the string is the intention behind this, `clone()` should be used.
2861     ///
2862     /// ### Example
2863     /// ```rust
2864     /// fn main() {
2865     ///     let x = String::from("hello world").repeat(1);
2866     /// }
2867     /// ```
2868     /// Use instead:
2869     /// ```rust
2870     /// fn main() {
2871     ///     let x = String::from("hello world").clone();
2872     /// }
2873     /// ```
2874     #[clippy::version = "1.47.0"]
2875     pub REPEAT_ONCE,
2876     complexity,
2877     "using `.repeat(1)` instead of `String.clone()`, `str.to_string()` or `slice.to_vec()` "
2878 }
2879
2880 declare_clippy_lint! {
2881     /// ### What it does
2882     /// When sorting primitive values (integers, bools, chars, as well
2883     /// as arrays, slices, and tuples of such items), it is typically better to
2884     /// use an unstable sort than a stable sort.
2885     ///
2886     /// ### Why is this bad?
2887     /// Typically, using a stable sort consumes more memory and cpu cycles.
2888     /// Because values which compare equal are identical, preserving their
2889     /// relative order (the guarantee that a stable sort provides) means
2890     /// nothing, while the extra costs still apply.
2891     ///
2892     /// ### Known problems
2893     ///
2894     /// As pointed out in
2895     /// [issue #8241](https://github.com/rust-lang/rust-clippy/issues/8241),
2896     /// a stable sort can instead be significantly faster for certain scenarios
2897     /// (eg. when a sorted vector is extended with new data and resorted).
2898     ///
2899     /// For more information and benchmarking results, please refer to the
2900     /// issue linked above.
2901     ///
2902     /// ### Example
2903     /// ```rust
2904     /// let mut vec = vec![2, 1, 3];
2905     /// vec.sort();
2906     /// ```
2907     /// Use instead:
2908     /// ```rust
2909     /// let mut vec = vec![2, 1, 3];
2910     /// vec.sort_unstable();
2911     /// ```
2912     #[clippy::version = "1.47.0"]
2913     pub STABLE_SORT_PRIMITIVE,
2914     pedantic,
2915     "use of sort() when sort_unstable() is equivalent"
2916 }
2917
2918 declare_clippy_lint! {
2919     /// ### What it does
2920     /// Detects `().hash(_)`.
2921     ///
2922     /// ### Why is this bad?
2923     /// Hashing a unit value doesn't do anything as the implementation of `Hash` for `()` is a no-op.
2924     ///
2925     /// ### Example
2926     /// ```rust
2927     /// # use std::hash::Hash;
2928     /// # use std::collections::hash_map::DefaultHasher;
2929     /// # enum Foo { Empty, WithValue(u8) }
2930     /// # use Foo::*;
2931     /// # let mut state = DefaultHasher::new();
2932     /// # let my_enum = Foo::Empty;
2933     /// match my_enum {
2934     ///         Empty => ().hash(&mut state),
2935     ///         WithValue(x) => x.hash(&mut state),
2936     /// }
2937     /// ```
2938     /// Use instead:
2939     /// ```rust
2940     /// # use std::hash::Hash;
2941     /// # use std::collections::hash_map::DefaultHasher;
2942     /// # enum Foo { Empty, WithValue(u8) }
2943     /// # use Foo::*;
2944     /// # let mut state = DefaultHasher::new();
2945     /// # let my_enum = Foo::Empty;
2946     /// match my_enum {
2947     ///         Empty => 0_u8.hash(&mut state),
2948     ///         WithValue(x) => x.hash(&mut state),
2949     /// }
2950     /// ```
2951     #[clippy::version = "1.58.0"]
2952     pub UNIT_HASH,
2953     correctness,
2954     "hashing a unit value, which does nothing"
2955 }
2956
2957 declare_clippy_lint! {
2958     /// ### What it does
2959     /// Detects uses of `Vec::sort_by` passing in a closure
2960     /// which compares the two arguments, either directly or indirectly.
2961     ///
2962     /// ### Why is this bad?
2963     /// It is more clear to use `Vec::sort_by_key` (or `Vec::sort` if
2964     /// possible) than to use `Vec::sort_by` and a more complicated
2965     /// closure.
2966     ///
2967     /// ### Known problems
2968     /// If the suggested `Vec::sort_by_key` uses Reverse and it isn't already
2969     /// imported by a use statement, then it will need to be added manually.
2970     ///
2971     /// ### Example
2972     /// ```rust
2973     /// # struct A;
2974     /// # impl A { fn foo(&self) {} }
2975     /// # let mut vec: Vec<A> = Vec::new();
2976     /// vec.sort_by(|a, b| a.foo().cmp(&b.foo()));
2977     /// ```
2978     /// Use instead:
2979     /// ```rust
2980     /// # struct A;
2981     /// # impl A { fn foo(&self) {} }
2982     /// # let mut vec: Vec<A> = Vec::new();
2983     /// vec.sort_by_key(|a| a.foo());
2984     /// ```
2985     #[clippy::version = "1.46.0"]
2986     pub UNNECESSARY_SORT_BY,
2987     complexity,
2988     "Use of `Vec::sort_by` when `Vec::sort_by_key` or `Vec::sort` would be clearer"
2989 }
2990
2991 declare_clippy_lint! {
2992     /// ### What it does
2993     /// Finds occurrences of `Vec::resize(0, an_int)`
2994     ///
2995     /// ### Why is this bad?
2996     /// This is probably an argument inversion mistake.
2997     ///
2998     /// ### Example
2999     /// ```rust
3000     /// vec!(1, 2, 3, 4, 5).resize(0, 5)
3001     /// ```
3002     ///
3003     /// Use instead:
3004     /// ```rust
3005     /// vec!(1, 2, 3, 4, 5).clear()
3006     /// ```
3007     #[clippy::version = "1.46.0"]
3008     pub VEC_RESIZE_TO_ZERO,
3009     correctness,
3010     "emptying a vector with `resize(0, an_int)` instead of `clear()` is probably an argument inversion mistake"
3011 }
3012
3013 declare_clippy_lint! {
3014     /// ### What it does
3015     /// Checks for use of File::read_to_end and File::read_to_string.
3016     ///
3017     /// ### Why is this bad?
3018     /// `fs::{read, read_to_string}` provide the same functionality when `buf` is empty with fewer imports and no intermediate values.
3019     /// See also: [fs::read docs](https://doc.rust-lang.org/std/fs/fn.read.html), [fs::read_to_string docs](https://doc.rust-lang.org/std/fs/fn.read_to_string.html)
3020     ///
3021     /// ### Example
3022     /// ```rust,no_run
3023     /// # use std::io::Read;
3024     /// # use std::fs::File;
3025     /// let mut f = File::open("foo.txt").unwrap();
3026     /// let mut bytes = Vec::new();
3027     /// f.read_to_end(&mut bytes).unwrap();
3028     /// ```
3029     /// Can be written more concisely as
3030     /// ```rust,no_run
3031     /// # use std::fs;
3032     /// let mut bytes = fs::read("foo.txt").unwrap();
3033     /// ```
3034     #[clippy::version = "1.44.0"]
3035     pub VERBOSE_FILE_READS,
3036     restriction,
3037     "use of `File::read_to_end` or `File::read_to_string`"
3038 }
3039
3040 declare_clippy_lint! {
3041     /// ### What it does
3042     ///
3043     /// Checks for iterating a map (`HashMap` or `BTreeMap`) and
3044     /// ignoring either the keys or values.
3045     ///
3046     /// ### Why is this bad?
3047     ///
3048     /// Readability. There are `keys` and `values` methods that
3049     /// can be used to express that we only need the keys or the values.
3050     ///
3051     /// ### Example
3052     ///
3053     /// ```
3054     /// # use std::collections::HashMap;
3055     /// let map: HashMap<u32, u32> = HashMap::new();
3056     /// let values = map.iter().map(|(_, value)| value).collect::<Vec<_>>();
3057     /// ```
3058     ///
3059     /// Use instead:
3060     /// ```
3061     /// # use std::collections::HashMap;
3062     /// let map: HashMap<u32, u32> = HashMap::new();
3063     /// let values = map.values().collect::<Vec<_>>();
3064     /// ```
3065     #[clippy::version = "1.65.0"]
3066     pub ITER_KV_MAP,
3067     complexity,
3068     "iterating on map using `iter` when `keys` or `values` would do"
3069 }
3070
3071 declare_clippy_lint! {
3072     /// ### What it does
3073     ///
3074     /// Checks an argument of `seek` method of `Seek` trait
3075     /// and if it start seek from `SeekFrom::Current(0)`, suggests `stream_position` instead.
3076     ///
3077     /// ### Why is this bad?
3078     ///
3079     /// Readability. Use dedicated method.
3080     ///
3081     /// ### Example
3082     ///
3083     /// ```rust
3084     /// use std::fs::File;
3085     /// use std::io::{self, Write, Seek, SeekFrom};
3086     ///
3087     /// fn main() -> io::Result<()> {
3088     ///     let mut f = File::create("foo.txt")?;
3089     ///     f.write_all(b"Hello")?;
3090     ///     eprintln!("Written {} bytes", f.seek(SeekFrom::Current(0))?);
3091     ///
3092     ///     Ok(())
3093     /// }
3094     /// ```
3095     /// Use instead:
3096     /// ```rust
3097     /// use std::fs::File;
3098     /// use std::io::{self, Write, Seek, SeekFrom};
3099     ///
3100     /// fn main() -> io::Result<()> {
3101     ///     let mut f = File::create("foo.txt")?;
3102     ///     f.write_all(b"Hello")?;
3103     ///     eprintln!("Written {} bytes", f.stream_position()?);
3104     ///
3105     ///     Ok(())
3106     /// }
3107     /// ```
3108     #[clippy::version = "1.66.0"]
3109     pub SEEK_FROM_CURRENT,
3110     complexity,
3111     "use dedicated method for seek from current position"
3112 }
3113
3114 declare_clippy_lint! {
3115     /// ### What it does
3116     ///
3117     /// Checks for jumps to the start of a stream that implements `Seek`
3118     /// and uses the `seek` method providing `Start` as parameter.
3119     ///
3120     /// ### Why is this bad?
3121     ///
3122     /// Readability. There is a specific method that was implemented for
3123     /// this exact scenario.
3124     ///
3125     /// ### Example
3126     /// ```rust
3127     /// # use std::io;
3128     /// fn foo<T: io::Seek>(t: &mut T) {
3129     ///     t.seek(io::SeekFrom::Start(0));
3130     /// }
3131     /// ```
3132     /// Use instead:
3133     /// ```rust
3134     /// # use std::io;
3135     /// fn foo<T: io::Seek>(t: &mut T) {
3136     ///     t.rewind();
3137     /// }
3138     /// ```
3139     #[clippy::version = "1.66.0"]
3140     pub SEEK_TO_START_INSTEAD_OF_REWIND,
3141     complexity,
3142     "jumping to the start of stream using `seek` method"
3143 }
3144
3145 declare_clippy_lint! {
3146     /// ### What it does
3147     /// Checks for functions collecting an iterator when collect
3148     /// is not needed.
3149     ///
3150     /// ### Why is this bad?
3151     /// `collect` causes the allocation of a new data structure,
3152     /// when this allocation may not be needed.
3153     ///
3154     /// ### Example
3155     /// ```rust
3156     /// # let iterator = vec![1].into_iter();
3157     /// let len = iterator.clone().collect::<Vec<_>>().len();
3158     /// // should be
3159     /// let len = iterator.count();
3160     /// ```
3161     #[clippy::version = "1.30.0"]
3162     pub NEEDLESS_COLLECT,
3163     nursery,
3164     "collecting an iterator when collect is not needed"
3165 }
3166
3167 pub struct Methods {
3168     avoid_breaking_exported_api: bool,
3169     msrv: Option<RustcVersion>,
3170     allow_expect_in_tests: bool,
3171     allow_unwrap_in_tests: bool,
3172 }
3173
3174 impl Methods {
3175     #[must_use]
3176     pub fn new(
3177         avoid_breaking_exported_api: bool,
3178         msrv: Option<RustcVersion>,
3179         allow_expect_in_tests: bool,
3180         allow_unwrap_in_tests: bool,
3181     ) -> Self {
3182         Self {
3183             avoid_breaking_exported_api,
3184             msrv,
3185             allow_expect_in_tests,
3186             allow_unwrap_in_tests,
3187         }
3188     }
3189 }
3190
3191 impl_lint_pass!(Methods => [
3192     UNWRAP_USED,
3193     EXPECT_USED,
3194     SHOULD_IMPLEMENT_TRAIT,
3195     WRONG_SELF_CONVENTION,
3196     OK_EXPECT,
3197     UNWRAP_OR_ELSE_DEFAULT,
3198     MAP_UNWRAP_OR,
3199     RESULT_MAP_OR_INTO_OPTION,
3200     OPTION_MAP_OR_NONE,
3201     BIND_INSTEAD_OF_MAP,
3202     OR_FUN_CALL,
3203     OR_THEN_UNWRAP,
3204     EXPECT_FUN_CALL,
3205     CHARS_NEXT_CMP,
3206     CHARS_LAST_CMP,
3207     CLONE_ON_COPY,
3208     CLONE_ON_REF_PTR,
3209     CLONE_DOUBLE_REF,
3210     COLLAPSIBLE_STR_REPLACE,
3211     ITER_OVEREAGER_CLONED,
3212     CLONED_INSTEAD_OF_COPIED,
3213     FLAT_MAP_OPTION,
3214     INEFFICIENT_TO_STRING,
3215     NEW_RET_NO_SELF,
3216     SINGLE_CHAR_PATTERN,
3217     SINGLE_CHAR_ADD_STR,
3218     SEARCH_IS_SOME,
3219     FILTER_NEXT,
3220     SKIP_WHILE_NEXT,
3221     FILTER_MAP_IDENTITY,
3222     MAP_IDENTITY,
3223     MANUAL_FILTER_MAP,
3224     MANUAL_FIND_MAP,
3225     OPTION_FILTER_MAP,
3226     FILTER_MAP_NEXT,
3227     FLAT_MAP_IDENTITY,
3228     MAP_FLATTEN,
3229     ITERATOR_STEP_BY_ZERO,
3230     ITER_NEXT_SLICE,
3231     ITER_COUNT,
3232     ITER_NTH,
3233     ITER_NTH_ZERO,
3234     BYTES_NTH,
3235     ITER_SKIP_NEXT,
3236     GET_UNWRAP,
3237     GET_LAST_WITH_LEN,
3238     STRING_EXTEND_CHARS,
3239     ITER_CLONED_COLLECT,
3240     ITER_WITH_DRAIN,
3241     USELESS_ASREF,
3242     UNNECESSARY_FOLD,
3243     UNNECESSARY_FILTER_MAP,
3244     UNNECESSARY_FIND_MAP,
3245     INTO_ITER_ON_REF,
3246     SUSPICIOUS_MAP,
3247     UNINIT_ASSUMED_INIT,
3248     MANUAL_SATURATING_ARITHMETIC,
3249     ZST_OFFSET,
3250     FILETYPE_IS_FILE,
3251     OPTION_AS_REF_DEREF,
3252     UNNECESSARY_LAZY_EVALUATIONS,
3253     MAP_COLLECT_RESULT_UNIT,
3254     FROM_ITER_INSTEAD_OF_COLLECT,
3255     INSPECT_FOR_EACH,
3256     IMPLICIT_CLONE,
3257     SUSPICIOUS_TO_OWNED,
3258     SUSPICIOUS_SPLITN,
3259     MANUAL_STR_REPEAT,
3260     EXTEND_WITH_DRAIN,
3261     MANUAL_SPLIT_ONCE,
3262     NEEDLESS_SPLITN,
3263     UNNECESSARY_TO_OWNED,
3264     UNNECESSARY_JOIN,
3265     ERR_EXPECT,
3266     NEEDLESS_OPTION_AS_DEREF,
3267     IS_DIGIT_ASCII_RADIX,
3268     NEEDLESS_OPTION_TAKE,
3269     NO_EFFECT_REPLACE,
3270     OBFUSCATED_IF_ELSE,
3271     ITER_ON_SINGLE_ITEMS,
3272     ITER_ON_EMPTY_COLLECTIONS,
3273     NAIVE_BYTECOUNT,
3274     BYTES_COUNT_TO_LEN,
3275     CASE_SENSITIVE_FILE_EXTENSION_COMPARISONS,
3276     GET_FIRST,
3277     MANUAL_OK_OR,
3278     MAP_CLONE,
3279     MAP_ERR_IGNORE,
3280     MUT_MUTEX_LOCK,
3281     NONSENSICAL_OPEN_OPTIONS,
3282     PATH_BUF_PUSH_OVERWRITE,
3283     RANGE_ZIP_WITH_LEN,
3284     REPEAT_ONCE,
3285     STABLE_SORT_PRIMITIVE,
3286     UNIT_HASH,
3287     UNNECESSARY_SORT_BY,
3288     VEC_RESIZE_TO_ZERO,
3289     VERBOSE_FILE_READS,
3290     ITER_KV_MAP,
3291     SEEK_FROM_CURRENT,
3292     SEEK_TO_START_INSTEAD_OF_REWIND,
3293     NEEDLESS_COLLECT,
3294 ]);
3295
3296 /// Extracts a method call name, args, and `Span` of the method name.
3297 fn method_call<'tcx>(
3298     recv: &'tcx hir::Expr<'tcx>,
3299 ) -> Option<(&'tcx str, &'tcx hir::Expr<'tcx>, &'tcx [hir::Expr<'tcx>], Span, Span)> {
3300     if let ExprKind::MethodCall(path, receiver, args, call_span) = recv.kind {
3301         if !args.iter().any(|e| e.span.from_expansion()) && !receiver.span.from_expansion() {
3302             let name = path.ident.name.as_str();
3303             return Some((name, receiver, args, path.ident.span, call_span));
3304         }
3305     }
3306     None
3307 }
3308
3309 impl<'tcx> LateLintPass<'tcx> for Methods {
3310     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) {
3311         if expr.span.from_expansion() {
3312             return;
3313         }
3314
3315         self.check_methods(cx, expr);
3316
3317         match expr.kind {
3318             hir::ExprKind::Call(func, args) => {
3319                 from_iter_instead_of_collect::check(cx, expr, args, func);
3320             },
3321             hir::ExprKind::MethodCall(method_call, receiver, args, _) => {
3322                 let method_span = method_call.ident.span;
3323                 or_fun_call::check(cx, expr, method_span, method_call.ident.as_str(), receiver, args);
3324                 expect_fun_call::check(cx, expr, method_span, method_call.ident.as_str(), receiver, args);
3325                 clone_on_copy::check(cx, expr, method_call.ident.name, receiver, args);
3326                 clone_on_ref_ptr::check(cx, expr, method_call.ident.name, receiver, args);
3327                 inefficient_to_string::check(cx, expr, method_call.ident.name, receiver, args);
3328                 single_char_add_str::check(cx, expr, receiver, args);
3329                 into_iter_on_ref::check(cx, expr, method_span, method_call.ident.name, receiver);
3330                 single_char_pattern::check(cx, expr, method_call.ident.name, receiver, args);
3331                 unnecessary_to_owned::check(cx, expr, method_call.ident.name, receiver, args, self.msrv);
3332             },
3333             hir::ExprKind::Binary(op, lhs, rhs) if op.node == hir::BinOpKind::Eq || op.node == hir::BinOpKind::Ne => {
3334                 let mut info = BinaryExprInfo {
3335                     expr,
3336                     chain: lhs,
3337                     other: rhs,
3338                     eq: op.node == hir::BinOpKind::Eq,
3339                 };
3340                 lint_binary_expr_with_method_call(cx, &mut info);
3341             },
3342             _ => (),
3343         }
3344     }
3345
3346     #[allow(clippy::too_many_lines)]
3347     fn check_impl_item(&mut self, cx: &LateContext<'tcx>, impl_item: &'tcx hir::ImplItem<'_>) {
3348         if in_external_macro(cx.sess(), impl_item.span) {
3349             return;
3350         }
3351         let name = impl_item.ident.name.as_str();
3352         let parent = cx.tcx.hir().get_parent_item(impl_item.hir_id()).def_id;
3353         let item = cx.tcx.hir().expect_item(parent);
3354         let self_ty = cx.tcx.type_of(item.def_id);
3355
3356         let implements_trait = matches!(item.kind, hir::ItemKind::Impl(hir::Impl { of_trait: Some(_), .. }));
3357         if let hir::ImplItemKind::Fn(ref sig, id) = impl_item.kind {
3358             let method_sig = cx.tcx.fn_sig(impl_item.def_id);
3359             let method_sig = cx.tcx.erase_late_bound_regions(method_sig);
3360             let first_arg_ty_opt = method_sig.inputs().iter().next().copied();
3361             // if this impl block implements a trait, lint in trait definition instead
3362             if !implements_trait && cx.access_levels.is_exported(impl_item.def_id.def_id) {
3363                 // check missing trait implementations
3364                 for method_config in &TRAIT_METHODS {
3365                     if name == method_config.method_name
3366                         && sig.decl.inputs.len() == method_config.param_count
3367                         && method_config.output_type.matches(&sig.decl.output)
3368                         // in case there is no first arg, since we already have checked the number of arguments
3369                         // it's should be always true
3370                         && first_arg_ty_opt.map_or(true, |first_arg_ty| method_config
3371                             .self_kind.matches(cx, self_ty, first_arg_ty)
3372                             )
3373                         && fn_header_equals(method_config.fn_header, sig.header)
3374                         && method_config.lifetime_param_cond(impl_item)
3375                     {
3376                         span_lint_and_help(
3377                             cx,
3378                             SHOULD_IMPLEMENT_TRAIT,
3379                             impl_item.span,
3380                             &format!(
3381                                 "method `{}` can be confused for the standard trait method `{}::{}`",
3382                                 method_config.method_name, method_config.trait_name, method_config.method_name
3383                             ),
3384                             None,
3385                             &format!(
3386                                 "consider implementing the trait `{}` or choosing a less ambiguous method name",
3387                                 method_config.trait_name
3388                             ),
3389                         );
3390                     }
3391                 }
3392             }
3393
3394             if sig.decl.implicit_self.has_implicit_self()
3395                     && !(self.avoid_breaking_exported_api
3396                     && cx.access_levels.is_exported(impl_item.def_id.def_id))
3397                     && let Some(first_arg) = iter_input_pats(sig.decl, cx.tcx.hir().body(id)).next()
3398                     && let Some(first_arg_ty) = first_arg_ty_opt
3399                 {
3400                     wrong_self_convention::check(
3401                         cx,
3402                         name,
3403                         self_ty,
3404                         first_arg_ty,
3405                         first_arg.pat.span,
3406                         implements_trait,
3407                         false
3408                     );
3409                 }
3410         }
3411
3412         // if this impl block implements a trait, lint in trait definition instead
3413         if implements_trait {
3414             return;
3415         }
3416
3417         if let hir::ImplItemKind::Fn(_, _) = impl_item.kind {
3418             let ret_ty = return_ty(cx, impl_item.hir_id());
3419
3420             if contains_ty_adt_constructor_opaque(cx, ret_ty, self_ty) {
3421                 return;
3422             }
3423
3424             if name == "new" && ret_ty != self_ty {
3425                 span_lint(
3426                     cx,
3427                     NEW_RET_NO_SELF,
3428                     impl_item.span,
3429                     "methods called `new` usually return `Self`",
3430                 );
3431             }
3432         }
3433     }
3434
3435     fn check_trait_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx TraitItem<'_>) {
3436         if in_external_macro(cx.tcx.sess, item.span) {
3437             return;
3438         }
3439
3440         if_chain! {
3441             if let TraitItemKind::Fn(ref sig, _) = item.kind;
3442             if sig.decl.implicit_self.has_implicit_self();
3443             if let Some(first_arg_ty) = sig.decl.inputs.iter().next();
3444
3445             then {
3446                 let first_arg_span = first_arg_ty.span;
3447                 let first_arg_ty = hir_ty_to_ty(cx.tcx, first_arg_ty);
3448                 let self_ty = TraitRef::identity(cx.tcx, item.def_id.to_def_id())
3449                     .self_ty()
3450                     .skip_binder();
3451                 wrong_self_convention::check(
3452                     cx,
3453                     item.ident.name.as_str(),
3454                     self_ty,
3455                     first_arg_ty,
3456                     first_arg_span,
3457                     false,
3458                     true,
3459                 );
3460             }
3461         }
3462
3463         if_chain! {
3464             if item.ident.name == sym::new;
3465             if let TraitItemKind::Fn(_, _) = item.kind;
3466             let ret_ty = return_ty(cx, item.hir_id());
3467             let self_ty = TraitRef::identity(cx.tcx, item.def_id.to_def_id())
3468                 .self_ty()
3469                 .skip_binder();
3470             if !ret_ty.contains(self_ty);
3471
3472             then {
3473                 span_lint(
3474                     cx,
3475                     NEW_RET_NO_SELF,
3476                     item.span,
3477                     "methods called `new` usually return `Self`",
3478                 );
3479             }
3480         }
3481     }
3482
3483     extract_msrv_attr!(LateContext);
3484 }
3485
3486 impl Methods {
3487     #[allow(clippy::too_many_lines)]
3488     fn check_methods<'tcx>(&self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
3489         if let Some((name, recv, args, span, call_span)) = method_call(expr) {
3490             match (name, args) {
3491                 ("add" | "offset" | "sub" | "wrapping_offset" | "wrapping_add" | "wrapping_sub", [_arg]) => {
3492                     zst_offset::check(cx, expr, recv);
3493                 },
3494                 ("and_then", [arg]) => {
3495                     let biom_option_linted = bind_instead_of_map::OptionAndThenSome::check(cx, expr, recv, arg);
3496                     let biom_result_linted = bind_instead_of_map::ResultAndThenOk::check(cx, expr, recv, arg);
3497                     if !biom_option_linted && !biom_result_linted {
3498                         unnecessary_lazy_eval::check(cx, expr, recv, arg, "and");
3499                     }
3500                 },
3501                 ("as_deref" | "as_deref_mut", []) => {
3502                     needless_option_as_deref::check(cx, expr, recv, name);
3503                 },
3504                 ("as_mut", []) => useless_asref::check(cx, expr, "as_mut", recv),
3505                 ("as_ref", []) => useless_asref::check(cx, expr, "as_ref", recv),
3506                 ("assume_init", []) => uninit_assumed_init::check(cx, expr, recv),
3507                 ("cloned", []) => cloned_instead_of_copied::check(cx, expr, recv, span, self.msrv),
3508                 ("collect", []) if is_trait_method(cx, expr, sym::Iterator) => {
3509                     needless_collect::check(cx, span, expr, recv, call_span);
3510                     match method_call(recv) {
3511                         Some((name @ ("cloned" | "copied"), recv2, [], _, _)) => {
3512                             iter_cloned_collect::check(cx, name, expr, recv2);
3513                         },
3514                         Some(("map", m_recv, [m_arg], _, _)) => {
3515                             map_collect_result_unit::check(cx, expr, m_recv, m_arg);
3516                         },
3517                         Some(("take", take_self_arg, [take_arg], _, _)) => {
3518                             if meets_msrv(self.msrv, msrvs::STR_REPEAT) {
3519                                 manual_str_repeat::check(cx, expr, recv, take_self_arg, take_arg);
3520                             }
3521                         },
3522                         _ => {},
3523                     }
3524                 },
3525                 ("count", []) if is_trait_method(cx, expr, sym::Iterator) => match method_call(recv) {
3526                     Some(("cloned", recv2, [], _, _)) => iter_overeager_cloned::check(cx, expr, recv, recv2, true, false),
3527                     Some((name2 @ ("into_iter" | "iter" | "iter_mut"), recv2, [], _, _)) => {
3528                         iter_count::check(cx, expr, recv2, name2);
3529                     },
3530                     Some(("map", _, [arg], _, _)) => suspicious_map::check(cx, expr, recv, arg),
3531                     Some(("filter", recv2, [arg], _, _)) => bytecount::check(cx, expr, recv2, arg),
3532                     Some(("bytes", recv2, [], _, _)) => bytes_count_to_len::check(cx, expr, recv, recv2),
3533                     _ => {},
3534                 },
3535                 ("drain", [arg]) => {
3536                     iter_with_drain::check(cx, expr, recv, span, arg);
3537                 },
3538                 ("ends_with", [arg]) => {
3539                     if let ExprKind::MethodCall(.., span) = expr.kind {
3540                         case_sensitive_file_extension_comparisons::check(cx, expr, span, recv, arg);
3541                     }
3542                 },
3543                 ("expect", [_]) => match method_call(recv) {
3544                     Some(("ok", recv, [], _, _)) => ok_expect::check(cx, expr, recv),
3545                     Some(("err", recv, [], err_span, _)) => err_expect::check(cx, expr, recv, self.msrv, span, err_span),
3546                     _ => expect_used::check(cx, expr, recv, false, self.allow_expect_in_tests),
3547                 },
3548                 ("expect_err", [_]) => expect_used::check(cx, expr, recv, true, self.allow_expect_in_tests),
3549                 ("extend", [arg]) => {
3550                     string_extend_chars::check(cx, expr, recv, arg);
3551                     extend_with_drain::check(cx, expr, recv, arg);
3552                 },
3553                 ("filter_map", [arg]) => {
3554                     unnecessary_filter_map::check(cx, expr, arg, name);
3555                     filter_map_identity::check(cx, expr, arg, span);
3556                 },
3557                 ("find_map", [arg]) => {
3558                     unnecessary_filter_map::check(cx, expr, arg, name);
3559                 },
3560                 ("flat_map", [arg]) => {
3561                     flat_map_identity::check(cx, expr, arg, span);
3562                     flat_map_option::check(cx, expr, arg, span);
3563                 },
3564                 ("flatten", []) => match method_call(recv) {
3565                     Some(("map", recv, [map_arg], map_span, _)) => map_flatten::check(cx, expr, recv, map_arg, map_span),
3566                     Some(("cloned", recv2, [], _, _)) => iter_overeager_cloned::check(cx, expr, recv, recv2, false, true),
3567                     _ => {},
3568                 },
3569                 ("fold", [init, acc]) => unnecessary_fold::check(cx, expr, init, acc, span),
3570                 ("for_each", [_]) => {
3571                     if let Some(("inspect", _, [_], span2, _)) = method_call(recv) {
3572                         inspect_for_each::check(cx, expr, span2);
3573                     }
3574                 },
3575                 ("get", [arg]) => {
3576                     get_first::check(cx, expr, recv, arg);
3577                     get_last_with_len::check(cx, expr, recv, arg);
3578                 },
3579                 ("get_or_insert_with", [arg]) => unnecessary_lazy_eval::check(cx, expr, recv, arg, "get_or_insert"),
3580                 ("hash", [arg]) => {
3581                     unit_hash::check(cx, expr, recv, arg);
3582                 },
3583                 ("is_file", []) => filetype_is_file::check(cx, expr, recv),
3584                 ("is_digit", [radix]) => is_digit_ascii_radix::check(cx, expr, recv, radix, self.msrv),
3585                 ("is_none", []) => check_is_some_is_none(cx, expr, recv, false),
3586                 ("is_some", []) => check_is_some_is_none(cx, expr, recv, true),
3587                 ("iter" | "iter_mut" | "into_iter", []) => {
3588                     iter_on_single_or_empty_collections::check(cx, expr, name, recv);
3589                 },
3590                 ("join", [join_arg]) => {
3591                     if let Some(("collect", _, _, span, _)) = method_call(recv) {
3592                         unnecessary_join::check(cx, expr, recv, join_arg, span);
3593                     }
3594                 },
3595                 ("last", []) | ("skip", [_]) => {
3596                     if let Some((name2, recv2, args2, _span2, _)) = method_call(recv) {
3597                         if let ("cloned", []) = (name2, args2) {
3598                             iter_overeager_cloned::check(cx, expr, recv, recv2, false, false);
3599                         }
3600                     }
3601                 },
3602                 ("lock", []) => {
3603                     mut_mutex_lock::check(cx, expr, recv, span);
3604                 },
3605                 (name @ ("map" | "map_err"), [m_arg]) => {
3606                     if name == "map" {
3607                         map_clone::check(cx, expr, recv, m_arg, self.msrv);
3608                         if let Some((map_name @ ("iter" | "into_iter"), recv2, _, _, _)) = method_call(recv) {
3609                             iter_kv_map::check(cx, map_name, expr, recv2, m_arg);
3610                         }
3611                     } else {
3612                         map_err_ignore::check(cx, expr, m_arg);
3613                     }
3614                     if let Some((name, recv2, args, span2,_)) = method_call(recv) {
3615                         match (name, args) {
3616                             ("as_mut", []) => option_as_ref_deref::check(cx, expr, recv2, m_arg, true, self.msrv),
3617                             ("as_ref", []) => option_as_ref_deref::check(cx, expr, recv2, m_arg, false, self.msrv),
3618                             ("filter", [f_arg]) => {
3619                                 filter_map::check(cx, expr, recv2, f_arg, span2, recv, m_arg, span, false);
3620                             },
3621                             ("find", [f_arg]) => {
3622                                 filter_map::check(cx, expr, recv2, f_arg, span2, recv, m_arg, span, true);
3623                             },
3624                             _ => {},
3625                         }
3626                     }
3627                     map_identity::check(cx, expr, recv, m_arg, name, span);
3628                 },
3629                 ("map_or", [def, map]) => {
3630                     option_map_or_none::check(cx, expr, recv, def, map);
3631                     manual_ok_or::check(cx, expr, recv, def, map);
3632                 },
3633                 ("next", []) => {
3634                     if let Some((name2, recv2, args2, _, _)) = method_call(recv) {
3635                         match (name2, args2) {
3636                             ("cloned", []) => iter_overeager_cloned::check(cx, expr, recv, recv2, false, false),
3637                             ("filter", [arg]) => filter_next::check(cx, expr, recv2, arg),
3638                             ("filter_map", [arg]) => filter_map_next::check(cx, expr, recv2, arg, self.msrv),
3639                             ("iter", []) => iter_next_slice::check(cx, expr, recv2),
3640                             ("skip", [arg]) => iter_skip_next::check(cx, expr, recv2, arg),
3641                             ("skip_while", [_]) => skip_while_next::check(cx, expr),
3642                             _ => {},
3643                         }
3644                     }
3645                 },
3646                 ("nth", [n_arg]) => match method_call(recv) {
3647                     Some(("bytes", recv2, [], _, _)) => bytes_nth::check(cx, expr, recv2, n_arg),
3648                     Some(("cloned", recv2, [], _, _)) => iter_overeager_cloned::check(cx, expr, recv, recv2, false, false),
3649                     Some(("iter", recv2, [], _, _)) => iter_nth::check(cx, expr, recv2, recv, n_arg, false),
3650                     Some(("iter_mut", recv2, [], _, _)) => iter_nth::check(cx, expr, recv2, recv, n_arg, true),
3651                     _ => iter_nth_zero::check(cx, expr, recv, n_arg),
3652                 },
3653                 ("ok_or_else", [arg]) => unnecessary_lazy_eval::check(cx, expr, recv, arg, "ok_or"),
3654                 ("open", [_]) => {
3655                     open_options::check(cx, expr, recv);
3656                 },
3657                 ("or_else", [arg]) => {
3658                     if !bind_instead_of_map::ResultOrElseErrInfo::check(cx, expr, recv, arg) {
3659                         unnecessary_lazy_eval::check(cx, expr, recv, arg, "or");
3660                     }
3661                 },
3662                 ("push", [arg]) => {
3663                     path_buf_push_overwrite::check(cx, expr, arg);
3664                 },
3665                 ("read_to_end", [_]) => {
3666                     verbose_file_reads::check(cx, expr, recv, verbose_file_reads::READ_TO_END_MSG);
3667                 },
3668                 ("read_to_string", [_]) => {
3669                     verbose_file_reads::check(cx, expr, recv, verbose_file_reads::READ_TO_STRING_MSG);
3670                 },
3671                 ("repeat", [arg]) => {
3672                     repeat_once::check(cx, expr, recv, arg);
3673                 },
3674                 (name @ ("replace" | "replacen"), [arg1, arg2] | [arg1, arg2, _]) => {
3675                     no_effect_replace::check(cx, expr, arg1, arg2);
3676
3677                     // Check for repeated `str::replace` calls to perform `collapsible_str_replace` lint
3678                     if name == "replace" && let Some(("replace", ..)) = method_call(recv) {
3679                         collapsible_str_replace::check(cx, expr, arg1, arg2);
3680                     }
3681                 },
3682                 ("resize", [count_arg, default_arg]) => {
3683                     vec_resize_to_zero::check(cx, expr, count_arg, default_arg, span);
3684                 },
3685                 ("seek", [arg]) => {
3686                     if meets_msrv(self.msrv, msrvs::SEEK_FROM_CURRENT) {
3687                         seek_from_current::check(cx, expr, recv, arg);
3688                     }
3689                     if meets_msrv(self.msrv, msrvs::SEEK_REWIND) {
3690                         seek_to_start_instead_of_rewind::check(cx, expr, recv, arg, span);
3691                     }
3692                 },
3693                 ("sort", []) => {
3694                     stable_sort_primitive::check(cx, expr, recv);
3695                 },
3696                 ("sort_by", [arg]) => {
3697                     unnecessary_sort_by::check(cx, expr, recv, arg, false);
3698                 },
3699                 ("sort_unstable_by", [arg]) => {
3700                     unnecessary_sort_by::check(cx, expr, recv, arg, true);
3701                 },
3702                 ("splitn" | "rsplitn", [count_arg, pat_arg]) => {
3703                     if let Some((Constant::Int(count), _)) = constant(cx, cx.typeck_results(), count_arg) {
3704                         suspicious_splitn::check(cx, name, expr, recv, count);
3705                         str_splitn::check(cx, name, expr, recv, pat_arg, count, self.msrv);
3706                     }
3707                 },
3708                 ("splitn_mut" | "rsplitn_mut", [count_arg, _]) => {
3709                     if let Some((Constant::Int(count), _)) = constant(cx, cx.typeck_results(), count_arg) {
3710                         suspicious_splitn::check(cx, name, expr, recv, count);
3711                     }
3712                 },
3713                 ("step_by", [arg]) => iterator_step_by_zero::check(cx, expr, arg),
3714                 ("take", [_arg]) => {
3715                     if let Some((name2, recv2, args2, _span2, _)) = method_call(recv) {
3716                         if let ("cloned", []) = (name2, args2) {
3717                             iter_overeager_cloned::check(cx, expr, recv, recv2, false, false);
3718                         }
3719                     }
3720                 },
3721                 ("take", []) => needless_option_take::check(cx, expr, recv),
3722                 ("then", [arg]) => {
3723                     if !meets_msrv(self.msrv, msrvs::BOOL_THEN_SOME) {
3724                         return;
3725                     }
3726                     unnecessary_lazy_eval::check(cx, expr, recv, arg, "then_some");
3727                 },
3728                 ("to_owned", []) => {
3729                     if !suspicious_to_owned::check(cx, expr, recv) {
3730                         implicit_clone::check(cx, name, expr, recv);
3731                     }
3732                 },
3733                 ("to_os_string" | "to_path_buf" | "to_vec", []) => {
3734                     implicit_clone::check(cx, name, expr, recv);
3735                 },
3736                 ("unwrap", []) => {
3737                     match method_call(recv) {
3738                         Some(("get", recv, [get_arg], _, _)) => {
3739                             get_unwrap::check(cx, expr, recv, get_arg, false);
3740                         },
3741                         Some(("get_mut", recv, [get_arg], _, _)) => {
3742                             get_unwrap::check(cx, expr, recv, get_arg, true);
3743                         },
3744                         Some(("or", recv, [or_arg], or_span, _)) => {
3745                             or_then_unwrap::check(cx, expr, recv, or_arg, or_span);
3746                         },
3747                         _ => {},
3748                     }
3749                     unwrap_used::check(cx, expr, recv, false, self.allow_unwrap_in_tests);
3750                 },
3751                 ("unwrap_err", []) => unwrap_used::check(cx, expr, recv, true, self.allow_unwrap_in_tests),
3752                 ("unwrap_or", [u_arg]) => match method_call(recv) {
3753                     Some((arith @ ("checked_add" | "checked_sub" | "checked_mul"), lhs, [rhs], _, _)) => {
3754                         manual_saturating_arithmetic::check(cx, expr, lhs, rhs, u_arg, &arith["checked_".len()..]);
3755                     },
3756                     Some(("map", m_recv, [m_arg], span, _)) => {
3757                         option_map_unwrap_or::check(cx, expr, m_recv, m_arg, recv, u_arg, span);
3758                     },
3759                     Some(("then_some", t_recv, [t_arg], _, _)) => {
3760                         obfuscated_if_else::check(cx, expr, t_recv, t_arg, u_arg);
3761                     },
3762                     _ => {},
3763                 },
3764                 ("unwrap_or_else", [u_arg]) => match method_call(recv) {
3765                     Some(("map", recv, [map_arg], _, _))
3766                         if map_unwrap_or::check(cx, expr, recv, map_arg, u_arg, self.msrv) => {},
3767                     _ => {
3768                         unwrap_or_else_default::check(cx, expr, recv, u_arg);
3769                         unnecessary_lazy_eval::check(cx, expr, recv, u_arg, "unwrap_or");
3770                     },
3771                 },
3772                 ("zip", [arg]) => {
3773                     if let ExprKind::MethodCall(name, iter_recv, [], _) = recv.kind
3774                         && name.ident.name == sym::iter
3775                     {
3776                         range_zip_with_len::check(cx, expr, iter_recv, arg);
3777                     }
3778                 },
3779                 _ => {},
3780             }
3781         }
3782     }
3783 }
3784
3785 fn check_is_some_is_none(cx: &LateContext<'_>, expr: &Expr<'_>, recv: &Expr<'_>, is_some: bool) {
3786     if let Some((name @ ("find" | "position" | "rposition"), f_recv, [arg], span, _)) = method_call(recv) {
3787         search_is_some::check(cx, expr, name, is_some, f_recv, arg, recv, span);
3788     }
3789 }
3790
3791 /// Used for `lint_binary_expr_with_method_call`.
3792 #[derive(Copy, Clone)]
3793 struct BinaryExprInfo<'a> {
3794     expr: &'a hir::Expr<'a>,
3795     chain: &'a hir::Expr<'a>,
3796     other: &'a hir::Expr<'a>,
3797     eq: bool,
3798 }
3799
3800 /// Checks for the `CHARS_NEXT_CMP` and `CHARS_LAST_CMP` lints.
3801 fn lint_binary_expr_with_method_call(cx: &LateContext<'_>, info: &mut BinaryExprInfo<'_>) {
3802     macro_rules! lint_with_both_lhs_and_rhs {
3803         ($func:expr, $cx:expr, $info:ident) => {
3804             if !$func($cx, $info) {
3805                 ::std::mem::swap(&mut $info.chain, &mut $info.other);
3806                 if $func($cx, $info) {
3807                     return;
3808                 }
3809             }
3810         };
3811     }
3812
3813     lint_with_both_lhs_and_rhs!(chars_next_cmp::check, cx, info);
3814     lint_with_both_lhs_and_rhs!(chars_last_cmp::check, cx, info);
3815     lint_with_both_lhs_and_rhs!(chars_next_cmp_with_unwrap::check, cx, info);
3816     lint_with_both_lhs_and_rhs!(chars_last_cmp_with_unwrap::check, cx, info);
3817 }
3818
3819 const FN_HEADER: hir::FnHeader = hir::FnHeader {
3820     unsafety: hir::Unsafety::Normal,
3821     constness: hir::Constness::NotConst,
3822     asyncness: hir::IsAsync::NotAsync,
3823     abi: rustc_target::spec::abi::Abi::Rust,
3824 };
3825
3826 struct ShouldImplTraitCase {
3827     trait_name: &'static str,
3828     method_name: &'static str,
3829     param_count: usize,
3830     fn_header: hir::FnHeader,
3831     // implicit self kind expected (none, self, &self, ...)
3832     self_kind: SelfKind,
3833     // checks against the output type
3834     output_type: OutType,
3835     // certain methods with explicit lifetimes can't implement the equivalent trait method
3836     lint_explicit_lifetime: bool,
3837 }
3838 impl ShouldImplTraitCase {
3839     const fn new(
3840         trait_name: &'static str,
3841         method_name: &'static str,
3842         param_count: usize,
3843         fn_header: hir::FnHeader,
3844         self_kind: SelfKind,
3845         output_type: OutType,
3846         lint_explicit_lifetime: bool,
3847     ) -> ShouldImplTraitCase {
3848         ShouldImplTraitCase {
3849             trait_name,
3850             method_name,
3851             param_count,
3852             fn_header,
3853             self_kind,
3854             output_type,
3855             lint_explicit_lifetime,
3856         }
3857     }
3858
3859     fn lifetime_param_cond(&self, impl_item: &hir::ImplItem<'_>) -> bool {
3860         self.lint_explicit_lifetime
3861             || !impl_item.generics.params.iter().any(|p| {
3862                 matches!(
3863                     p.kind,
3864                     hir::GenericParamKind::Lifetime {
3865                         kind: hir::LifetimeParamKind::Explicit
3866                     }
3867                 )
3868             })
3869     }
3870 }
3871
3872 #[rustfmt::skip]
3873 const TRAIT_METHODS: [ShouldImplTraitCase; 30] = [
3874     ShouldImplTraitCase::new("std::ops::Add", "add",  2,  FN_HEADER,  SelfKind::Value,  OutType::Any, true),
3875     ShouldImplTraitCase::new("std::convert::AsMut", "as_mut",  1,  FN_HEADER,  SelfKind::RefMut,  OutType::Ref, true),
3876     ShouldImplTraitCase::new("std::convert::AsRef", "as_ref",  1,  FN_HEADER,  SelfKind::Ref,  OutType::Ref, true),
3877     ShouldImplTraitCase::new("std::ops::BitAnd", "bitand",  2,  FN_HEADER,  SelfKind::Value,  OutType::Any, true),
3878     ShouldImplTraitCase::new("std::ops::BitOr", "bitor",  2,  FN_HEADER,  SelfKind::Value,  OutType::Any, true),
3879     ShouldImplTraitCase::new("std::ops::BitXor", "bitxor",  2,  FN_HEADER,  SelfKind::Value,  OutType::Any, true),
3880     ShouldImplTraitCase::new("std::borrow::Borrow", "borrow",  1,  FN_HEADER,  SelfKind::Ref,  OutType::Ref, true),
3881     ShouldImplTraitCase::new("std::borrow::BorrowMut", "borrow_mut",  1,  FN_HEADER,  SelfKind::RefMut,  OutType::Ref, true),
3882     ShouldImplTraitCase::new("std::clone::Clone", "clone",  1,  FN_HEADER,  SelfKind::Ref,  OutType::Any, true),
3883     ShouldImplTraitCase::new("std::cmp::Ord", "cmp",  2,  FN_HEADER,  SelfKind::Ref,  OutType::Any, true),
3884     ShouldImplTraitCase::new("std::default::Default", "default",  0,  FN_HEADER,  SelfKind::No,  OutType::Any, true),
3885     ShouldImplTraitCase::new("std::ops::Deref", "deref",  1,  FN_HEADER,  SelfKind::Ref,  OutType::Ref, true),
3886     ShouldImplTraitCase::new("std::ops::DerefMut", "deref_mut",  1,  FN_HEADER,  SelfKind::RefMut,  OutType::Ref, true),
3887     ShouldImplTraitCase::new("std::ops::Div", "div",  2,  FN_HEADER,  SelfKind::Value,  OutType::Any, true),
3888     ShouldImplTraitCase::new("std::ops::Drop", "drop",  1,  FN_HEADER,  SelfKind::RefMut,  OutType::Unit, true),
3889     ShouldImplTraitCase::new("std::cmp::PartialEq", "eq",  2,  FN_HEADER,  SelfKind::Ref,  OutType::Bool, true),
3890     ShouldImplTraitCase::new("std::iter::FromIterator", "from_iter",  1,  FN_HEADER,  SelfKind::No,  OutType::Any, true),
3891     ShouldImplTraitCase::new("std::str::FromStr", "from_str",  1,  FN_HEADER,  SelfKind::No,  OutType::Any, true),
3892     ShouldImplTraitCase::new("std::hash::Hash", "hash",  2,  FN_HEADER,  SelfKind::Ref,  OutType::Unit, true),
3893     ShouldImplTraitCase::new("std::ops::Index", "index",  2,  FN_HEADER,  SelfKind::Ref,  OutType::Ref, true),
3894     ShouldImplTraitCase::new("std::ops::IndexMut", "index_mut",  2,  FN_HEADER,  SelfKind::RefMut,  OutType::Ref, true),
3895     ShouldImplTraitCase::new("std::iter::IntoIterator", "into_iter",  1,  FN_HEADER,  SelfKind::Value,  OutType::Any, true),
3896     ShouldImplTraitCase::new("std::ops::Mul", "mul",  2,  FN_HEADER,  SelfKind::Value,  OutType::Any, true),
3897     ShouldImplTraitCase::new("std::ops::Neg", "neg",  1,  FN_HEADER,  SelfKind::Value,  OutType::Any, true),
3898     ShouldImplTraitCase::new("std::iter::Iterator", "next",  1,  FN_HEADER,  SelfKind::RefMut,  OutType::Any, false),
3899     ShouldImplTraitCase::new("std::ops::Not", "not",  1,  FN_HEADER,  SelfKind::Value,  OutType::Any, true),
3900     ShouldImplTraitCase::new("std::ops::Rem", "rem",  2,  FN_HEADER,  SelfKind::Value,  OutType::Any, true),
3901     ShouldImplTraitCase::new("std::ops::Shl", "shl",  2,  FN_HEADER,  SelfKind::Value,  OutType::Any, true),
3902     ShouldImplTraitCase::new("std::ops::Shr", "shr",  2,  FN_HEADER,  SelfKind::Value,  OutType::Any, true),
3903     ShouldImplTraitCase::new("std::ops::Sub", "sub",  2,  FN_HEADER,  SelfKind::Value,  OutType::Any, true),
3904 ];
3905
3906 #[derive(Clone, Copy, PartialEq, Eq, Debug)]
3907 enum SelfKind {
3908     Value,
3909     Ref,
3910     RefMut,
3911     No, // When we want the first argument type to be different than `Self`
3912 }
3913
3914 impl SelfKind {
3915     fn matches<'a>(self, cx: &LateContext<'a>, parent_ty: Ty<'a>, ty: Ty<'a>) -> bool {
3916         fn matches_value<'a>(cx: &LateContext<'a>, parent_ty: Ty<'a>, ty: Ty<'a>) -> bool {
3917             if ty == parent_ty {
3918                 true
3919             } else if ty.is_box() {
3920                 ty.boxed_ty() == parent_ty
3921             } else if is_type_diagnostic_item(cx, ty, sym::Rc) || is_type_diagnostic_item(cx, ty, sym::Arc) {
3922                 if let ty::Adt(_, substs) = ty.kind() {
3923                     substs.types().next().map_or(false, |t| t == parent_ty)
3924                 } else {
3925                     false
3926                 }
3927             } else {
3928                 false
3929             }
3930         }
3931
3932         fn matches_ref<'a>(cx: &LateContext<'a>, mutability: hir::Mutability, parent_ty: Ty<'a>, ty: Ty<'a>) -> bool {
3933             if let ty::Ref(_, t, m) = *ty.kind() {
3934                 return m == mutability && t == parent_ty;
3935             }
3936
3937             let trait_sym = match mutability {
3938                 hir::Mutability::Not => sym::AsRef,
3939                 hir::Mutability::Mut => sym::AsMut,
3940             };
3941
3942             let Some(trait_def_id) = cx.tcx.get_diagnostic_item(trait_sym) else {
3943                 return false
3944             };
3945             implements_trait(cx, ty, trait_def_id, &[parent_ty.into()])
3946         }
3947
3948         fn matches_none<'a>(cx: &LateContext<'a>, parent_ty: Ty<'a>, ty: Ty<'a>) -> bool {
3949             !matches_value(cx, parent_ty, ty)
3950                 && !matches_ref(cx, hir::Mutability::Not, parent_ty, ty)
3951                 && !matches_ref(cx, hir::Mutability::Mut, parent_ty, ty)
3952         }
3953
3954         match self {
3955             Self::Value => matches_value(cx, parent_ty, ty),
3956             Self::Ref => matches_ref(cx, hir::Mutability::Not, parent_ty, ty) || ty == parent_ty && is_copy(cx, ty),
3957             Self::RefMut => matches_ref(cx, hir::Mutability::Mut, parent_ty, ty),
3958             Self::No => matches_none(cx, parent_ty, ty),
3959         }
3960     }
3961
3962     #[must_use]
3963     fn description(self) -> &'static str {
3964         match self {
3965             Self::Value => "`self` by value",
3966             Self::Ref => "`self` by reference",
3967             Self::RefMut => "`self` by mutable reference",
3968             Self::No => "no `self`",
3969         }
3970     }
3971 }
3972
3973 #[derive(Clone, Copy)]
3974 enum OutType {
3975     Unit,
3976     Bool,
3977     Any,
3978     Ref,
3979 }
3980
3981 impl OutType {
3982     fn matches(self, ty: &hir::FnRetTy<'_>) -> bool {
3983         let is_unit = |ty: &hir::Ty<'_>| matches!(ty.kind, hir::TyKind::Tup(&[]));
3984         match (self, ty) {
3985             (Self::Unit, &hir::FnRetTy::DefaultReturn(_)) => true,
3986             (Self::Unit, &hir::FnRetTy::Return(ty)) if is_unit(ty) => true,
3987             (Self::Bool, &hir::FnRetTy::Return(ty)) if is_bool(ty) => true,
3988             (Self::Any, &hir::FnRetTy::Return(ty)) if !is_unit(ty) => true,
3989             (Self::Ref, &hir::FnRetTy::Return(ty)) => matches!(ty.kind, hir::TyKind::Rptr(_, _)),
3990             _ => false,
3991         }
3992     }
3993 }
3994
3995 fn is_bool(ty: &hir::Ty<'_>) -> bool {
3996     if let hir::TyKind::Path(QPath::Resolved(_, path)) = ty.kind {
3997         matches!(path.res, Res::PrimTy(PrimTy::Bool))
3998     } else {
3999         false
4000     }
4001 }
4002
4003 fn fn_header_equals(expected: hir::FnHeader, actual: hir::FnHeader) -> bool {
4004     expected.constness == actual.constness
4005         && expected.unsafety == actual.unsafety
4006         && expected.asyncness == actual.asyncness
4007 }