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