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