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