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