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