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