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