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