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