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