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