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