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