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