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