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