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