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