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