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