1 mod bind_instead_of_map;
3 mod bytes_count_to_len;
5 mod case_sensitive_file_extension_comparisons;
7 mod chars_cmp_with_unwrap;
9 mod chars_last_cmp_with_unwrap;
11 mod chars_next_cmp_with_unwrap;
14 mod cloned_instead_of_copied;
15 mod collapsible_str_replace;
19 mod extend_with_drain;
22 mod filter_map_identity;
25 mod flat_map_identity;
27 mod from_iter_instead_of_collect;
29 mod get_last_with_len;
32 mod inefficient_to_string;
35 mod is_digit_ascii_radix;
36 mod iter_cloned_collect;
42 mod iter_on_single_or_empty_collections;
43 mod iter_overeager_cloned;
46 mod iterator_step_by_zero;
48 mod manual_saturating_arithmetic;
49 mod manual_str_repeat;
51 mod map_collect_result_unit;
58 mod needless_option_as_deref;
59 mod needless_option_take;
60 mod no_effect_replace;
61 mod obfuscated_if_else;
64 mod option_as_ref_deref;
65 mod option_map_or_none;
66 mod option_map_unwrap_or;
69 mod path_buf_push_overwrite;
70 mod range_zip_with_len;
73 mod seek_from_current;
74 mod seek_to_start_instead_of_rewind;
75 mod single_char_add_str;
76 mod single_char_insert_string;
77 mod single_char_pattern;
78 mod single_char_push_string;
80 mod stable_sort_primitive;
82 mod string_extend_chars;
84 mod suspicious_splitn;
85 mod suspicious_to_owned;
86 mod uninit_assumed_init;
88 mod unnecessary_filter_map;
90 mod unnecessary_iter_cloned;
92 mod unnecessary_lazy_eval;
93 mod unnecessary_sort_by;
94 mod unnecessary_to_owned;
95 mod unwrap_or_else_default;
99 mod vec_resize_to_zero;
100 mod verbose_file_reads;
101 mod wrong_self_convention;
104 use bind_instead_of_map::BindInsteadOfMap;
105 use clippy_utils::consts::{constant, Constant};
106 use clippy_utils::diagnostics::{span_lint, span_lint_and_help};
107 use clippy_utils::ty::{contains_ty_adt_constructor_opaque, implements_trait, is_copy, is_type_diagnostic_item};
108 use clippy_utils::{contains_return, is_trait_method, iter_input_pats, meets_msrv, msrvs, return_ty};
109 use if_chain::if_chain;
110 use rustc_hir as hir;
111 use rustc_hir::def::Res;
112 use rustc_hir::{Expr, ExprKind, PrimTy, QPath, TraitItem, TraitItemKind};
113 use rustc_hir_analysis::hir_ty_to_ty;
114 use rustc_lint::{LateContext, LateLintPass, LintContext};
115 use rustc_middle::lint::in_external_macro;
116 use rustc_middle::ty::{self, TraitRef, Ty};
117 use rustc_semver::RustcVersion;
118 use rustc_session::{declare_tool_lint, impl_lint_pass};
119 use rustc_span::{sym, Span};
121 declare_clippy_lint! {
123 /// Checks for usages of `cloned()` on an `Iterator` or `Option` where
124 /// `copied()` could be used instead.
126 /// ### Why is this bad?
127 /// `copied()` is better because it guarantees that the type being cloned
128 /// implements `Copy`.
132 /// [1, 2, 3].iter().cloned();
136 /// [1, 2, 3].iter().copied();
138 #[clippy::version = "1.53.0"]
139 pub CLONED_INSTEAD_OF_COPIED,
141 "used `cloned` where `copied` could be used instead"
144 declare_clippy_lint! {
146 /// Checks for consecutive calls to `str::replace` (2 or more)
147 /// that can be collapsed into a single call.
149 /// ### Why is this bad?
150 /// Consecutive `str::replace` calls scan the string multiple times
151 /// with repetitive code.
155 /// let hello = "hesuo worpd"
156 /// .replace('s', "l")
157 /// .replace("u", "l")
158 /// .replace('p', "l");
162 /// let hello = "hesuo worpd".replace(&['s', 'u', 'p'], "l");
164 #[clippy::version = "1.65.0"]
165 pub COLLAPSIBLE_STR_REPLACE,
167 "collapse consecutive calls to str::replace (2 or more) into a single call"
170 declare_clippy_lint! {
172 /// Checks for usage of `_.cloned().<func>()` where call to `.cloned()` can be postponed.
174 /// ### Why is this bad?
175 /// It's often inefficient to clone all elements of an iterator, when eventually, only some
176 /// of them will be consumed.
178 /// ### Known Problems
179 /// This `lint` removes the side of effect of cloning items in the iterator.
180 /// A code that relies on that side-effect could fail.
184 /// # let vec = vec!["string".to_string()];
185 /// vec.iter().cloned().take(10);
186 /// vec.iter().cloned().last();
191 /// # let vec = vec!["string".to_string()];
192 /// vec.iter().take(10).cloned();
193 /// vec.iter().last().cloned();
195 #[clippy::version = "1.60.0"]
196 pub ITER_OVEREAGER_CLONED,
198 "using `cloned()` early with `Iterator::iter()` can lead to some performance inefficiencies"
201 declare_clippy_lint! {
203 /// Checks for usages of `Iterator::flat_map()` where `filter_map()` could be
206 /// ### Why is this bad?
207 /// When applicable, `filter_map()` is more clear since it shows that
208 /// `Option` is used to produce 0 or 1 items.
212 /// let nums: Vec<i32> = ["1", "2", "whee!"].iter().flat_map(|x| x.parse().ok()).collect();
216 /// let nums: Vec<i32> = ["1", "2", "whee!"].iter().filter_map(|x| x.parse().ok()).collect();
218 #[clippy::version = "1.53.0"]
221 "used `flat_map` where `filter_map` could be used instead"
224 declare_clippy_lint! {
226 /// Checks for `.unwrap()` or `.unwrap_err()` calls on `Result`s and `.unwrap()` call on `Option`s.
228 /// ### Why is this bad?
229 /// It is better to handle the `None` or `Err` case,
230 /// or at least call `.expect(_)` with a more helpful message. Still, for a lot of
231 /// quick-and-dirty code, `unwrap` is a good choice, which is why this lint is
232 /// `Allow` by default.
234 /// `result.unwrap()` will let the thread panic on `Err` values.
235 /// Normally, you want to implement more sophisticated error handling,
236 /// and propagate errors upwards with `?` operator.
238 /// Even if you want to panic on errors, not all `Error`s implement good
239 /// messages on display. Therefore, it may be beneficial to look at the places
240 /// where they may get displayed. Activate this lint to do just that.
244 /// # let option = Some(1);
245 /// # let result: Result<usize, ()> = Ok(1);
252 /// # let option = Some(1);
253 /// # let result: Result<usize, ()> = Ok(1);
254 /// option.expect("more helpful message");
255 /// result.expect("more helpful message");
258 /// If [expect_used](#expect_used) is enabled, instead:
260 /// # let option = Some(1);
261 /// # let result: Result<usize, ()> = Ok(1);
268 #[clippy::version = "1.45.0"]
271 "using `.unwrap()` on `Result` or `Option`, which should at least get a better message using `expect()`"
274 declare_clippy_lint! {
276 /// Checks for `.expect()` or `.expect_err()` calls on `Result`s and `.expect()` call on `Option`s.
278 /// ### Why is this bad?
279 /// Usually it is better to handle the `None` or `Err` case.
280 /// Still, for a lot of quick-and-dirty code, `expect` is a good choice, which is why
281 /// this lint is `Allow` by default.
283 /// `result.expect()` will let the thread panic on `Err`
284 /// values. Normally, you want to implement more sophisticated error handling,
285 /// and propagate errors upwards with `?` operator.
289 /// # let option = Some(1);
290 /// # let result: Result<usize, ()> = Ok(1);
291 /// option.expect("one");
292 /// result.expect("one");
297 /// # let option = Some(1);
298 /// # let result: Result<usize, ()> = Ok(1);
305 #[clippy::version = "1.45.0"]
308 "using `.expect()` on `Result` or `Option`, which might be better handled"
311 declare_clippy_lint! {
313 /// Checks for methods that should live in a trait
314 /// implementation of a `std` trait (see [llogiq's blog
315 /// post](http://llogiq.github.io/2015/07/30/traits.html) for further
316 /// information) instead of an inherent implementation.
318 /// ### Why is this bad?
319 /// Implementing the traits improve ergonomics for users of
320 /// the code, often with very little cost. Also people seeing a `mul(...)`
322 /// may expect `*` to work equally, so you should have good reason to disappoint
329 /// fn add(&self, other: &X) -> X {
335 #[clippy::version = "pre 1.29.0"]
336 pub SHOULD_IMPLEMENT_TRAIT,
338 "defining a method that should be implementing a std trait"
341 declare_clippy_lint! {
343 /// Checks for methods with certain name prefixes and which
344 /// doesn't match how self is taken. The actual rules are:
346 /// |Prefix |Postfix |`self` taken | `self` type |
347 /// |-------|------------|-------------------------------|--------------|
348 /// |`as_` | none |`&self` or `&mut self` | any |
349 /// |`from_`| none | none | any |
350 /// |`into_`| none |`self` | any |
351 /// |`is_` | none |`&mut self` or `&self` or none | any |
352 /// |`to_` | `_mut` |`&mut self` | any |
353 /// |`to_` | not `_mut` |`self` | `Copy` |
354 /// |`to_` | not `_mut` |`&self` | not `Copy` |
356 /// Note: Clippy doesn't trigger methods with `to_` prefix in:
357 /// - Traits definition.
358 /// Clippy can not tell if a type that implements a trait is `Copy` or not.
359 /// - Traits implementation, when `&self` is taken.
360 /// The method signature is controlled by the trait and often `&self` is required for all types that implement the trait
361 /// (see e.g. the `std::string::ToString` trait).
363 /// Clippy allows `Pin<&Self>` and `Pin<&mut Self>` if `&self` and `&mut self` is required.
365 /// Please find more info here:
366 /// https://rust-lang.github.io/api-guidelines/naming.html#ad-hoc-conversions-follow-as_-to_-into_-conventions-c-conv
368 /// ### Why is this bad?
369 /// Consistency breeds readability. If you follow the
370 /// conventions, your users won't be surprised that they, e.g., need to supply a
371 /// mutable reference to a `as_..` function.
377 /// fn as_str(self) -> &'static str {
383 #[clippy::version = "pre 1.29.0"]
384 pub WRONG_SELF_CONVENTION,
386 "defining a method named with an established prefix (like \"into_\") that takes `self` with the wrong convention"
389 declare_clippy_lint! {
391 /// Checks for usage of `ok().expect(..)`.
393 /// ### Why is this bad?
394 /// Because you usually call `expect()` on the `Result`
395 /// directly to get a better error message.
397 /// ### Known problems
398 /// The error type needs to implement `Debug`
402 /// # let x = Ok::<_, ()>(());
403 /// x.ok().expect("why did I do this again?");
408 /// # let x = Ok::<_, ()>(());
409 /// x.expect("why did I do this again?");
411 #[clippy::version = "pre 1.29.0"]
414 "using `ok().expect()`, which gives worse error messages than calling `expect` directly on the Result"
417 declare_clippy_lint! {
419 /// Checks for `.err().expect()` calls on the `Result` type.
421 /// ### Why is this bad?
422 /// `.expect_err()` can be called directly to avoid the extra type conversion from `err()`.
426 /// let x: Result<u32, &str> = Ok(10);
427 /// x.err().expect("Testing err().expect()");
431 /// let x: Result<u32, &str> = Ok(10);
432 /// x.expect_err("Testing expect_err");
434 #[clippy::version = "1.62.0"]
437 r#"using `.err().expect("")` when `.expect_err("")` can be used"#
440 declare_clippy_lint! {
442 /// Checks for usages of `_.unwrap_or_else(Default::default)` on `Option` and
445 /// ### Why is this bad?
446 /// Readability, these can be written as `_.unwrap_or_default`, which is
447 /// simpler and more concise.
451 /// # let x = Some(1);
452 /// x.unwrap_or_else(Default::default);
453 /// x.unwrap_or_else(u32::default);
458 /// # let x = Some(1);
459 /// x.unwrap_or_default();
461 #[clippy::version = "1.56.0"]
462 pub UNWRAP_OR_ELSE_DEFAULT,
464 "using `.unwrap_or_else(Default::default)`, which is more succinctly expressed as `.unwrap_or_default()`"
467 declare_clippy_lint! {
469 /// Checks for usage of `option.map(_).unwrap_or(_)` or `option.map(_).unwrap_or_else(_)` or
470 /// `result.map(_).unwrap_or_else(_)`.
472 /// ### Why is this bad?
473 /// Readability, these can be written more concisely (resp.) as
474 /// `option.map_or(_, _)`, `option.map_or_else(_, _)` and `result.map_or_else(_, _)`.
476 /// ### Known problems
477 /// The order of the arguments is not in execution order
481 /// # let option = Some(1);
482 /// # let result: Result<usize, ()> = Ok(1);
483 /// # fn some_function(foo: ()) -> usize { 1 }
484 /// option.map(|a| a + 1).unwrap_or(0);
485 /// result.map(|a| a + 1).unwrap_or_else(some_function);
490 /// # let option = Some(1);
491 /// # let result: Result<usize, ()> = Ok(1);
492 /// # fn some_function(foo: ()) -> usize { 1 }
493 /// option.map_or(0, |a| a + 1);
494 /// result.map_or_else(some_function, |a| a + 1);
496 #[clippy::version = "1.45.0"]
499 "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)`"
502 declare_clippy_lint! {
504 /// Checks for usage of `_.map_or(None, _)`.
506 /// ### Why is this bad?
507 /// Readability, this can be written more concisely as
510 /// ### Known problems
511 /// The order of the arguments is not in execution order.
515 /// # let opt = Some(1);
516 /// opt.map_or(None, |a| Some(a + 1));
521 /// # let opt = Some(1);
522 /// opt.and_then(|a| Some(a + 1));
524 #[clippy::version = "pre 1.29.0"]
525 pub OPTION_MAP_OR_NONE,
527 "using `Option.map_or(None, f)`, which is more succinctly expressed as `and_then(f)`"
530 declare_clippy_lint! {
532 /// Checks for usage of `_.map_or(None, Some)`.
534 /// ### Why is this bad?
535 /// Readability, this can be written more concisely as
540 /// # let r: Result<u32, &str> = Ok(1);
541 /// assert_eq!(Some(1), r.map_or(None, Some));
546 /// # let r: Result<u32, &str> = Ok(1);
547 /// assert_eq!(Some(1), r.ok());
549 #[clippy::version = "1.44.0"]
550 pub RESULT_MAP_OR_INTO_OPTION,
552 "using `Result.map_or(None, Some)`, which is more succinctly expressed as `ok()`"
555 declare_clippy_lint! {
557 /// Checks for usage of `_.and_then(|x| Some(y))`, `_.and_then(|x| Ok(y))` or
558 /// `_.or_else(|x| Err(y))`.
560 /// ### Why is this bad?
561 /// Readability, this can be written more concisely as
562 /// `_.map(|x| y)` or `_.map_err(|x| y)`.
566 /// # fn opt() -> Option<&'static str> { Some("42") }
567 /// # fn res() -> Result<&'static str, &'static str> { Ok("42") }
568 /// let _ = opt().and_then(|s| Some(s.len()));
569 /// let _ = res().and_then(|s| if s.len() == 42 { Ok(10) } else { Ok(20) });
570 /// let _ = res().or_else(|s| if s.len() == 42 { Err(10) } else { Err(20) });
573 /// The correct use would be:
576 /// # fn opt() -> Option<&'static str> { Some("42") }
577 /// # fn res() -> Result<&'static str, &'static str> { Ok("42") }
578 /// let _ = opt().map(|s| s.len());
579 /// let _ = res().map(|s| if s.len() == 42 { 10 } else { 20 });
580 /// let _ = res().map_err(|s| if s.len() == 42 { 10 } else { 20 });
582 #[clippy::version = "1.45.0"]
583 pub BIND_INSTEAD_OF_MAP,
585 "using `Option.and_then(|x| Some(y))`, which is more succinctly expressed as `map(|x| y)`"
588 declare_clippy_lint! {
590 /// Checks for usage of `_.filter(_).next()`.
592 /// ### Why is this bad?
593 /// Readability, this can be written more concisely as
598 /// # let vec = vec![1];
599 /// vec.iter().filter(|x| **x == 0).next();
604 /// # let vec = vec![1];
605 /// vec.iter().find(|x| **x == 0);
607 #[clippy::version = "pre 1.29.0"]
610 "using `filter(p).next()`, which is more succinctly expressed as `.find(p)`"
613 declare_clippy_lint! {
615 /// Checks for usage of `_.skip_while(condition).next()`.
617 /// ### Why is this bad?
618 /// Readability, this can be written more concisely as
619 /// `_.find(!condition)`.
623 /// # let vec = vec![1];
624 /// vec.iter().skip_while(|x| **x == 0).next();
629 /// # let vec = vec![1];
630 /// vec.iter().find(|x| **x != 0);
632 #[clippy::version = "1.42.0"]
635 "using `skip_while(p).next()`, which is more succinctly expressed as `.find(!p)`"
638 declare_clippy_lint! {
640 /// Checks for usage of `_.map(_).flatten(_)` on `Iterator` and `Option`
642 /// ### Why is this bad?
643 /// Readability, this can be written more concisely as
644 /// `_.flat_map(_)` for `Iterator` or `_.and_then(_)` for `Option`
648 /// let vec = vec![vec![1]];
649 /// let opt = Some(5);
651 /// vec.iter().map(|x| x.iter()).flatten();
652 /// opt.map(|x| Some(x * 2)).flatten();
657 /// # let vec = vec![vec![1]];
658 /// # let opt = Some(5);
659 /// vec.iter().flat_map(|x| x.iter());
660 /// opt.and_then(|x| Some(x * 2));
662 #[clippy::version = "1.31.0"]
665 "using combinations of `flatten` and `map` which can usually be written as a single method call"
668 declare_clippy_lint! {
670 /// Checks for usage of `_.filter(_).map(_)` that can be written more simply
671 /// as `filter_map(_)`.
673 /// ### Why is this bad?
674 /// Redundant code in the `filter` and `map` operations is poor style and
679 /// # #![allow(unused)]
681 /// .filter(|n| n.checked_add(1).is_some())
682 /// .map(|n| n.checked_add(1).unwrap());
687 /// # #[allow(unused)]
688 /// (0_i32..10).filter_map(|n| n.checked_add(1));
690 #[clippy::version = "1.51.0"]
691 pub MANUAL_FILTER_MAP,
693 "using `_.filter(_).map(_)` in a way that can be written more simply as `filter_map(_)`"
696 declare_clippy_lint! {
698 /// Checks for usage of `_.find(_).map(_)` that can be written more simply
699 /// as `find_map(_)`.
701 /// ### Why is this bad?
702 /// Redundant code in the `find` and `map` operations is poor style and
708 /// .find(|n| n.checked_add(1).is_some())
709 /// .map(|n| n.checked_add(1).unwrap());
714 /// (0_i32..10).find_map(|n| n.checked_add(1));
716 #[clippy::version = "1.51.0"]
719 "using `_.find(_).map(_)` in a way that can be written more simply as `find_map(_)`"
722 declare_clippy_lint! {
724 /// Checks for usage of `_.filter_map(_).next()`.
726 /// ### Why is this bad?
727 /// Readability, this can be written more concisely as
732 /// (0..3).filter_map(|x| if x == 2 { Some(x) } else { None }).next();
734 /// Can be written as
737 /// (0..3).find_map(|x| if x == 2 { Some(x) } else { None });
739 #[clippy::version = "1.36.0"]
742 "using combination of `filter_map` and `next` which can usually be written as a single method call"
745 declare_clippy_lint! {
747 /// Checks for usage of `flat_map(|x| x)`.
749 /// ### Why is this bad?
750 /// Readability, this can be written more concisely by using `flatten`.
754 /// # let iter = vec![vec![0]].into_iter();
755 /// iter.flat_map(|x| x);
757 /// Can be written as
759 /// # let iter = vec![vec![0]].into_iter();
762 #[clippy::version = "1.39.0"]
763 pub FLAT_MAP_IDENTITY,
765 "call to `flat_map` where `flatten` is sufficient"
768 declare_clippy_lint! {
770 /// Checks for an iterator or string search (such as `find()`,
771 /// `position()`, or `rposition()`) followed by a call to `is_some()` or `is_none()`.
773 /// ### Why is this bad?
774 /// Readability, this can be written more concisely as:
775 /// * `_.any(_)`, or `_.contains(_)` for `is_some()`,
776 /// * `!_.any(_)`, or `!_.contains(_)` for `is_none()`.
780 /// # #![allow(unused)]
781 /// let vec = vec![1];
782 /// vec.iter().find(|x| **x == 0).is_some();
784 /// "hello world".find("world").is_none();
789 /// let vec = vec![1];
790 /// vec.iter().any(|x| *x == 0);
792 /// # #[allow(unused)]
793 /// !"hello world".contains("world");
795 #[clippy::version = "pre 1.29.0"]
798 "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()`)"
801 declare_clippy_lint! {
803 /// Checks for usage of `.chars().next()` on a `str` to check
804 /// if it starts with a given char.
806 /// ### Why is this bad?
807 /// Readability, this can be written more concisely as
808 /// `_.starts_with(_)`.
812 /// let name = "foo";
813 /// if name.chars().next() == Some('_') {};
818 /// let name = "foo";
819 /// if name.starts_with('_') {};
821 #[clippy::version = "pre 1.29.0"]
824 "using `.chars().next()` to check if a string starts with a char"
827 declare_clippy_lint! {
829 /// Checks for calls to `.or(foo(..))`, `.unwrap_or(foo(..))`,
830 /// `.or_insert(foo(..))` etc., and suggests to use `.or_else(|| foo(..))`,
831 /// `.unwrap_or_else(|| foo(..))`, `.unwrap_or_default()` or `.or_default()`
834 /// ### Why is this bad?
835 /// The function will always be called and potentially
836 /// allocate an object acting as the default.
838 /// ### Known problems
839 /// If the function has side-effects, not calling it will
840 /// change the semantic of the program, but you shouldn't rely on that anyway.
844 /// # let foo = Some(String::new());
845 /// foo.unwrap_or(String::new());
850 /// # let foo = Some(String::new());
851 /// foo.unwrap_or_else(String::new);
855 /// # let foo = Some(String::new());
856 /// foo.unwrap_or_default();
858 #[clippy::version = "pre 1.29.0"]
861 "using any `*or` method with a function call, which suggests `*or_else`"
864 declare_clippy_lint! {
866 /// Checks for `.or(…).unwrap()` calls to Options and Results.
868 /// ### Why is this bad?
869 /// You should use `.unwrap_or(…)` instead for clarity.
873 /// # let fallback = "fallback";
875 /// # type Error = &'static str;
876 /// # let result: Result<&str, Error> = Err("error");
877 /// let value = result.or::<Error>(Ok(fallback)).unwrap();
880 /// # let option: Option<&str> = None;
881 /// let value = option.or(Some(fallback)).unwrap();
885 /// # let fallback = "fallback";
887 /// # let result: Result<&str, &str> = Err("error");
888 /// let value = result.unwrap_or(fallback);
891 /// # let option: Option<&str> = None;
892 /// let value = option.unwrap_or(fallback);
894 #[clippy::version = "1.61.0"]
897 "checks for `.or(…).unwrap()` calls to Options and Results."
900 declare_clippy_lint! {
902 /// Checks for calls to `.expect(&format!(...))`, `.expect(foo(..))`,
903 /// etc., and suggests to use `unwrap_or_else` instead
905 /// ### Why is this bad?
906 /// The function will always be called.
908 /// ### Known problems
909 /// If the function has side-effects, not calling it will
910 /// change the semantics of the program, but you shouldn't rely on that anyway.
914 /// # let foo = Some(String::new());
915 /// # let err_code = "418";
916 /// # let err_msg = "I'm a teapot";
917 /// foo.expect(&format!("Err {}: {}", err_code, err_msg));
921 /// # let foo = Some(String::new());
922 /// foo.expect(format!("Err {}: {}", err_code, err_msg).as_str());
927 /// # let foo = Some(String::new());
928 /// # let err_code = "418";
929 /// # let err_msg = "I'm a teapot";
930 /// foo.unwrap_or_else(|| panic!("Err {}: {}", err_code, err_msg));
932 #[clippy::version = "pre 1.29.0"]
935 "using any `expect` method with a function call"
938 declare_clippy_lint! {
940 /// Checks for usage of `.clone()` on a `Copy` type.
942 /// ### Why is this bad?
943 /// The only reason `Copy` types implement `Clone` is for
944 /// generics, not for using the `clone` method on a concrete type.
950 #[clippy::version = "pre 1.29.0"]
953 "using `clone` on a `Copy` type"
956 declare_clippy_lint! {
958 /// Checks for usage of `.clone()` on a ref-counted pointer,
959 /// (`Rc`, `Arc`, `rc::Weak`, or `sync::Weak`), and suggests calling Clone via unified
960 /// function syntax instead (e.g., `Rc::clone(foo)`).
962 /// ### Why is this bad?
963 /// Calling '.clone()' on an Rc, Arc, or Weak
964 /// can obscure the fact that only the pointer is being cloned, not the underlying
969 /// # use std::rc::Rc;
970 /// let x = Rc::new(1);
977 /// # use std::rc::Rc;
978 /// # let x = Rc::new(1);
981 #[clippy::version = "pre 1.29.0"]
982 pub CLONE_ON_REF_PTR,
984 "using 'clone' on a ref-counted pointer"
987 declare_clippy_lint! {
989 /// Checks for usage of `.clone()` on an `&&T`.
991 /// ### Why is this bad?
992 /// Cloning an `&&T` copies the inner `&T`, instead of
993 /// cloning the underlying `T`.
1000 /// let z = y.clone();
1001 /// println!("{:p} {:p}", *y, z); // prints out the same pointer
1004 #[clippy::version = "pre 1.29.0"]
1005 pub CLONE_DOUBLE_REF,
1007 "using `clone` on `&&T`"
1010 declare_clippy_lint! {
1011 /// ### What it does
1012 /// Checks for usage of `.to_string()` on an `&&T` where
1013 /// `T` implements `ToString` directly (like `&&str` or `&&String`).
1015 /// ### Why is this bad?
1016 /// This bypasses the specialized implementation of
1017 /// `ToString` and instead goes through the more expensive string formatting
1022 /// // Generic implementation for `T: Display` is used (slow)
1023 /// ["foo", "bar"].iter().map(|s| s.to_string());
1025 /// // OK, the specialized impl is used
1026 /// ["foo", "bar"].iter().map(|&s| s.to_string());
1028 #[clippy::version = "1.40.0"]
1029 pub INEFFICIENT_TO_STRING,
1031 "using `to_string` on `&&T` where `T: ToString`"
1034 declare_clippy_lint! {
1035 /// ### What it does
1036 /// Checks for `new` not returning a type that contains `Self`.
1038 /// ### Why is this bad?
1039 /// As a convention, `new` methods are used to make a new
1040 /// instance of a type.
1043 /// In an impl block:
1046 /// # struct NotAFoo;
1048 /// fn new() -> NotAFoo {
1056 /// struct Bar(Foo);
1058 /// // Bad. The type name must contain `Self`
1059 /// fn new() -> Bar {
1067 /// # struct FooError;
1069 /// // Good. Return type contains `Self`
1070 /// fn new() -> Result<Foo, FooError> {
1076 /// Or in a trait definition:
1078 /// pub trait Trait {
1079 /// // Bad. The type name must contain `Self`
1085 /// pub trait Trait {
1086 /// // Good. Return type contains `Self`
1087 /// fn new() -> Self;
1090 #[clippy::version = "pre 1.29.0"]
1091 pub NEW_RET_NO_SELF,
1093 "not returning type containing `Self` in a `new` method"
1096 declare_clippy_lint! {
1097 /// ### What it does
1098 /// Checks for string methods that receive a single-character
1099 /// `str` as an argument, e.g., `_.split("x")`.
1101 /// ### Why is this bad?
1102 /// Performing these methods using a `char` is faster than
1105 /// ### Known problems
1106 /// Does not catch multi-byte unicode characters.
1117 #[clippy::version = "pre 1.29.0"]
1118 pub SINGLE_CHAR_PATTERN,
1120 "using a single-character str where a char could be used, e.g., `_.split(\"x\")`"
1123 declare_clippy_lint! {
1124 /// ### What it does
1125 /// Checks for calling `.step_by(0)` on iterators which panics.
1127 /// ### Why is this bad?
1128 /// This very much looks like an oversight. Use `panic!()` instead if you
1129 /// actually intend to panic.
1132 /// ```rust,should_panic
1133 /// for x in (0..100).step_by(0) {
1137 #[clippy::version = "pre 1.29.0"]
1138 pub ITERATOR_STEP_BY_ZERO,
1140 "using `Iterator::step_by(0)`, which will panic at runtime"
1143 declare_clippy_lint! {
1144 /// ### What it does
1145 /// Checks for indirect collection of populated `Option`
1147 /// ### Why is this bad?
1148 /// `Option` is like a collection of 0-1 things, so `flatten`
1149 /// automatically does this without suspicious-looking `unwrap` calls.
1153 /// let _ = std::iter::empty::<Option<i32>>().filter(Option::is_some).map(Option::unwrap);
1157 /// let _ = std::iter::empty::<Option<i32>>().flatten();
1159 #[clippy::version = "1.53.0"]
1160 pub OPTION_FILTER_MAP,
1162 "filtering `Option` for `Some` then force-unwrapping, which can be one type-safe operation"
1165 declare_clippy_lint! {
1166 /// ### What it does
1167 /// Checks for the use of `iter.nth(0)`.
1169 /// ### Why is this bad?
1170 /// `iter.next()` is equivalent to
1171 /// `iter.nth(0)`, as they both consume the next element,
1172 /// but is more readable.
1176 /// # use std::collections::HashSet;
1177 /// # let mut s = HashSet::new();
1179 /// let x = s.iter().nth(0);
1184 /// # use std::collections::HashSet;
1185 /// # let mut s = HashSet::new();
1187 /// let x = s.iter().next();
1189 #[clippy::version = "1.42.0"]
1192 "replace `iter.nth(0)` with `iter.next()`"
1195 declare_clippy_lint! {
1196 /// ### What it does
1197 /// Checks for use of `.iter().nth()` (and the related
1198 /// `.iter_mut().nth()`) on standard library types with *O*(1) element access.
1200 /// ### Why is this bad?
1201 /// `.get()` and `.get_mut()` are more efficient and more
1206 /// let some_vec = vec![0, 1, 2, 3];
1207 /// let bad_vec = some_vec.iter().nth(3);
1208 /// let bad_slice = &some_vec[..].iter().nth(3);
1210 /// The correct use would be:
1212 /// let some_vec = vec![0, 1, 2, 3];
1213 /// let bad_vec = some_vec.get(3);
1214 /// let bad_slice = &some_vec[..].get(3);
1216 #[clippy::version = "pre 1.29.0"]
1219 "using `.iter().nth()` on a standard library type with O(1) element access"
1222 declare_clippy_lint! {
1223 /// ### What it does
1224 /// Checks for use of `.skip(x).next()` on iterators.
1226 /// ### Why is this bad?
1227 /// `.nth(x)` is cleaner
1231 /// let some_vec = vec![0, 1, 2, 3];
1232 /// let bad_vec = some_vec.iter().skip(3).next();
1233 /// let bad_slice = &some_vec[..].iter().skip(3).next();
1235 /// The correct use would be:
1237 /// let some_vec = vec![0, 1, 2, 3];
1238 /// let bad_vec = some_vec.iter().nth(3);
1239 /// let bad_slice = &some_vec[..].iter().nth(3);
1241 #[clippy::version = "pre 1.29.0"]
1244 "using `.skip(x).next()` on an iterator"
1247 declare_clippy_lint! {
1248 /// ### What it does
1249 /// Checks for use of `.drain(..)` on `Vec` and `VecDeque` for iteration.
1251 /// ### Why is this bad?
1252 /// `.into_iter()` is simpler with better performance.
1256 /// # use std::collections::HashSet;
1257 /// let mut foo = vec![0, 1, 2, 3];
1258 /// let bar: HashSet<usize> = foo.drain(..).collect();
1262 /// # use std::collections::HashSet;
1263 /// let foo = vec![0, 1, 2, 3];
1264 /// let bar: HashSet<usize> = foo.into_iter().collect();
1266 #[clippy::version = "1.61.0"]
1267 pub ITER_WITH_DRAIN,
1269 "replace `.drain(..)` with `.into_iter()`"
1272 declare_clippy_lint! {
1273 /// ### What it does
1274 /// Checks for using `x.get(x.len() - 1)` instead of
1277 /// ### Why is this bad?
1278 /// Using `x.last()` is easier to read and has the same
1281 /// Note that using `x[x.len() - 1]` is semantically different from
1282 /// `x.last()`. Indexing into the array will panic on out-of-bounds
1283 /// accesses, while `x.get()` and `x.last()` will return `None`.
1285 /// There is another lint (get_unwrap) that covers the case of using
1286 /// `x.get(index).unwrap()` instead of `x[index]`.
1290 /// let x = vec![2, 3, 5];
1291 /// let last_element = x.get(x.len() - 1);
1296 /// let x = vec![2, 3, 5];
1297 /// let last_element = x.last();
1299 #[clippy::version = "1.37.0"]
1300 pub GET_LAST_WITH_LEN,
1302 "Using `x.get(x.len() - 1)` when `x.last()` is correct and simpler"
1305 declare_clippy_lint! {
1306 /// ### What it does
1307 /// Checks for use of `.get().unwrap()` (or
1308 /// `.get_mut().unwrap`) on a standard library type which implements `Index`
1310 /// ### Why is this bad?
1311 /// Using the Index trait (`[]`) is more clear and more
1314 /// ### Known problems
1315 /// Not a replacement for error handling: Using either
1316 /// `.unwrap()` or the Index trait (`[]`) carries the risk of causing a `panic`
1317 /// if the value being accessed is `None`. If the use of `.get().unwrap()` is a
1318 /// temporary placeholder for dealing with the `Option` type, then this does
1319 /// not mitigate the need for error handling. If there is a chance that `.get()`
1320 /// will be `None` in your program, then it is advisable that the `None` case
1321 /// is handled in a future refactor instead of using `.unwrap()` or the Index
1326 /// let mut some_vec = vec![0, 1, 2, 3];
1327 /// let last = some_vec.get(3).unwrap();
1328 /// *some_vec.get_mut(0).unwrap() = 1;
1330 /// The correct use would be:
1332 /// let mut some_vec = vec![0, 1, 2, 3];
1333 /// let last = some_vec[3];
1334 /// some_vec[0] = 1;
1336 #[clippy::version = "pre 1.29.0"]
1339 "using `.get().unwrap()` or `.get_mut().unwrap()` when using `[]` would work instead"
1342 declare_clippy_lint! {
1343 /// ### What it does
1344 /// Checks for occurrences where one vector gets extended instead of append
1346 /// ### Why is this bad?
1347 /// Using `append` instead of `extend` is more concise and faster
1351 /// let mut a = vec![1, 2, 3];
1352 /// let mut b = vec![4, 5, 6];
1354 /// a.extend(b.drain(..));
1359 /// let mut a = vec![1, 2, 3];
1360 /// let mut b = vec![4, 5, 6];
1362 /// a.append(&mut b);
1364 #[clippy::version = "1.55.0"]
1365 pub EXTEND_WITH_DRAIN,
1367 "using vec.append(&mut vec) to move the full range of a vector to another"
1370 declare_clippy_lint! {
1371 /// ### What it does
1372 /// Checks for the use of `.extend(s.chars())` where s is a
1373 /// `&str` or `String`.
1375 /// ### Why is this bad?
1376 /// `.push_str(s)` is clearer
1380 /// let abc = "abc";
1381 /// let def = String::from("def");
1382 /// let mut s = String::new();
1383 /// s.extend(abc.chars());
1384 /// s.extend(def.chars());
1386 /// The correct use would be:
1388 /// let abc = "abc";
1389 /// let def = String::from("def");
1390 /// let mut s = String::new();
1391 /// s.push_str(abc);
1392 /// s.push_str(&def);
1394 #[clippy::version = "pre 1.29.0"]
1395 pub STRING_EXTEND_CHARS,
1397 "using `x.extend(s.chars())` where s is a `&str` or `String`"
1400 declare_clippy_lint! {
1401 /// ### What it does
1402 /// Checks for the use of `.cloned().collect()` on slice to
1405 /// ### Why is this bad?
1406 /// `.to_vec()` is clearer
1410 /// let s = [1, 2, 3, 4, 5];
1411 /// let s2: Vec<isize> = s[..].iter().cloned().collect();
1413 /// The better use would be:
1415 /// let s = [1, 2, 3, 4, 5];
1416 /// let s2: Vec<isize> = s.to_vec();
1418 #[clippy::version = "pre 1.29.0"]
1419 pub ITER_CLONED_COLLECT,
1421 "using `.cloned().collect()` on slice to create a `Vec`"
1424 declare_clippy_lint! {
1425 /// ### What it does
1426 /// Checks for usage of `_.chars().last()` or
1427 /// `_.chars().next_back()` on a `str` to check if it ends with a given char.
1429 /// ### Why is this bad?
1430 /// Readability, this can be written more concisely as
1431 /// `_.ends_with(_)`.
1435 /// # let name = "_";
1436 /// name.chars().last() == Some('_') || name.chars().next_back() == Some('-');
1441 /// # let name = "_";
1442 /// name.ends_with('_') || name.ends_with('-');
1444 #[clippy::version = "pre 1.29.0"]
1447 "using `.chars().last()` or `.chars().next_back()` to check if a string ends with a char"
1450 declare_clippy_lint! {
1451 /// ### What it does
1452 /// Checks for usage of `.as_ref()` or `.as_mut()` where the
1453 /// types before and after the call are the same.
1455 /// ### Why is this bad?
1456 /// The call is unnecessary.
1460 /// # fn do_stuff(x: &[i32]) {}
1461 /// let x: &[i32] = &[1, 2, 3, 4, 5];
1462 /// do_stuff(x.as_ref());
1464 /// The correct use would be:
1466 /// # fn do_stuff(x: &[i32]) {}
1467 /// let x: &[i32] = &[1, 2, 3, 4, 5];
1470 #[clippy::version = "pre 1.29.0"]
1473 "using `as_ref` where the types before and after the call are the same"
1476 declare_clippy_lint! {
1477 /// ### What it does
1478 /// Checks for using `fold` when a more succinct alternative exists.
1479 /// Specifically, this checks for `fold`s which could be replaced by `any`, `all`,
1480 /// `sum` or `product`.
1482 /// ### Why is this bad?
1487 /// # #[allow(unused)]
1488 /// (0..3).fold(false, |acc, x| acc || x > 2);
1493 /// (0..3).any(|x| x > 2);
1495 #[clippy::version = "pre 1.29.0"]
1496 pub UNNECESSARY_FOLD,
1498 "using `fold` when a more succinct alternative exists"
1501 declare_clippy_lint! {
1502 /// ### What it does
1503 /// Checks for `filter_map` calls that could be replaced by `filter` or `map`.
1504 /// More specifically it checks if the closure provided is only performing one of the
1505 /// filter or map operations and suggests the appropriate option.
1507 /// ### Why is this bad?
1508 /// Complexity. The intent is also clearer if only a single
1509 /// operation is being performed.
1513 /// let _ = (0..3).filter_map(|x| if x > 2 { Some(x) } else { None });
1515 /// // As there is no transformation of the argument this could be written as:
1516 /// let _ = (0..3).filter(|&x| x > 2);
1520 /// let _ = (0..4).filter_map(|x| Some(x + 1));
1522 /// // As there is no conditional check on the argument this could be written as:
1523 /// let _ = (0..4).map(|x| x + 1);
1525 #[clippy::version = "1.31.0"]
1526 pub UNNECESSARY_FILTER_MAP,
1528 "using `filter_map` when a more succinct alternative exists"
1531 declare_clippy_lint! {
1532 /// ### What it does
1533 /// Checks for `find_map` calls that could be replaced by `find` or `map`. More
1534 /// specifically it checks if the closure provided is only performing one of the
1535 /// find or map operations and suggests the appropriate option.
1537 /// ### Why is this bad?
1538 /// Complexity. The intent is also clearer if only a single
1539 /// operation is being performed.
1543 /// let _ = (0..3).find_map(|x| if x > 2 { Some(x) } else { None });
1545 /// // As there is no transformation of the argument this could be written as:
1546 /// let _ = (0..3).find(|&x| x > 2);
1550 /// let _ = (0..4).find_map(|x| Some(x + 1));
1552 /// // As there is no conditional check on the argument this could be written as:
1553 /// let _ = (0..4).map(|x| x + 1).next();
1555 #[clippy::version = "1.61.0"]
1556 pub UNNECESSARY_FIND_MAP,
1558 "using `find_map` when a more succinct alternative exists"
1561 declare_clippy_lint! {
1562 /// ### What it does
1563 /// Checks for `into_iter` calls on references which should be replaced by `iter`
1566 /// ### Why is this bad?
1567 /// Readability. Calling `into_iter` on a reference will not move out its
1568 /// content into the resulting iterator, which is confusing. It is better just call `iter` or
1569 /// `iter_mut` directly.
1573 /// # let vec = vec![3, 4, 5];
1574 /// (&vec).into_iter();
1579 /// # let vec = vec![3, 4, 5];
1582 #[clippy::version = "1.32.0"]
1583 pub INTO_ITER_ON_REF,
1585 "using `.into_iter()` on a reference"
1588 declare_clippy_lint! {
1589 /// ### What it does
1590 /// Checks for calls to `map` followed by a `count`.
1592 /// ### Why is this bad?
1593 /// It looks suspicious. Maybe `map` was confused with `filter`.
1594 /// If the `map` call is intentional, this should be rewritten
1595 /// using `inspect`. Or, if you intend to drive the iterator to
1596 /// completion, you can just use `for_each` instead.
1600 /// let _ = (0..3).map(|x| x + 2).count();
1602 #[clippy::version = "1.39.0"]
1605 "suspicious usage of map"
1608 declare_clippy_lint! {
1609 /// ### What it does
1610 /// Checks for `MaybeUninit::uninit().assume_init()`.
1612 /// ### Why is this bad?
1613 /// For most types, this is undefined behavior.
1615 /// ### Known problems
1616 /// For now, we accept empty tuples and tuples / arrays
1617 /// of `MaybeUninit`. There may be other types that allow uninitialized
1618 /// data, but those are not yet rigorously defined.
1622 /// // Beware the UB
1623 /// use std::mem::MaybeUninit;
1625 /// let _: usize = unsafe { MaybeUninit::uninit().assume_init() };
1628 /// Note that the following is OK:
1631 /// use std::mem::MaybeUninit;
1633 /// let _: [MaybeUninit<bool>; 5] = unsafe {
1634 /// MaybeUninit::uninit().assume_init()
1637 #[clippy::version = "1.39.0"]
1638 pub UNINIT_ASSUMED_INIT,
1640 "`MaybeUninit::uninit().assume_init()`"
1643 declare_clippy_lint! {
1644 /// ### What it does
1645 /// Checks for `.checked_add/sub(x).unwrap_or(MAX/MIN)`.
1647 /// ### Why is this bad?
1648 /// These can be written simply with `saturating_add/sub` methods.
1652 /// # let y: u32 = 0;
1653 /// # let x: u32 = 100;
1654 /// let add = x.checked_add(y).unwrap_or(u32::MAX);
1655 /// let sub = x.checked_sub(y).unwrap_or(u32::MIN);
1658 /// can be written using dedicated methods for saturating addition/subtraction as:
1661 /// # let y: u32 = 0;
1662 /// # let x: u32 = 100;
1663 /// let add = x.saturating_add(y);
1664 /// let sub = x.saturating_sub(y);
1666 #[clippy::version = "1.39.0"]
1667 pub MANUAL_SATURATING_ARITHMETIC,
1669 "`.checked_add/sub(x).unwrap_or(MAX/MIN)`"
1672 declare_clippy_lint! {
1673 /// ### What it does
1674 /// Checks for `offset(_)`, `wrapping_`{`add`, `sub`}, etc. on raw pointers to
1675 /// zero-sized types
1677 /// ### Why is this bad?
1678 /// This is a no-op, and likely unintended
1682 /// unsafe { (&() as *const ()).offset(1) };
1684 #[clippy::version = "1.41.0"]
1687 "Check for offset calculations on raw pointers to zero-sized types"
1690 declare_clippy_lint! {
1691 /// ### What it does
1692 /// Checks for `FileType::is_file()`.
1694 /// ### Why is this bad?
1695 /// When people testing a file type with `FileType::is_file`
1696 /// they are testing whether a path is something they can get bytes from. But
1697 /// `is_file` doesn't cover special file types in unix-like systems, and doesn't cover
1698 /// symlink in windows. Using `!FileType::is_dir()` is a better way to that intention.
1703 /// let metadata = std::fs::metadata("foo.txt")?;
1704 /// let filetype = metadata.file_type();
1706 /// if filetype.is_file() {
1709 /// # Ok::<_, std::io::Error>(())
1713 /// should be written as:
1717 /// let metadata = std::fs::metadata("foo.txt")?;
1718 /// let filetype = metadata.file_type();
1720 /// if !filetype.is_dir() {
1723 /// # Ok::<_, std::io::Error>(())
1726 #[clippy::version = "1.42.0"]
1727 pub FILETYPE_IS_FILE,
1729 "`FileType::is_file` is not recommended to test for readable file type"
1732 declare_clippy_lint! {
1733 /// ### What it does
1734 /// Checks for usage of `_.as_ref().map(Deref::deref)` or its aliases (such as String::as_str).
1736 /// ### Why is this bad?
1737 /// Readability, this can be written more concisely as
1742 /// # let opt = Some("".to_string());
1743 /// opt.as_ref().map(String::as_str)
1746 /// Can be written as
1748 /// # let opt = Some("".to_string());
1752 #[clippy::version = "1.42.0"]
1753 pub OPTION_AS_REF_DEREF,
1755 "using `as_ref().map(Deref::deref)`, which is more succinctly expressed as `as_deref()`"
1758 declare_clippy_lint! {
1759 /// ### What it does
1760 /// Checks for usage of `iter().next()` on a Slice or an Array
1762 /// ### Why is this bad?
1763 /// These can be shortened into `.get()`
1767 /// # let a = [1, 2, 3];
1768 /// # let b = vec![1, 2, 3];
1769 /// a[2..].iter().next();
1770 /// b.iter().next();
1772 /// should be written as:
1774 /// # let a = [1, 2, 3];
1775 /// # let b = vec![1, 2, 3];
1779 #[clippy::version = "1.46.0"]
1780 pub ITER_NEXT_SLICE,
1782 "using `.iter().next()` on a sliced array, which can be shortened to just `.get()`"
1785 declare_clippy_lint! {
1786 /// ### What it does
1787 /// Warns when using `push_str`/`insert_str` with a single-character string literal
1788 /// where `push`/`insert` with a `char` would work fine.
1790 /// ### Why is this bad?
1791 /// It's less clear that we are pushing a single character.
1795 /// # let mut string = String::new();
1796 /// string.insert_str(0, "R");
1797 /// string.push_str("R");
1802 /// # let mut string = String::new();
1803 /// string.insert(0, 'R');
1804 /// string.push('R');
1806 #[clippy::version = "1.49.0"]
1807 pub SINGLE_CHAR_ADD_STR,
1809 "`push_str()` or `insert_str()` used with a single-character string literal as parameter"
1812 declare_clippy_lint! {
1813 /// ### What it does
1814 /// As the counterpart to `or_fun_call`, this lint looks for unnecessary
1815 /// lazily evaluated closures on `Option` and `Result`.
1817 /// This lint suggests changing the following functions, when eager evaluation results in
1819 /// - `unwrap_or_else` to `unwrap_or`
1820 /// - `and_then` to `and`
1821 /// - `or_else` to `or`
1822 /// - `get_or_insert_with` to `get_or_insert`
1823 /// - `ok_or_else` to `ok_or`
1825 /// ### Why is this bad?
1826 /// Using eager evaluation is shorter and simpler in some cases.
1828 /// ### Known problems
1829 /// It is possible, but not recommended for `Deref` and `Index` to have
1830 /// side effects. Eagerly evaluating them can change the semantics of the program.
1834 /// // example code where clippy issues a warning
1835 /// let opt: Option<u32> = None;
1837 /// opt.unwrap_or_else(|| 42);
1841 /// let opt: Option<u32> = None;
1843 /// opt.unwrap_or(42);
1845 #[clippy::version = "1.48.0"]
1846 pub UNNECESSARY_LAZY_EVALUATIONS,
1848 "using unnecessary lazy evaluation, which can be replaced with simpler eager evaluation"
1851 declare_clippy_lint! {
1852 /// ### What it does
1853 /// Checks for usage of `_.map(_).collect::<Result<(), _>()`.
1855 /// ### Why is this bad?
1856 /// Using `try_for_each` instead is more readable and idiomatic.
1860 /// (0..3).map(|t| Err(t)).collect::<Result<(), _>>();
1864 /// (0..3).try_for_each(|t| Err(t));
1866 #[clippy::version = "1.49.0"]
1867 pub MAP_COLLECT_RESULT_UNIT,
1869 "using `.map(_).collect::<Result<(),_>()`, which can be replaced with `try_for_each`"
1872 declare_clippy_lint! {
1873 /// ### What it does
1874 /// Checks for `from_iter()` function calls on types that implement the `FromIterator`
1877 /// ### Why is this bad?
1878 /// It is recommended style to use collect. See
1879 /// [FromIterator documentation](https://doc.rust-lang.org/std/iter/trait.FromIterator.html)
1883 /// let five_fives = std::iter::repeat(5).take(5);
1885 /// let v = Vec::from_iter(five_fives);
1887 /// assert_eq!(v, vec![5, 5, 5, 5, 5]);
1891 /// let five_fives = std::iter::repeat(5).take(5);
1893 /// let v: Vec<i32> = five_fives.collect();
1895 /// assert_eq!(v, vec![5, 5, 5, 5, 5]);
1897 #[clippy::version = "1.49.0"]
1898 pub FROM_ITER_INSTEAD_OF_COLLECT,
1900 "use `.collect()` instead of `::from_iter()`"
1903 declare_clippy_lint! {
1904 /// ### What it does
1905 /// Checks for usage of `inspect().for_each()`.
1907 /// ### Why is this bad?
1908 /// It is the same as performing the computation
1909 /// inside `inspect` at the beginning of the closure in `for_each`.
1913 /// [1,2,3,4,5].iter()
1914 /// .inspect(|&x| println!("inspect the number: {}", x))
1915 /// .for_each(|&x| {
1916 /// assert!(x >= 0);
1919 /// Can be written as
1921 /// [1,2,3,4,5].iter()
1922 /// .for_each(|&x| {
1923 /// println!("inspect the number: {}", x);
1924 /// assert!(x >= 0);
1927 #[clippy::version = "1.51.0"]
1928 pub INSPECT_FOR_EACH,
1930 "using `.inspect().for_each()`, which can be replaced with `.for_each()`"
1933 declare_clippy_lint! {
1934 /// ### What it does
1935 /// Checks for usage of `filter_map(|x| x)`.
1937 /// ### Why is this bad?
1938 /// Readability, this can be written more concisely by using `flatten`.
1942 /// # let iter = vec![Some(1)].into_iter();
1943 /// iter.filter_map(|x| x);
1947 /// # let iter = vec![Some(1)].into_iter();
1950 #[clippy::version = "1.52.0"]
1951 pub FILTER_MAP_IDENTITY,
1953 "call to `filter_map` where `flatten` is sufficient"
1956 declare_clippy_lint! {
1957 /// ### What it does
1958 /// Checks for instances of `map(f)` where `f` is the identity function.
1960 /// ### Why is this bad?
1961 /// It can be written more concisely without the call to `map`.
1965 /// let x = [1, 2, 3];
1966 /// let y: Vec<_> = x.iter().map(|x| x).map(|x| 2*x).collect();
1970 /// let x = [1, 2, 3];
1971 /// let y: Vec<_> = x.iter().map(|x| 2*x).collect();
1973 #[clippy::version = "1.47.0"]
1976 "using iterator.map(|x| x)"
1979 declare_clippy_lint! {
1980 /// ### What it does
1981 /// Checks for the use of `.bytes().nth()`.
1983 /// ### Why is this bad?
1984 /// `.as_bytes().get()` is more efficient and more
1989 /// # #[allow(unused)]
1990 /// "Hello".bytes().nth(3);
1995 /// # #[allow(unused)]
1996 /// "Hello".as_bytes().get(3);
1998 #[clippy::version = "1.52.0"]
2001 "replace `.bytes().nth()` with `.as_bytes().get()`"
2004 declare_clippy_lint! {
2005 /// ### What it does
2006 /// Checks for the usage of `_.to_owned()`, `vec.to_vec()`, or similar when calling `_.clone()` would be clearer.
2008 /// ### Why is this bad?
2009 /// These methods do the same thing as `_.clone()` but may be confusing as
2010 /// to why we are calling `to_vec` on something that is already a `Vec` or calling `to_owned` on something that is already owned.
2014 /// let a = vec![1, 2, 3];
2015 /// let b = a.to_vec();
2016 /// let c = a.to_owned();
2020 /// let a = vec![1, 2, 3];
2021 /// let b = a.clone();
2022 /// let c = a.clone();
2024 #[clippy::version = "1.52.0"]
2027 "implicitly cloning a value by invoking a function on its dereferenced type"
2030 declare_clippy_lint! {
2031 /// ### What it does
2032 /// Checks for the use of `.iter().count()`.
2034 /// ### Why is this bad?
2035 /// `.len()` is more efficient and more
2040 /// # #![allow(unused)]
2041 /// let some_vec = vec![0, 1, 2, 3];
2043 /// some_vec.iter().count();
2044 /// &some_vec[..].iter().count();
2049 /// let some_vec = vec![0, 1, 2, 3];
2052 /// &some_vec[..].len();
2054 #[clippy::version = "1.52.0"]
2057 "replace `.iter().count()` with `.len()`"
2060 declare_clippy_lint! {
2061 /// ### What it does
2062 /// Checks for the usage of `_.to_owned()`, on a `Cow<'_, _>`.
2064 /// ### Why is this bad?
2065 /// Calling `to_owned()` on a `Cow` creates a clone of the `Cow`
2066 /// itself, without taking ownership of the `Cow` contents (i.e.
2067 /// it's equivalent to calling `Cow::clone`).
2068 /// The similarly named `into_owned` method, on the other hand,
2069 /// clones the `Cow` contents, effectively turning any `Cow::Borrowed`
2070 /// into a `Cow::Owned`.
2072 /// Given the potential ambiguity, consider replacing `to_owned`
2073 /// with `clone` for better readability or, if getting a `Cow::Owned`
2074 /// was the original intent, using `into_owned` instead.
2078 /// # use std::borrow::Cow;
2079 /// let s = "Hello world!";
2080 /// let cow = Cow::Borrowed(s);
2082 /// let data = cow.to_owned();
2083 /// assert!(matches!(data, Cow::Borrowed(_)))
2087 /// # use std::borrow::Cow;
2088 /// let s = "Hello world!";
2089 /// let cow = Cow::Borrowed(s);
2091 /// let data = cow.clone();
2092 /// assert!(matches!(data, Cow::Borrowed(_)))
2096 /// # use std::borrow::Cow;
2097 /// let s = "Hello world!";
2098 /// let cow = Cow::Borrowed(s);
2100 /// let _data: String = cow.into_owned();
2102 #[clippy::version = "1.65.0"]
2103 pub SUSPICIOUS_TO_OWNED,
2105 "calls to `to_owned` on a `Cow<'_, _>` might not do what they are expected"
2108 declare_clippy_lint! {
2109 /// ### What it does
2110 /// Checks for calls to [`splitn`]
2111 /// (https://doc.rust-lang.org/std/primitive.str.html#method.splitn) and
2112 /// related functions with either zero or one splits.
2114 /// ### Why is this bad?
2115 /// These calls don't actually split the value and are
2116 /// likely to be intended as a different number.
2121 /// for x in s.splitn(1, ":") {
2129 /// for x in s.splitn(2, ":") {
2133 #[clippy::version = "1.54.0"]
2134 pub SUSPICIOUS_SPLITN,
2136 "checks for `.splitn(0, ..)` and `.splitn(1, ..)`"
2139 declare_clippy_lint! {
2140 /// ### What it does
2141 /// Checks for manual implementations of `str::repeat`
2143 /// ### Why is this bad?
2144 /// These are both harder to read, as well as less performant.
2148 /// let x: String = std::iter::repeat('x').take(10).collect();
2153 /// let x: String = "x".repeat(10);
2155 #[clippy::version = "1.54.0"]
2156 pub MANUAL_STR_REPEAT,
2158 "manual implementation of `str::repeat`"
2161 declare_clippy_lint! {
2162 /// ### What it does
2163 /// Checks for usages of `str::splitn(2, _)`
2165 /// ### Why is this bad?
2166 /// `split_once` is both clearer in intent and slightly more efficient.
2170 /// let s = "key=value=add";
2171 /// let (key, value) = s.splitn(2, '=').next_tuple()?;
2172 /// let value = s.splitn(2, '=').nth(1)?;
2174 /// let mut parts = s.splitn(2, '=');
2175 /// let key = parts.next()?;
2176 /// let value = parts.next()?;
2181 /// let s = "key=value=add";
2182 /// let (key, value) = s.split_once('=')?;
2183 /// let value = s.split_once('=')?.1;
2185 /// let (key, value) = s.split_once('=')?;
2189 /// The multiple statement variant currently only detects `iter.next()?`/`iter.next().unwrap()`
2190 /// in two separate `let` statements that immediately follow the `splitn()`
2191 #[clippy::version = "1.57.0"]
2192 pub MANUAL_SPLIT_ONCE,
2194 "replace `.splitn(2, pat)` with `.split_once(pat)`"
2197 declare_clippy_lint! {
2198 /// ### What it does
2199 /// Checks for usages of `str::splitn` (or `str::rsplitn`) where using `str::split` would be the same.
2200 /// ### Why is this bad?
2201 /// The function `split` is simpler and there is no performance difference in these cases, considering
2202 /// that both functions return a lazy iterator.
2205 /// let str = "key=value=add";
2206 /// let _ = str.splitn(3, '=').next().unwrap();
2211 /// let str = "key=value=add";
2212 /// let _ = str.split('=').next().unwrap();
2214 #[clippy::version = "1.59.0"]
2215 pub NEEDLESS_SPLITN,
2217 "usages of `str::splitn` that can be replaced with `str::split`"
2220 declare_clippy_lint! {
2221 /// ### What it does
2222 /// Checks for unnecessary calls to [`ToOwned::to_owned`](https://doc.rust-lang.org/std/borrow/trait.ToOwned.html#tymethod.to_owned)
2223 /// and other `to_owned`-like functions.
2225 /// ### Why is this bad?
2226 /// The unnecessary calls result in useless allocations.
2228 /// ### Known problems
2229 /// `unnecessary_to_owned` can falsely trigger if `IntoIterator::into_iter` is applied to an
2230 /// owned copy of a resource and the resource is later used mutably. See
2231 /// [#8148](https://github.com/rust-lang/rust-clippy/issues/8148).
2235 /// let path = std::path::Path::new("x");
2236 /// foo(&path.to_string_lossy().to_string());
2237 /// fn foo(s: &str) {}
2241 /// let path = std::path::Path::new("x");
2242 /// foo(&path.to_string_lossy());
2243 /// fn foo(s: &str) {}
2245 #[clippy::version = "1.59.0"]
2246 pub UNNECESSARY_TO_OWNED,
2248 "unnecessary calls to `to_owned`-like functions"
2251 declare_clippy_lint! {
2252 /// ### What it does
2253 /// Checks for use of `.collect::<Vec<String>>().join("")` on iterators.
2255 /// ### Why is this bad?
2256 /// `.collect::<String>()` is more concise and might be more performant
2260 /// let vector = vec!["hello", "world"];
2261 /// let output = vector.iter().map(|item| item.to_uppercase()).collect::<Vec<String>>().join("");
2262 /// println!("{}", output);
2264 /// The correct use would be:
2266 /// let vector = vec!["hello", "world"];
2267 /// let output = vector.iter().map(|item| item.to_uppercase()).collect::<String>();
2268 /// println!("{}", output);
2270 /// ### Known problems
2271 /// While `.collect::<String>()` is sometimes more performant, there are cases where
2272 /// using `.collect::<String>()` over `.collect::<Vec<String>>().join("")`
2273 /// will prevent loop unrolling and will result in a negative performance impact.
2275 /// Additionally, differences have been observed between aarch64 and x86_64 assembly output,
2276 /// with aarch64 tending to producing faster assembly in more cases when using `.collect::<String>()`
2277 #[clippy::version = "1.61.0"]
2278 pub UNNECESSARY_JOIN,
2280 "using `.collect::<Vec<String>>().join(\"\")` on an iterator"
2283 declare_clippy_lint! {
2284 /// ### What it does
2285 /// Checks for no-op uses of `Option::{as_deref, as_deref_mut}`,
2286 /// for example, `Option<&T>::as_deref()` returns the same type.
2288 /// ### Why is this bad?
2289 /// Redundant code and improving readability.
2293 /// let a = Some(&1);
2294 /// let b = a.as_deref(); // goes from Option<&i32> to Option<&i32>
2299 /// let a = Some(&1);
2302 #[clippy::version = "1.57.0"]
2303 pub NEEDLESS_OPTION_AS_DEREF,
2305 "no-op use of `deref` or `deref_mut` method to `Option`."
2308 declare_clippy_lint! {
2309 /// ### What it does
2310 /// Finds usages of [`char::is_digit`](https://doc.rust-lang.org/stable/std/primitive.char.html#method.is_digit) that
2311 /// can be replaced with [`is_ascii_digit`](https://doc.rust-lang.org/stable/std/primitive.char.html#method.is_ascii_digit) or
2312 /// [`is_ascii_hexdigit`](https://doc.rust-lang.org/stable/std/primitive.char.html#method.is_ascii_hexdigit).
2314 /// ### Why is this bad?
2315 /// `is_digit(..)` is slower and requires specifying the radix.
2319 /// let c: char = '6';
2325 /// let c: char = '6';
2326 /// c.is_ascii_digit();
2327 /// c.is_ascii_hexdigit();
2329 #[clippy::version = "1.62.0"]
2330 pub IS_DIGIT_ASCII_RADIX,
2332 "use of `char::is_digit(..)` with literal radix of 10 or 16"
2335 declare_clippy_lint! {
2336 /// ### What it does
2337 /// Checks for calling `take` function after `as_ref`.
2339 /// ### Why is this bad?
2340 /// Redundant code. `take` writes `None` to its argument.
2341 /// In this case the modification is useless as it's a temporary that cannot be read from afterwards.
2345 /// let x = Some(3);
2346 /// x.as_ref().take();
2350 /// let x = Some(3);
2353 #[clippy::version = "1.62.0"]
2354 pub NEEDLESS_OPTION_TAKE,
2356 "using `.as_ref().take()` on a temporary value"
2359 declare_clippy_lint! {
2360 /// ### What it does
2361 /// Checks for `replace` statements which have no effect.
2363 /// ### Why is this bad?
2364 /// It's either a mistake or confusing.
2368 /// "1234".replace("12", "12");
2369 /// "1234".replacen("12", "12", 1);
2371 #[clippy::version = "1.63.0"]
2372 pub NO_EFFECT_REPLACE,
2374 "replace with no effect"
2377 declare_clippy_lint! {
2378 /// ### What it does
2379 /// Checks for usages of `.then_some(..).unwrap_or(..)`
2381 /// ### Why is this bad?
2382 /// This can be written more clearly with `if .. else ..`
2385 /// This lint currently only looks for usages of
2386 /// `.then_some(..).unwrap_or(..)`, but will be expanded
2387 /// to account for similar patterns.
2392 /// x.then_some("a").unwrap_or("b");
2397 /// if x { "a" } else { "b" };
2399 #[clippy::version = "1.64.0"]
2400 pub OBFUSCATED_IF_ELSE,
2402 "use of `.then_some(..).unwrap_or(..)` can be written \
2403 more clearly with `if .. else ..`"
2406 declare_clippy_lint! {
2407 /// ### What it does
2409 /// Checks for calls to `iter`, `iter_mut` or `into_iter` on collections containing a single item
2411 /// ### Why is this bad?
2413 /// It is simpler to use the once function from the standard library:
2418 /// let a = [123].iter();
2419 /// let b = Some(123).into_iter();
2424 /// let a = iter::once(&123);
2425 /// let b = iter::once(123);
2428 /// ### Known problems
2430 /// The type of the resulting iterator might become incompatible with its usage
2431 #[clippy::version = "1.65.0"]
2432 pub ITER_ON_SINGLE_ITEMS,
2434 "Iterator for array of length 1"
2437 declare_clippy_lint! {
2438 /// ### What it does
2440 /// Checks for calls to `iter`, `iter_mut` or `into_iter` on empty collections
2442 /// ### Why is this bad?
2444 /// It is simpler to use the empty function from the standard library:
2449 /// use std::{slice, option};
2450 /// let a: slice::Iter<i32> = [].iter();
2451 /// let f: option::IntoIter<i32> = None.into_iter();
2456 /// let a: iter::Empty<i32> = iter::empty();
2457 /// let b: iter::Empty<i32> = iter::empty();
2460 /// ### Known problems
2462 /// The type of the resulting iterator might become incompatible with its usage
2463 #[clippy::version = "1.65.0"]
2464 pub ITER_ON_EMPTY_COLLECTIONS,
2466 "Iterator for empty array"
2469 declare_clippy_lint! {
2470 /// ### What it does
2471 /// Checks for naive byte counts
2473 /// ### Why is this bad?
2474 /// The [`bytecount`](https://crates.io/crates/bytecount)
2475 /// crate has methods to count your bytes faster, especially for large slices.
2477 /// ### Known problems
2478 /// If you have predominantly small slices, the
2479 /// `bytecount::count(..)` method may actually be slower. However, if you can
2480 /// ensure that less than 2³²-1 matches arise, the `naive_count_32(..)` can be
2481 /// faster in those cases.
2485 /// # let vec = vec![1_u8];
2486 /// let count = vec.iter().filter(|x| **x == 0u8).count();
2491 /// # let vec = vec![1_u8];
2492 /// let count = bytecount::count(&vec, 0u8);
2494 #[clippy::version = "pre 1.29.0"]
2495 pub NAIVE_BYTECOUNT,
2497 "use of naive `<slice>.filter(|&x| x == y).count()` to count byte values"
2500 declare_clippy_lint! {
2501 /// ### What it does
2502 /// It checks for `str::bytes().count()` and suggests replacing it with
2505 /// ### Why is this bad?
2506 /// `str::bytes().count()` is longer and may not be as performant as using
2511 /// "hello".bytes().count();
2512 /// String::from("hello").bytes().count();
2517 /// String::from("hello").len();
2519 #[clippy::version = "1.62.0"]
2520 pub BYTES_COUNT_TO_LEN,
2522 "Using `bytes().count()` when `len()` performs the same functionality"
2525 declare_clippy_lint! {
2526 /// ### What it does
2527 /// Checks for calls to `ends_with` with possible file extensions
2528 /// and suggests to use a case-insensitive approach instead.
2530 /// ### Why is this bad?
2531 /// `ends_with` is case-sensitive and may not detect files with a valid extension.
2535 /// fn is_rust_file(filename: &str) -> bool {
2536 /// filename.ends_with(".rs")
2541 /// fn is_rust_file(filename: &str) -> bool {
2542 /// let filename = std::path::Path::new(filename);
2543 /// filename.extension()
2544 /// .map_or(false, |ext| ext.eq_ignore_ascii_case("rs"))
2547 #[clippy::version = "1.51.0"]
2548 pub CASE_SENSITIVE_FILE_EXTENSION_COMPARISONS,
2550 "Checks for calls to ends_with with case-sensitive file extensions"
2553 declare_clippy_lint! {
2554 /// ### What it does
2555 /// Checks for using `x.get(0)` instead of
2558 /// ### Why is this bad?
2559 /// Using `x.first()` is easier to read and has the same
2564 /// let x = vec![2, 3, 5];
2565 /// let first_element = x.get(0);
2570 /// let x = vec![2, 3, 5];
2571 /// let first_element = x.first();
2573 #[clippy::version = "1.63.0"]
2576 "Using `x.get(0)` when `x.first()` is simpler"
2579 declare_clippy_lint! {
2580 /// ### What it does
2582 /// Finds patterns that reimplement `Option::ok_or`.
2584 /// ### Why is this bad?
2586 /// Concise code helps focusing on behavior instead of boilerplate.
2590 /// let foo: Option<i32> = None;
2591 /// foo.map_or(Err("error"), |v| Ok(v));
2596 /// let foo: Option<i32> = None;
2597 /// foo.ok_or("error");
2599 #[clippy::version = "1.49.0"]
2602 "finds patterns that can be encoded more concisely with `Option::ok_or`"
2605 declare_clippy_lint! {
2606 /// ### What it does
2607 /// Checks for usage of `map(|x| x.clone())` or
2608 /// dereferencing closures for `Copy` types, on `Iterator` or `Option`,
2609 /// and suggests `cloned()` or `copied()` instead
2611 /// ### Why is this bad?
2612 /// Readability, this can be written more concisely
2616 /// let x = vec![42, 43];
2617 /// let y = x.iter();
2618 /// let z = y.map(|i| *i);
2621 /// The correct use would be:
2624 /// let x = vec![42, 43];
2625 /// let y = x.iter();
2626 /// let z = y.cloned();
2628 #[clippy::version = "pre 1.29.0"]
2631 "using `iterator.map(|x| x.clone())`, or dereferencing closures for `Copy` types"
2634 declare_clippy_lint! {
2635 /// ### What it does
2636 /// Checks for instances of `map_err(|_| Some::Enum)`
2638 /// ### Why is this bad?
2639 /// This `map_err` throws away the original error rather than allowing the enum to contain and report the cause of the error
2646 /// #[derive(Debug)]
2652 /// impl fmt::Display for Error {
2653 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2655 /// Error::Indivisible => write!(f, "could not divide input by three"),
2656 /// Error::Remainder(remainder) => write!(
2658 /// "input is not divisible by three, remainder = {}",
2665 /// impl std::error::Error for Error {}
2667 /// fn divisible_by_3(input: &str) -> Result<(), Error> {
2670 /// .map_err(|_| Error::Indivisible)
2672 /// .and_then(|remainder| {
2673 /// if remainder == 0 {
2676 /// Err(Error::Remainder(remainder as u8))
2684 /// use std::{fmt, num::ParseIntError};
2686 /// #[derive(Debug)]
2688 /// Indivisible(ParseIntError),
2692 /// impl fmt::Display for Error {
2693 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2695 /// Error::Indivisible(_) => write!(f, "could not divide input by three"),
2696 /// Error::Remainder(remainder) => write!(
2698 /// "input is not divisible by three, remainder = {}",
2705 /// impl std::error::Error for Error {
2706 /// fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
2708 /// Error::Indivisible(source) => Some(source),
2714 /// fn divisible_by_3(input: &str) -> Result<(), Error> {
2717 /// .map_err(Error::Indivisible)
2719 /// .and_then(|remainder| {
2720 /// if remainder == 0 {
2723 /// Err(Error::Remainder(remainder as u8))
2728 #[clippy::version = "1.48.0"]
2731 "`map_err` should not ignore the original error"
2734 declare_clippy_lint! {
2735 /// ### What it does
2736 /// Checks for `&mut Mutex::lock` calls
2738 /// ### Why is this bad?
2739 /// `Mutex::lock` is less efficient than
2740 /// calling `Mutex::get_mut`. In addition you also have a statically
2741 /// guarantee that the mutex isn't locked, instead of just a runtime
2746 /// use std::sync::{Arc, Mutex};
2748 /// let mut value_rc = Arc::new(Mutex::new(42_u8));
2749 /// let value_mutex = Arc::get_mut(&mut value_rc).unwrap();
2751 /// let mut value = value_mutex.lock().unwrap();
2756 /// use std::sync::{Arc, Mutex};
2758 /// let mut value_rc = Arc::new(Mutex::new(42_u8));
2759 /// let value_mutex = Arc::get_mut(&mut value_rc).unwrap();
2761 /// let value = value_mutex.get_mut().unwrap();
2764 #[clippy::version = "1.49.0"]
2767 "`&mut Mutex::lock` does unnecessary locking"
2770 declare_clippy_lint! {
2771 /// ### What it does
2772 /// Checks for duplicate open options as well as combinations
2773 /// that make no sense.
2775 /// ### Why is this bad?
2776 /// In the best case, the code will be harder to read than
2777 /// necessary. I don't know the worst case.
2781 /// use std::fs::OpenOptions;
2783 /// OpenOptions::new().read(true).truncate(true);
2785 #[clippy::version = "pre 1.29.0"]
2786 pub NONSENSICAL_OPEN_OPTIONS,
2788 "nonsensical combination of options for opening a file"
2791 declare_clippy_lint! {
2792 /// ### What it does
2793 ///* Checks for [push](https://doc.rust-lang.org/std/path/struct.PathBuf.html#method.push)
2794 /// calls on `PathBuf` that can cause overwrites.
2796 /// ### Why is this bad?
2797 /// Calling `push` with a root path at the start can overwrite the
2798 /// previous defined path.
2802 /// use std::path::PathBuf;
2804 /// let mut x = PathBuf::from("/foo");
2806 /// assert_eq!(x, PathBuf::from("/bar"));
2808 /// Could be written:
2811 /// use std::path::PathBuf;
2813 /// let mut x = PathBuf::from("/foo");
2815 /// assert_eq!(x, PathBuf::from("/foo/bar"));
2817 #[clippy::version = "1.36.0"]
2818 pub PATH_BUF_PUSH_OVERWRITE,
2820 "calling `push` with file system root on `PathBuf` can overwrite it"
2823 declare_clippy_lint! {
2824 /// ### What it does
2825 /// Checks for zipping a collection with the range of
2828 /// ### Why is this bad?
2829 /// The code is better expressed with `.enumerate()`.
2833 /// # let x = vec![1];
2834 /// let _ = x.iter().zip(0..x.len());
2839 /// # let x = vec![1];
2840 /// let _ = x.iter().enumerate();
2842 #[clippy::version = "pre 1.29.0"]
2843 pub RANGE_ZIP_WITH_LEN,
2845 "zipping iterator with a range when `enumerate()` would do"
2848 declare_clippy_lint! {
2849 /// ### What it does
2850 /// Checks for usage of `.repeat(1)` and suggest the following method for each types.
2851 /// - `.to_string()` for `str`
2852 /// - `.clone()` for `String`
2853 /// - `.to_vec()` for `slice`
2855 /// The lint will evaluate constant expressions and values as arguments of `.repeat(..)` and emit a message if
2856 /// they are equivalent to `1`. (Related discussion in [rust-clippy#7306](https://github.com/rust-lang/rust-clippy/issues/7306))
2858 /// ### Why is this bad?
2859 /// For example, `String.repeat(1)` is equivalent to `.clone()`. If cloning
2860 /// the string is the intention behind this, `clone()` should be used.
2865 /// let x = String::from("hello world").repeat(1);
2871 /// let x = String::from("hello world").clone();
2874 #[clippy::version = "1.47.0"]
2877 "using `.repeat(1)` instead of `String.clone()`, `str.to_string()` or `slice.to_vec()` "
2880 declare_clippy_lint! {
2881 /// ### What it does
2882 /// When sorting primitive values (integers, bools, chars, as well
2883 /// as arrays, slices, and tuples of such items), it is typically better to
2884 /// use an unstable sort than a stable sort.
2886 /// ### Why is this bad?
2887 /// Typically, using a stable sort consumes more memory and cpu cycles.
2888 /// Because values which compare equal are identical, preserving their
2889 /// relative order (the guarantee that a stable sort provides) means
2890 /// nothing, while the extra costs still apply.
2892 /// ### Known problems
2894 /// As pointed out in
2895 /// [issue #8241](https://github.com/rust-lang/rust-clippy/issues/8241),
2896 /// a stable sort can instead be significantly faster for certain scenarios
2897 /// (eg. when a sorted vector is extended with new data and resorted).
2899 /// For more information and benchmarking results, please refer to the
2900 /// issue linked above.
2904 /// let mut vec = vec![2, 1, 3];
2909 /// let mut vec = vec![2, 1, 3];
2910 /// vec.sort_unstable();
2912 #[clippy::version = "1.47.0"]
2913 pub STABLE_SORT_PRIMITIVE,
2915 "use of sort() when sort_unstable() is equivalent"
2918 declare_clippy_lint! {
2919 /// ### What it does
2920 /// Detects `().hash(_)`.
2922 /// ### Why is this bad?
2923 /// Hashing a unit value doesn't do anything as the implementation of `Hash` for `()` is a no-op.
2927 /// # use std::hash::Hash;
2928 /// # use std::collections::hash_map::DefaultHasher;
2929 /// # enum Foo { Empty, WithValue(u8) }
2931 /// # let mut state = DefaultHasher::new();
2932 /// # let my_enum = Foo::Empty;
2934 /// Empty => ().hash(&mut state),
2935 /// WithValue(x) => x.hash(&mut state),
2940 /// # use std::hash::Hash;
2941 /// # use std::collections::hash_map::DefaultHasher;
2942 /// # enum Foo { Empty, WithValue(u8) }
2944 /// # let mut state = DefaultHasher::new();
2945 /// # let my_enum = Foo::Empty;
2947 /// Empty => 0_u8.hash(&mut state),
2948 /// WithValue(x) => x.hash(&mut state),
2951 #[clippy::version = "1.58.0"]
2954 "hashing a unit value, which does nothing"
2957 declare_clippy_lint! {
2958 /// ### What it does
2959 /// Detects uses of `Vec::sort_by` passing in a closure
2960 /// which compares the two arguments, either directly or indirectly.
2962 /// ### Why is this bad?
2963 /// It is more clear to use `Vec::sort_by_key` (or `Vec::sort` if
2964 /// possible) than to use `Vec::sort_by` and a more complicated
2967 /// ### Known problems
2968 /// If the suggested `Vec::sort_by_key` uses Reverse and it isn't already
2969 /// imported by a use statement, then it will need to be added manually.
2974 /// # impl A { fn foo(&self) {} }
2975 /// # let mut vec: Vec<A> = Vec::new();
2976 /// vec.sort_by(|a, b| a.foo().cmp(&b.foo()));
2981 /// # impl A { fn foo(&self) {} }
2982 /// # let mut vec: Vec<A> = Vec::new();
2983 /// vec.sort_by_key(|a| a.foo());
2985 #[clippy::version = "1.46.0"]
2986 pub UNNECESSARY_SORT_BY,
2988 "Use of `Vec::sort_by` when `Vec::sort_by_key` or `Vec::sort` would be clearer"
2991 declare_clippy_lint! {
2992 /// ### What it does
2993 /// Finds occurrences of `Vec::resize(0, an_int)`
2995 /// ### Why is this bad?
2996 /// This is probably an argument inversion mistake.
3000 /// vec!(1, 2, 3, 4, 5).resize(0, 5)
3005 /// vec!(1, 2, 3, 4, 5).clear()
3007 #[clippy::version = "1.46.0"]
3008 pub VEC_RESIZE_TO_ZERO,
3010 "emptying a vector with `resize(0, an_int)` instead of `clear()` is probably an argument inversion mistake"
3013 declare_clippy_lint! {
3014 /// ### What it does
3015 /// Checks for use of File::read_to_end and File::read_to_string.
3017 /// ### Why is this bad?
3018 /// `fs::{read, read_to_string}` provide the same functionality when `buf` is empty with fewer imports and no intermediate values.
3019 /// See also: [fs::read docs](https://doc.rust-lang.org/std/fs/fn.read.html), [fs::read_to_string docs](https://doc.rust-lang.org/std/fs/fn.read_to_string.html)
3023 /// # use std::io::Read;
3024 /// # use std::fs::File;
3025 /// let mut f = File::open("foo.txt").unwrap();
3026 /// let mut bytes = Vec::new();
3027 /// f.read_to_end(&mut bytes).unwrap();
3029 /// Can be written more concisely as
3032 /// let mut bytes = fs::read("foo.txt").unwrap();
3034 #[clippy::version = "1.44.0"]
3035 pub VERBOSE_FILE_READS,
3037 "use of `File::read_to_end` or `File::read_to_string`"
3040 declare_clippy_lint! {
3041 /// ### What it does
3043 /// Checks for iterating a map (`HashMap` or `BTreeMap`) and
3044 /// ignoring either the keys or values.
3046 /// ### Why is this bad?
3048 /// Readability. There are `keys` and `values` methods that
3049 /// can be used to express that we only need the keys or the values.
3054 /// # use std::collections::HashMap;
3055 /// let map: HashMap<u32, u32> = HashMap::new();
3056 /// let values = map.iter().map(|(_, value)| value).collect::<Vec<_>>();
3061 /// # use std::collections::HashMap;
3062 /// let map: HashMap<u32, u32> = HashMap::new();
3063 /// let values = map.values().collect::<Vec<_>>();
3065 #[clippy::version = "1.65.0"]
3068 "iterating on map using `iter` when `keys` or `values` would do"
3071 declare_clippy_lint! {
3072 /// ### What it does
3074 /// Checks an argument of `seek` method of `Seek` trait
3075 /// and if it start seek from `SeekFrom::Current(0)`, suggests `stream_position` instead.
3077 /// ### Why is this bad?
3079 /// Readability. Use dedicated method.
3084 /// use std::fs::File;
3085 /// use std::io::{self, Write, Seek, SeekFrom};
3087 /// fn main() -> io::Result<()> {
3088 /// let mut f = File::create("foo.txt")?;
3089 /// f.write_all(b"Hello")?;
3090 /// eprintln!("Written {} bytes", f.seek(SeekFrom::Current(0))?);
3097 /// use std::fs::File;
3098 /// use std::io::{self, Write, Seek, SeekFrom};
3100 /// fn main() -> io::Result<()> {
3101 /// let mut f = File::create("foo.txt")?;
3102 /// f.write_all(b"Hello")?;
3103 /// eprintln!("Written {} bytes", f.stream_position()?);
3108 #[clippy::version = "1.66.0"]
3109 pub SEEK_FROM_CURRENT,
3111 "use dedicated method for seek from current position"
3114 declare_clippy_lint! {
3115 /// ### What it does
3117 /// Checks for jumps to the start of a stream that implements `Seek`
3118 /// and uses the `seek` method providing `Start` as parameter.
3120 /// ### Why is this bad?
3122 /// Readability. There is a specific method that was implemented for
3123 /// this exact scenario.
3128 /// fn foo<T: io::Seek>(t: &mut T) {
3129 /// t.seek(io::SeekFrom::Start(0));
3135 /// fn foo<T: io::Seek>(t: &mut T) {
3139 #[clippy::version = "1.66.0"]
3140 pub SEEK_TO_START_INSTEAD_OF_REWIND,
3142 "jumping to the start of stream using `seek` method"
3145 declare_clippy_lint! {
3146 /// ### What it does
3147 /// Checks for functions collecting an iterator when collect
3150 /// ### Why is this bad?
3151 /// `collect` causes the allocation of a new data structure,
3152 /// when this allocation may not be needed.
3156 /// # let iterator = vec![1].into_iter();
3157 /// let len = iterator.clone().collect::<Vec<_>>().len();
3159 /// let len = iterator.count();
3161 #[clippy::version = "1.30.0"]
3162 pub NEEDLESS_COLLECT,
3164 "collecting an iterator when collect is not needed"
3167 pub struct Methods {
3168 avoid_breaking_exported_api: bool,
3169 msrv: Option<RustcVersion>,
3170 allow_expect_in_tests: bool,
3171 allow_unwrap_in_tests: bool,
3177 avoid_breaking_exported_api: bool,
3178 msrv: Option<RustcVersion>,
3179 allow_expect_in_tests: bool,
3180 allow_unwrap_in_tests: bool,
3183 avoid_breaking_exported_api,
3185 allow_expect_in_tests,
3186 allow_unwrap_in_tests,
3191 impl_lint_pass!(Methods => [
3194 SHOULD_IMPLEMENT_TRAIT,
3195 WRONG_SELF_CONVENTION,
3197 UNWRAP_OR_ELSE_DEFAULT,
3199 RESULT_MAP_OR_INTO_OPTION,
3201 BIND_INSTEAD_OF_MAP,
3210 COLLAPSIBLE_STR_REPLACE,
3211 ITER_OVEREAGER_CLONED,
3212 CLONED_INSTEAD_OF_COPIED,
3214 INEFFICIENT_TO_STRING,
3216 SINGLE_CHAR_PATTERN,
3217 SINGLE_CHAR_ADD_STR,
3221 FILTER_MAP_IDENTITY,
3229 ITERATOR_STEP_BY_ZERO,
3238 STRING_EXTEND_CHARS,
3239 ITER_CLONED_COLLECT,
3243 UNNECESSARY_FILTER_MAP,
3244 UNNECESSARY_FIND_MAP,
3247 UNINIT_ASSUMED_INIT,
3248 MANUAL_SATURATING_ARITHMETIC,
3251 OPTION_AS_REF_DEREF,
3252 UNNECESSARY_LAZY_EVALUATIONS,
3253 MAP_COLLECT_RESULT_UNIT,
3254 FROM_ITER_INSTEAD_OF_COLLECT,
3257 SUSPICIOUS_TO_OWNED,
3263 UNNECESSARY_TO_OWNED,
3266 NEEDLESS_OPTION_AS_DEREF,
3267 IS_DIGIT_ASCII_RADIX,
3268 NEEDLESS_OPTION_TAKE,
3271 ITER_ON_SINGLE_ITEMS,
3272 ITER_ON_EMPTY_COLLECTIONS,
3275 CASE_SENSITIVE_FILE_EXTENSION_COMPARISONS,
3281 NONSENSICAL_OPEN_OPTIONS,
3282 PATH_BUF_PUSH_OVERWRITE,
3285 STABLE_SORT_PRIMITIVE,
3287 UNNECESSARY_SORT_BY,
3292 SEEK_TO_START_INSTEAD_OF_REWIND,
3296 /// Extracts a method call name, args, and `Span` of the method name.
3297 fn method_call<'tcx>(
3298 recv: &'tcx hir::Expr<'tcx>,
3299 ) -> Option<(&'tcx str, &'tcx hir::Expr<'tcx>, &'tcx [hir::Expr<'tcx>], Span, Span)> {
3300 if let ExprKind::MethodCall(path, receiver, args, call_span) = recv.kind {
3301 if !args.iter().any(|e| e.span.from_expansion()) && !receiver.span.from_expansion() {
3302 let name = path.ident.name.as_str();
3303 return Some((name, receiver, args, path.ident.span, call_span));
3309 impl<'tcx> LateLintPass<'tcx> for Methods {
3310 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) {
3311 if expr.span.from_expansion() {
3315 self.check_methods(cx, expr);
3318 hir::ExprKind::Call(func, args) => {
3319 from_iter_instead_of_collect::check(cx, expr, args, func);
3321 hir::ExprKind::MethodCall(method_call, receiver, args, _) => {
3322 let method_span = method_call.ident.span;
3323 or_fun_call::check(cx, expr, method_span, method_call.ident.as_str(), receiver, args);
3324 expect_fun_call::check(cx, expr, method_span, method_call.ident.as_str(), receiver, args);
3325 clone_on_copy::check(cx, expr, method_call.ident.name, receiver, args);
3326 clone_on_ref_ptr::check(cx, expr, method_call.ident.name, receiver, args);
3327 inefficient_to_string::check(cx, expr, method_call.ident.name, receiver, args);
3328 single_char_add_str::check(cx, expr, receiver, args);
3329 into_iter_on_ref::check(cx, expr, method_span, method_call.ident.name, receiver);
3330 single_char_pattern::check(cx, expr, method_call.ident.name, receiver, args);
3331 unnecessary_to_owned::check(cx, expr, method_call.ident.name, receiver, args, self.msrv);
3333 hir::ExprKind::Binary(op, lhs, rhs) if op.node == hir::BinOpKind::Eq || op.node == hir::BinOpKind::Ne => {
3334 let mut info = BinaryExprInfo {
3338 eq: op.node == hir::BinOpKind::Eq,
3340 lint_binary_expr_with_method_call(cx, &mut info);
3346 #[allow(clippy::too_many_lines)]
3347 fn check_impl_item(&mut self, cx: &LateContext<'tcx>, impl_item: &'tcx hir::ImplItem<'_>) {
3348 if in_external_macro(cx.sess(), impl_item.span) {
3351 let name = impl_item.ident.name.as_str();
3352 let parent = cx.tcx.hir().get_parent_item(impl_item.hir_id()).def_id;
3353 let item = cx.tcx.hir().expect_item(parent);
3354 let self_ty = cx.tcx.type_of(item.def_id);
3356 let implements_trait = matches!(item.kind, hir::ItemKind::Impl(hir::Impl { of_trait: Some(_), .. }));
3357 if let hir::ImplItemKind::Fn(ref sig, id) = impl_item.kind {
3358 let method_sig = cx.tcx.fn_sig(impl_item.def_id);
3359 let method_sig = cx.tcx.erase_late_bound_regions(method_sig);
3360 let first_arg_ty_opt = method_sig.inputs().iter().next().copied();
3361 // if this impl block implements a trait, lint in trait definition instead
3362 if !implements_trait && cx.access_levels.is_exported(impl_item.def_id.def_id) {
3363 // check missing trait implementations
3364 for method_config in &TRAIT_METHODS {
3365 if name == method_config.method_name
3366 && sig.decl.inputs.len() == method_config.param_count
3367 && method_config.output_type.matches(&sig.decl.output)
3368 // in case there is no first arg, since we already have checked the number of arguments
3369 // it's should be always true
3370 && first_arg_ty_opt.map_or(true, |first_arg_ty| method_config
3371 .self_kind.matches(cx, self_ty, first_arg_ty)
3373 && fn_header_equals(method_config.fn_header, sig.header)
3374 && method_config.lifetime_param_cond(impl_item)
3378 SHOULD_IMPLEMENT_TRAIT,
3381 "method `{}` can be confused for the standard trait method `{}::{}`",
3382 method_config.method_name, method_config.trait_name, method_config.method_name
3386 "consider implementing the trait `{}` or choosing a less ambiguous method name",
3387 method_config.trait_name
3394 if sig.decl.implicit_self.has_implicit_self()
3395 && !(self.avoid_breaking_exported_api
3396 && cx.access_levels.is_exported(impl_item.def_id.def_id))
3397 && let Some(first_arg) = iter_input_pats(sig.decl, cx.tcx.hir().body(id)).next()
3398 && let Some(first_arg_ty) = first_arg_ty_opt
3400 wrong_self_convention::check(
3412 // if this impl block implements a trait, lint in trait definition instead
3413 if implements_trait {
3417 if let hir::ImplItemKind::Fn(_, _) = impl_item.kind {
3418 let ret_ty = return_ty(cx, impl_item.hir_id());
3420 if contains_ty_adt_constructor_opaque(cx, ret_ty, self_ty) {
3424 if name == "new" && ret_ty != self_ty {
3429 "methods called `new` usually return `Self`",
3435 fn check_trait_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx TraitItem<'_>) {
3436 if in_external_macro(cx.tcx.sess, item.span) {
3441 if let TraitItemKind::Fn(ref sig, _) = item.kind;
3442 if sig.decl.implicit_self.has_implicit_self();
3443 if let Some(first_arg_ty) = sig.decl.inputs.iter().next();
3446 let first_arg_span = first_arg_ty.span;
3447 let first_arg_ty = hir_ty_to_ty(cx.tcx, first_arg_ty);
3448 let self_ty = TraitRef::identity(cx.tcx, item.def_id.to_def_id())
3451 wrong_self_convention::check(
3453 item.ident.name.as_str(),
3464 if item.ident.name == sym::new;
3465 if let TraitItemKind::Fn(_, _) = item.kind;
3466 let ret_ty = return_ty(cx, item.hir_id());
3467 let self_ty = TraitRef::identity(cx.tcx, item.def_id.to_def_id())
3470 if !ret_ty.contains(self_ty);
3477 "methods called `new` usually return `Self`",
3483 extract_msrv_attr!(LateContext);
3487 #[allow(clippy::too_many_lines)]
3488 fn check_methods<'tcx>(&self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
3489 if let Some((name, recv, args, span, call_span)) = method_call(expr) {
3490 match (name, args) {
3491 ("add" | "offset" | "sub" | "wrapping_offset" | "wrapping_add" | "wrapping_sub", [_arg]) => {
3492 zst_offset::check(cx, expr, recv);
3494 ("and_then", [arg]) => {
3495 let biom_option_linted = bind_instead_of_map::OptionAndThenSome::check(cx, expr, recv, arg);
3496 let biom_result_linted = bind_instead_of_map::ResultAndThenOk::check(cx, expr, recv, arg);
3497 if !biom_option_linted && !biom_result_linted {
3498 unnecessary_lazy_eval::check(cx, expr, recv, arg, "and");
3501 ("as_deref" | "as_deref_mut", []) => {
3502 needless_option_as_deref::check(cx, expr, recv, name);
3504 ("as_mut", []) => useless_asref::check(cx, expr, "as_mut", recv),
3505 ("as_ref", []) => useless_asref::check(cx, expr, "as_ref", recv),
3506 ("assume_init", []) => uninit_assumed_init::check(cx, expr, recv),
3507 ("cloned", []) => cloned_instead_of_copied::check(cx, expr, recv, span, self.msrv),
3508 ("collect", []) if is_trait_method(cx, expr, sym::Iterator) => {
3509 needless_collect::check(cx, span, expr, recv, call_span);
3510 match method_call(recv) {
3511 Some((name @ ("cloned" | "copied"), recv2, [], _, _)) => {
3512 iter_cloned_collect::check(cx, name, expr, recv2);
3514 Some(("map", m_recv, [m_arg], _, _)) => {
3515 map_collect_result_unit::check(cx, expr, m_recv, m_arg);
3517 Some(("take", take_self_arg, [take_arg], _, _)) => {
3518 if meets_msrv(self.msrv, msrvs::STR_REPEAT) {
3519 manual_str_repeat::check(cx, expr, recv, take_self_arg, take_arg);
3525 ("count", []) if is_trait_method(cx, expr, sym::Iterator) => match method_call(recv) {
3526 Some(("cloned", recv2, [], _, _)) => iter_overeager_cloned::check(cx, expr, recv, recv2, true, false),
3527 Some((name2 @ ("into_iter" | "iter" | "iter_mut"), recv2, [], _, _)) => {
3528 iter_count::check(cx, expr, recv2, name2);
3530 Some(("map", _, [arg], _, _)) => suspicious_map::check(cx, expr, recv, arg),
3531 Some(("filter", recv2, [arg], _, _)) => bytecount::check(cx, expr, recv2, arg),
3532 Some(("bytes", recv2, [], _, _)) => bytes_count_to_len::check(cx, expr, recv, recv2),
3535 ("drain", [arg]) => {
3536 iter_with_drain::check(cx, expr, recv, span, arg);
3538 ("ends_with", [arg]) => {
3539 if let ExprKind::MethodCall(.., span) = expr.kind {
3540 case_sensitive_file_extension_comparisons::check(cx, expr, span, recv, arg);
3543 ("expect", [_]) => match method_call(recv) {
3544 Some(("ok", recv, [], _, _)) => ok_expect::check(cx, expr, recv),
3545 Some(("err", recv, [], err_span, _)) => err_expect::check(cx, expr, recv, self.msrv, span, err_span),
3546 _ => expect_used::check(cx, expr, recv, false, self.allow_expect_in_tests),
3548 ("expect_err", [_]) => expect_used::check(cx, expr, recv, true, self.allow_expect_in_tests),
3549 ("extend", [arg]) => {
3550 string_extend_chars::check(cx, expr, recv, arg);
3551 extend_with_drain::check(cx, expr, recv, arg);
3553 ("filter_map", [arg]) => {
3554 unnecessary_filter_map::check(cx, expr, arg, name);
3555 filter_map_identity::check(cx, expr, arg, span);
3557 ("find_map", [arg]) => {
3558 unnecessary_filter_map::check(cx, expr, arg, name);
3560 ("flat_map", [arg]) => {
3561 flat_map_identity::check(cx, expr, arg, span);
3562 flat_map_option::check(cx, expr, arg, span);
3564 ("flatten", []) => match method_call(recv) {
3565 Some(("map", recv, [map_arg], map_span, _)) => map_flatten::check(cx, expr, recv, map_arg, map_span),
3566 Some(("cloned", recv2, [], _, _)) => iter_overeager_cloned::check(cx, expr, recv, recv2, false, true),
3569 ("fold", [init, acc]) => unnecessary_fold::check(cx, expr, init, acc, span),
3570 ("for_each", [_]) => {
3571 if let Some(("inspect", _, [_], span2, _)) = method_call(recv) {
3572 inspect_for_each::check(cx, expr, span2);
3576 get_first::check(cx, expr, recv, arg);
3577 get_last_with_len::check(cx, expr, recv, arg);
3579 ("get_or_insert_with", [arg]) => unnecessary_lazy_eval::check(cx, expr, recv, arg, "get_or_insert"),
3580 ("hash", [arg]) => {
3581 unit_hash::check(cx, expr, recv, arg);
3583 ("is_file", []) => filetype_is_file::check(cx, expr, recv),
3584 ("is_digit", [radix]) => is_digit_ascii_radix::check(cx, expr, recv, radix, self.msrv),
3585 ("is_none", []) => check_is_some_is_none(cx, expr, recv, false),
3586 ("is_some", []) => check_is_some_is_none(cx, expr, recv, true),
3587 ("iter" | "iter_mut" | "into_iter", []) => {
3588 iter_on_single_or_empty_collections::check(cx, expr, name, recv);
3590 ("join", [join_arg]) => {
3591 if let Some(("collect", _, _, span, _)) = method_call(recv) {
3592 unnecessary_join::check(cx, expr, recv, join_arg, span);
3595 ("last", []) | ("skip", [_]) => {
3596 if let Some((name2, recv2, args2, _span2, _)) = method_call(recv) {
3597 if let ("cloned", []) = (name2, args2) {
3598 iter_overeager_cloned::check(cx, expr, recv, recv2, false, false);
3603 mut_mutex_lock::check(cx, expr, recv, span);
3605 (name @ ("map" | "map_err"), [m_arg]) => {
3607 map_clone::check(cx, expr, recv, m_arg, self.msrv);
3608 if let Some((map_name @ ("iter" | "into_iter"), recv2, _, _, _)) = method_call(recv) {
3609 iter_kv_map::check(cx, map_name, expr, recv2, m_arg);
3612 map_err_ignore::check(cx, expr, m_arg);
3614 if let Some((name, recv2, args, span2,_)) = method_call(recv) {
3615 match (name, args) {
3616 ("as_mut", []) => option_as_ref_deref::check(cx, expr, recv2, m_arg, true, self.msrv),
3617 ("as_ref", []) => option_as_ref_deref::check(cx, expr, recv2, m_arg, false, self.msrv),
3618 ("filter", [f_arg]) => {
3619 filter_map::check(cx, expr, recv2, f_arg, span2, recv, m_arg, span, false);
3621 ("find", [f_arg]) => {
3622 filter_map::check(cx, expr, recv2, f_arg, span2, recv, m_arg, span, true);
3627 map_identity::check(cx, expr, recv, m_arg, name, span);
3629 ("map_or", [def, map]) => {
3630 option_map_or_none::check(cx, expr, recv, def, map);
3631 manual_ok_or::check(cx, expr, recv, def, map);
3634 if let Some((name2, recv2, args2, _, _)) = method_call(recv) {
3635 match (name2, args2) {
3636 ("cloned", []) => iter_overeager_cloned::check(cx, expr, recv, recv2, false, false),
3637 ("filter", [arg]) => filter_next::check(cx, expr, recv2, arg),
3638 ("filter_map", [arg]) => filter_map_next::check(cx, expr, recv2, arg, self.msrv),
3639 ("iter", []) => iter_next_slice::check(cx, expr, recv2),
3640 ("skip", [arg]) => iter_skip_next::check(cx, expr, recv2, arg),
3641 ("skip_while", [_]) => skip_while_next::check(cx, expr),
3646 ("nth", [n_arg]) => match method_call(recv) {
3647 Some(("bytes", recv2, [], _, _)) => bytes_nth::check(cx, expr, recv2, n_arg),
3648 Some(("cloned", recv2, [], _, _)) => iter_overeager_cloned::check(cx, expr, recv, recv2, false, false),
3649 Some(("iter", recv2, [], _, _)) => iter_nth::check(cx, expr, recv2, recv, n_arg, false),
3650 Some(("iter_mut", recv2, [], _, _)) => iter_nth::check(cx, expr, recv2, recv, n_arg, true),
3651 _ => iter_nth_zero::check(cx, expr, recv, n_arg),
3653 ("ok_or_else", [arg]) => unnecessary_lazy_eval::check(cx, expr, recv, arg, "ok_or"),
3655 open_options::check(cx, expr, recv);
3657 ("or_else", [arg]) => {
3658 if !bind_instead_of_map::ResultOrElseErrInfo::check(cx, expr, recv, arg) {
3659 unnecessary_lazy_eval::check(cx, expr, recv, arg, "or");
3662 ("push", [arg]) => {
3663 path_buf_push_overwrite::check(cx, expr, arg);
3665 ("read_to_end", [_]) => {
3666 verbose_file_reads::check(cx, expr, recv, verbose_file_reads::READ_TO_END_MSG);
3668 ("read_to_string", [_]) => {
3669 verbose_file_reads::check(cx, expr, recv, verbose_file_reads::READ_TO_STRING_MSG);
3671 ("repeat", [arg]) => {
3672 repeat_once::check(cx, expr, recv, arg);
3674 (name @ ("replace" | "replacen"), [arg1, arg2] | [arg1, arg2, _]) => {
3675 no_effect_replace::check(cx, expr, arg1, arg2);
3677 // Check for repeated `str::replace` calls to perform `collapsible_str_replace` lint
3678 if name == "replace" && let Some(("replace", ..)) = method_call(recv) {
3679 collapsible_str_replace::check(cx, expr, arg1, arg2);
3682 ("resize", [count_arg, default_arg]) => {
3683 vec_resize_to_zero::check(cx, expr, count_arg, default_arg, span);
3685 ("seek", [arg]) => {
3686 if meets_msrv(self.msrv, msrvs::SEEK_FROM_CURRENT) {
3687 seek_from_current::check(cx, expr, recv, arg);
3689 if meets_msrv(self.msrv, msrvs::SEEK_REWIND) {
3690 seek_to_start_instead_of_rewind::check(cx, expr, recv, arg, span);
3694 stable_sort_primitive::check(cx, expr, recv);
3696 ("sort_by", [arg]) => {
3697 unnecessary_sort_by::check(cx, expr, recv, arg, false);
3699 ("sort_unstable_by", [arg]) => {
3700 unnecessary_sort_by::check(cx, expr, recv, arg, true);
3702 ("splitn" | "rsplitn", [count_arg, pat_arg]) => {
3703 if let Some((Constant::Int(count), _)) = constant(cx, cx.typeck_results(), count_arg) {
3704 suspicious_splitn::check(cx, name, expr, recv, count);
3705 str_splitn::check(cx, name, expr, recv, pat_arg, count, self.msrv);
3708 ("splitn_mut" | "rsplitn_mut", [count_arg, _]) => {
3709 if let Some((Constant::Int(count), _)) = constant(cx, cx.typeck_results(), count_arg) {
3710 suspicious_splitn::check(cx, name, expr, recv, count);
3713 ("step_by", [arg]) => iterator_step_by_zero::check(cx, expr, arg),
3714 ("take", [_arg]) => {
3715 if let Some((name2, recv2, args2, _span2, _)) = method_call(recv) {
3716 if let ("cloned", []) = (name2, args2) {
3717 iter_overeager_cloned::check(cx, expr, recv, recv2, false, false);
3721 ("take", []) => needless_option_take::check(cx, expr, recv),
3722 ("then", [arg]) => {
3723 if !meets_msrv(self.msrv, msrvs::BOOL_THEN_SOME) {
3726 unnecessary_lazy_eval::check(cx, expr, recv, arg, "then_some");
3728 ("to_owned", []) => {
3729 if !suspicious_to_owned::check(cx, expr, recv) {
3730 implicit_clone::check(cx, name, expr, recv);
3733 ("to_os_string" | "to_path_buf" | "to_vec", []) => {
3734 implicit_clone::check(cx, name, expr, recv);
3737 match method_call(recv) {
3738 Some(("get", recv, [get_arg], _, _)) => {
3739 get_unwrap::check(cx, expr, recv, get_arg, false);
3741 Some(("get_mut", recv, [get_arg], _, _)) => {
3742 get_unwrap::check(cx, expr, recv, get_arg, true);
3744 Some(("or", recv, [or_arg], or_span, _)) => {
3745 or_then_unwrap::check(cx, expr, recv, or_arg, or_span);
3749 unwrap_used::check(cx, expr, recv, false, self.allow_unwrap_in_tests);
3751 ("unwrap_err", []) => unwrap_used::check(cx, expr, recv, true, self.allow_unwrap_in_tests),
3752 ("unwrap_or", [u_arg]) => match method_call(recv) {
3753 Some((arith @ ("checked_add" | "checked_sub" | "checked_mul"), lhs, [rhs], _, _)) => {
3754 manual_saturating_arithmetic::check(cx, expr, lhs, rhs, u_arg, &arith["checked_".len()..]);
3756 Some(("map", m_recv, [m_arg], span, _)) => {
3757 option_map_unwrap_or::check(cx, expr, m_recv, m_arg, recv, u_arg, span);
3759 Some(("then_some", t_recv, [t_arg], _, _)) => {
3760 obfuscated_if_else::check(cx, expr, t_recv, t_arg, u_arg);
3764 ("unwrap_or_else", [u_arg]) => match method_call(recv) {
3765 Some(("map", recv, [map_arg], _, _))
3766 if map_unwrap_or::check(cx, expr, recv, map_arg, u_arg, self.msrv) => {},
3768 unwrap_or_else_default::check(cx, expr, recv, u_arg);
3769 unnecessary_lazy_eval::check(cx, expr, recv, u_arg, "unwrap_or");
3773 if let ExprKind::MethodCall(name, iter_recv, [], _) = recv.kind
3774 && name.ident.name == sym::iter
3776 range_zip_with_len::check(cx, expr, iter_recv, arg);
3785 fn check_is_some_is_none(cx: &LateContext<'_>, expr: &Expr<'_>, recv: &Expr<'_>, is_some: bool) {
3786 if let Some((name @ ("find" | "position" | "rposition"), f_recv, [arg], span, _)) = method_call(recv) {
3787 search_is_some::check(cx, expr, name, is_some, f_recv, arg, recv, span);
3791 /// Used for `lint_binary_expr_with_method_call`.
3792 #[derive(Copy, Clone)]
3793 struct BinaryExprInfo<'a> {
3794 expr: &'a hir::Expr<'a>,
3795 chain: &'a hir::Expr<'a>,
3796 other: &'a hir::Expr<'a>,
3800 /// Checks for the `CHARS_NEXT_CMP` and `CHARS_LAST_CMP` lints.
3801 fn lint_binary_expr_with_method_call(cx: &LateContext<'_>, info: &mut BinaryExprInfo<'_>) {
3802 macro_rules! lint_with_both_lhs_and_rhs {
3803 ($func:expr, $cx:expr, $info:ident) => {
3804 if !$func($cx, $info) {
3805 ::std::mem::swap(&mut $info.chain, &mut $info.other);
3806 if $func($cx, $info) {
3813 lint_with_both_lhs_and_rhs!(chars_next_cmp::check, cx, info);
3814 lint_with_both_lhs_and_rhs!(chars_last_cmp::check, cx, info);
3815 lint_with_both_lhs_and_rhs!(chars_next_cmp_with_unwrap::check, cx, info);
3816 lint_with_both_lhs_and_rhs!(chars_last_cmp_with_unwrap::check, cx, info);
3819 const FN_HEADER: hir::FnHeader = hir::FnHeader {
3820 unsafety: hir::Unsafety::Normal,
3821 constness: hir::Constness::NotConst,
3822 asyncness: hir::IsAsync::NotAsync,
3823 abi: rustc_target::spec::abi::Abi::Rust,
3826 struct ShouldImplTraitCase {
3827 trait_name: &'static str,
3828 method_name: &'static str,
3830 fn_header: hir::FnHeader,
3831 // implicit self kind expected (none, self, &self, ...)
3832 self_kind: SelfKind,
3833 // checks against the output type
3834 output_type: OutType,
3835 // certain methods with explicit lifetimes can't implement the equivalent trait method
3836 lint_explicit_lifetime: bool,
3838 impl ShouldImplTraitCase {
3840 trait_name: &'static str,
3841 method_name: &'static str,
3843 fn_header: hir::FnHeader,
3844 self_kind: SelfKind,
3845 output_type: OutType,
3846 lint_explicit_lifetime: bool,
3847 ) -> ShouldImplTraitCase {
3848 ShouldImplTraitCase {
3855 lint_explicit_lifetime,
3859 fn lifetime_param_cond(&self, impl_item: &hir::ImplItem<'_>) -> bool {
3860 self.lint_explicit_lifetime
3861 || !impl_item.generics.params.iter().any(|p| {
3864 hir::GenericParamKind::Lifetime {
3865 kind: hir::LifetimeParamKind::Explicit
3873 const TRAIT_METHODS: [ShouldImplTraitCase; 30] = [
3874 ShouldImplTraitCase::new("std::ops::Add", "add", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3875 ShouldImplTraitCase::new("std::convert::AsMut", "as_mut", 1, FN_HEADER, SelfKind::RefMut, OutType::Ref, true),
3876 ShouldImplTraitCase::new("std::convert::AsRef", "as_ref", 1, FN_HEADER, SelfKind::Ref, OutType::Ref, true),
3877 ShouldImplTraitCase::new("std::ops::BitAnd", "bitand", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3878 ShouldImplTraitCase::new("std::ops::BitOr", "bitor", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3879 ShouldImplTraitCase::new("std::ops::BitXor", "bitxor", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3880 ShouldImplTraitCase::new("std::borrow::Borrow", "borrow", 1, FN_HEADER, SelfKind::Ref, OutType::Ref, true),
3881 ShouldImplTraitCase::new("std::borrow::BorrowMut", "borrow_mut", 1, FN_HEADER, SelfKind::RefMut, OutType::Ref, true),
3882 ShouldImplTraitCase::new("std::clone::Clone", "clone", 1, FN_HEADER, SelfKind::Ref, OutType::Any, true),
3883 ShouldImplTraitCase::new("std::cmp::Ord", "cmp", 2, FN_HEADER, SelfKind::Ref, OutType::Any, true),
3884 ShouldImplTraitCase::new("std::default::Default", "default", 0, FN_HEADER, SelfKind::No, OutType::Any, true),
3885 ShouldImplTraitCase::new("std::ops::Deref", "deref", 1, FN_HEADER, SelfKind::Ref, OutType::Ref, true),
3886 ShouldImplTraitCase::new("std::ops::DerefMut", "deref_mut", 1, FN_HEADER, SelfKind::RefMut, OutType::Ref, true),
3887 ShouldImplTraitCase::new("std::ops::Div", "div", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3888 ShouldImplTraitCase::new("std::ops::Drop", "drop", 1, FN_HEADER, SelfKind::RefMut, OutType::Unit, true),
3889 ShouldImplTraitCase::new("std::cmp::PartialEq", "eq", 2, FN_HEADER, SelfKind::Ref, OutType::Bool, true),
3890 ShouldImplTraitCase::new("std::iter::FromIterator", "from_iter", 1, FN_HEADER, SelfKind::No, OutType::Any, true),
3891 ShouldImplTraitCase::new("std::str::FromStr", "from_str", 1, FN_HEADER, SelfKind::No, OutType::Any, true),
3892 ShouldImplTraitCase::new("std::hash::Hash", "hash", 2, FN_HEADER, SelfKind::Ref, OutType::Unit, true),
3893 ShouldImplTraitCase::new("std::ops::Index", "index", 2, FN_HEADER, SelfKind::Ref, OutType::Ref, true),
3894 ShouldImplTraitCase::new("std::ops::IndexMut", "index_mut", 2, FN_HEADER, SelfKind::RefMut, OutType::Ref, true),
3895 ShouldImplTraitCase::new("std::iter::IntoIterator", "into_iter", 1, FN_HEADER, SelfKind::Value, OutType::Any, true),
3896 ShouldImplTraitCase::new("std::ops::Mul", "mul", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3897 ShouldImplTraitCase::new("std::ops::Neg", "neg", 1, FN_HEADER, SelfKind::Value, OutType::Any, true),
3898 ShouldImplTraitCase::new("std::iter::Iterator", "next", 1, FN_HEADER, SelfKind::RefMut, OutType::Any, false),
3899 ShouldImplTraitCase::new("std::ops::Not", "not", 1, FN_HEADER, SelfKind::Value, OutType::Any, true),
3900 ShouldImplTraitCase::new("std::ops::Rem", "rem", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3901 ShouldImplTraitCase::new("std::ops::Shl", "shl", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3902 ShouldImplTraitCase::new("std::ops::Shr", "shr", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3903 ShouldImplTraitCase::new("std::ops::Sub", "sub", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3906 #[derive(Clone, Copy, PartialEq, Eq, Debug)]
3911 No, // When we want the first argument type to be different than `Self`
3915 fn matches<'a>(self, cx: &LateContext<'a>, parent_ty: Ty<'a>, ty: Ty<'a>) -> bool {
3916 fn matches_value<'a>(cx: &LateContext<'a>, parent_ty: Ty<'a>, ty: Ty<'a>) -> bool {
3917 if ty == parent_ty {
3919 } else if ty.is_box() {
3920 ty.boxed_ty() == parent_ty
3921 } else if is_type_diagnostic_item(cx, ty, sym::Rc) || is_type_diagnostic_item(cx, ty, sym::Arc) {
3922 if let ty::Adt(_, substs) = ty.kind() {
3923 substs.types().next().map_or(false, |t| t == parent_ty)
3932 fn matches_ref<'a>(cx: &LateContext<'a>, mutability: hir::Mutability, parent_ty: Ty<'a>, ty: Ty<'a>) -> bool {
3933 if let ty::Ref(_, t, m) = *ty.kind() {
3934 return m == mutability && t == parent_ty;
3937 let trait_sym = match mutability {
3938 hir::Mutability::Not => sym::AsRef,
3939 hir::Mutability::Mut => sym::AsMut,
3942 let Some(trait_def_id) = cx.tcx.get_diagnostic_item(trait_sym) else {
3945 implements_trait(cx, ty, trait_def_id, &[parent_ty.into()])
3948 fn matches_none<'a>(cx: &LateContext<'a>, parent_ty: Ty<'a>, ty: Ty<'a>) -> bool {
3949 !matches_value(cx, parent_ty, ty)
3950 && !matches_ref(cx, hir::Mutability::Not, parent_ty, ty)
3951 && !matches_ref(cx, hir::Mutability::Mut, parent_ty, ty)
3955 Self::Value => matches_value(cx, parent_ty, ty),
3956 Self::Ref => matches_ref(cx, hir::Mutability::Not, parent_ty, ty) || ty == parent_ty && is_copy(cx, ty),
3957 Self::RefMut => matches_ref(cx, hir::Mutability::Mut, parent_ty, ty),
3958 Self::No => matches_none(cx, parent_ty, ty),
3963 fn description(self) -> &'static str {
3965 Self::Value => "`self` by value",
3966 Self::Ref => "`self` by reference",
3967 Self::RefMut => "`self` by mutable reference",
3968 Self::No => "no `self`",
3973 #[derive(Clone, Copy)]
3982 fn matches(self, ty: &hir::FnRetTy<'_>) -> bool {
3983 let is_unit = |ty: &hir::Ty<'_>| matches!(ty.kind, hir::TyKind::Tup(&[]));
3985 (Self::Unit, &hir::FnRetTy::DefaultReturn(_)) => true,
3986 (Self::Unit, &hir::FnRetTy::Return(ty)) if is_unit(ty) => true,
3987 (Self::Bool, &hir::FnRetTy::Return(ty)) if is_bool(ty) => true,
3988 (Self::Any, &hir::FnRetTy::Return(ty)) if !is_unit(ty) => true,
3989 (Self::Ref, &hir::FnRetTy::Return(ty)) => matches!(ty.kind, hir::TyKind::Rptr(_, _)),
3995 fn is_bool(ty: &hir::Ty<'_>) -> bool {
3996 if let hir::TyKind::Path(QPath::Resolved(_, path)) = ty.kind {
3997 matches!(path.res, Res::PrimTy(PrimTy::Bool))
4003 fn fn_header_equals(expected: hir::FnHeader, actual: hir::FnHeader) -> bool {
4004 expected.constness == actual.constness
4005 && expected.unsafety == actual.unsafety
4006 && expected.asyncness == actual.asyncness