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;
57 mod needless_option_as_deref;
58 mod needless_option_take;
59 mod no_effect_replace;
60 mod obfuscated_if_else;
63 mod option_as_ref_deref;
64 mod option_map_or_none;
65 mod option_map_unwrap_or;
68 mod path_buf_push_overwrite;
69 mod range_zip_with_len;
72 mod single_char_add_str;
73 mod single_char_insert_string;
74 mod single_char_pattern;
75 mod single_char_push_string;
77 mod stable_sort_primitive;
79 mod string_extend_chars;
81 mod suspicious_splitn;
82 mod suspicious_to_owned;
83 mod uninit_assumed_init;
85 mod unnecessary_filter_map;
87 mod unnecessary_iter_cloned;
89 mod unnecessary_lazy_eval;
90 mod unnecessary_sort_by;
91 mod unnecessary_to_owned;
92 mod unwrap_or_else_default;
96 mod vec_resize_to_zero;
97 mod verbose_file_reads;
98 mod wrong_self_convention;
101 use bind_instead_of_map::BindInsteadOfMap;
102 use clippy_utils::consts::{constant, Constant};
103 use clippy_utils::diagnostics::{span_lint, span_lint_and_help};
104 use clippy_utils::ty::{contains_adt_constructor, implements_trait, is_copy, is_type_diagnostic_item};
105 use clippy_utils::{contains_return, is_trait_method, iter_input_pats, meets_msrv, msrvs, return_ty};
106 use if_chain::if_chain;
107 use rustc_hir as hir;
108 use rustc_hir::def::Res;
109 use rustc_hir::{Expr, ExprKind, PrimTy, QPath, TraitItem, TraitItemKind};
110 use rustc_hir_analysis::hir_ty_to_ty;
111 use rustc_lint::{LateContext, LateLintPass, LintContext};
112 use rustc_middle::lint::in_external_macro;
113 use rustc_middle::ty::{self, TraitRef, Ty};
114 use rustc_semver::RustcVersion;
115 use rustc_session::{declare_tool_lint, impl_lint_pass};
116 use rustc_span::{sym, Span};
118 declare_clippy_lint! {
120 /// Checks for usages of `cloned()` on an `Iterator` or `Option` where
121 /// `copied()` could be used instead.
123 /// ### Why is this bad?
124 /// `copied()` is better because it guarantees that the type being cloned
125 /// implements `Copy`.
129 /// [1, 2, 3].iter().cloned();
133 /// [1, 2, 3].iter().copied();
135 #[clippy::version = "1.53.0"]
136 pub CLONED_INSTEAD_OF_COPIED,
138 "used `cloned` where `copied` could be used instead"
141 declare_clippy_lint! {
143 /// Checks for consecutive calls to `str::replace` (2 or more)
144 /// that can be collapsed into a single call.
146 /// ### Why is this bad?
147 /// Consecutive `str::replace` calls scan the string multiple times
148 /// with repetitive code.
152 /// let hello = "hesuo worpd"
153 /// .replace('s', "l")
154 /// .replace("u", "l")
155 /// .replace('p', "l");
159 /// let hello = "hesuo worpd".replace(&['s', 'u', 'p'], "l");
161 #[clippy::version = "1.64.0"]
162 pub COLLAPSIBLE_STR_REPLACE,
164 "collapse consecutive calls to str::replace (2 or more) into a single call"
167 declare_clippy_lint! {
169 /// Checks for usage of `_.cloned().<func>()` where call to `.cloned()` can be postponed.
171 /// ### Why is this bad?
172 /// It's often inefficient to clone all elements of an iterator, when eventually, only some
173 /// of them will be consumed.
175 /// ### Known Problems
176 /// This `lint` removes the side of effect of cloning items in the iterator.
177 /// A code that relies on that side-effect could fail.
181 /// # let vec = vec!["string".to_string()];
182 /// vec.iter().cloned().take(10);
183 /// vec.iter().cloned().last();
188 /// # let vec = vec!["string".to_string()];
189 /// vec.iter().take(10).cloned();
190 /// vec.iter().last().cloned();
192 #[clippy::version = "1.60.0"]
193 pub ITER_OVEREAGER_CLONED,
195 "using `cloned()` early with `Iterator::iter()` can lead to some performance inefficiencies"
198 declare_clippy_lint! {
200 /// Checks for usages of `Iterator::flat_map()` where `filter_map()` could be
203 /// ### Why is this bad?
204 /// When applicable, `filter_map()` is more clear since it shows that
205 /// `Option` is used to produce 0 or 1 items.
209 /// let nums: Vec<i32> = ["1", "2", "whee!"].iter().flat_map(|x| x.parse().ok()).collect();
213 /// let nums: Vec<i32> = ["1", "2", "whee!"].iter().filter_map(|x| x.parse().ok()).collect();
215 #[clippy::version = "1.53.0"]
218 "used `flat_map` where `filter_map` could be used instead"
221 declare_clippy_lint! {
223 /// Checks for `.unwrap()` or `.unwrap_err()` calls on `Result`s and `.unwrap()` call on `Option`s.
225 /// ### Why is this bad?
226 /// It is better to handle the `None` or `Err` case,
227 /// or at least call `.expect(_)` with a more helpful message. Still, for a lot of
228 /// quick-and-dirty code, `unwrap` is a good choice, which is why this lint is
229 /// `Allow` by default.
231 /// `result.unwrap()` will let the thread panic on `Err` values.
232 /// Normally, you want to implement more sophisticated error handling,
233 /// and propagate errors upwards with `?` operator.
235 /// Even if you want to panic on errors, not all `Error`s implement good
236 /// messages on display. Therefore, it may be beneficial to look at the places
237 /// where they may get displayed. Activate this lint to do just that.
241 /// # let option = Some(1);
242 /// # let result: Result<usize, ()> = Ok(1);
249 /// # let option = Some(1);
250 /// # let result: Result<usize, ()> = Ok(1);
251 /// option.expect("more helpful message");
252 /// result.expect("more helpful message");
255 /// If [expect_used](#expect_used) is enabled, instead:
257 /// # let option = Some(1);
258 /// # let result: Result<usize, ()> = Ok(1);
265 #[clippy::version = "1.45.0"]
268 "using `.unwrap()` on `Result` or `Option`, which should at least get a better message using `expect()`"
271 declare_clippy_lint! {
273 /// Checks for `.expect()` or `.expect_err()` calls on `Result`s and `.expect()` call on `Option`s.
275 /// ### Why is this bad?
276 /// Usually it is better to handle the `None` or `Err` case.
277 /// Still, for a lot of quick-and-dirty code, `expect` is a good choice, which is why
278 /// this lint is `Allow` by default.
280 /// `result.expect()` will let the thread panic on `Err`
281 /// values. Normally, you want to implement more sophisticated error handling,
282 /// and propagate errors upwards with `?` operator.
286 /// # let option = Some(1);
287 /// # let result: Result<usize, ()> = Ok(1);
288 /// option.expect("one");
289 /// result.expect("one");
294 /// # let option = Some(1);
295 /// # let result: Result<usize, ()> = Ok(1);
302 #[clippy::version = "1.45.0"]
305 "using `.expect()` on `Result` or `Option`, which might be better handled"
308 declare_clippy_lint! {
310 /// Checks for methods that should live in a trait
311 /// implementation of a `std` trait (see [llogiq's blog
312 /// post](http://llogiq.github.io/2015/07/30/traits.html) for further
313 /// information) instead of an inherent implementation.
315 /// ### Why is this bad?
316 /// Implementing the traits improve ergonomics for users of
317 /// the code, often with very little cost. Also people seeing a `mul(...)`
319 /// may expect `*` to work equally, so you should have good reason to disappoint
326 /// fn add(&self, other: &X) -> X {
332 #[clippy::version = "pre 1.29.0"]
333 pub SHOULD_IMPLEMENT_TRAIT,
335 "defining a method that should be implementing a std trait"
338 declare_clippy_lint! {
340 /// Checks for methods with certain name prefixes and which
341 /// doesn't match how self is taken. The actual rules are:
343 /// |Prefix |Postfix |`self` taken | `self` type |
344 /// |-------|------------|-------------------------------|--------------|
345 /// |`as_` | none |`&self` or `&mut self` | any |
346 /// |`from_`| none | none | any |
347 /// |`into_`| none |`self` | any |
348 /// |`is_` | none |`&mut self` or `&self` or none | any |
349 /// |`to_` | `_mut` |`&mut self` | any |
350 /// |`to_` | not `_mut` |`self` | `Copy` |
351 /// |`to_` | not `_mut` |`&self` | not `Copy` |
353 /// Note: Clippy doesn't trigger methods with `to_` prefix in:
354 /// - Traits definition.
355 /// Clippy can not tell if a type that implements a trait is `Copy` or not.
356 /// - Traits implementation, when `&self` is taken.
357 /// The method signature is controlled by the trait and often `&self` is required for all types that implement the trait
358 /// (see e.g. the `std::string::ToString` trait).
360 /// Clippy allows `Pin<&Self>` and `Pin<&mut Self>` if `&self` and `&mut self` is required.
362 /// Please find more info here:
363 /// https://rust-lang.github.io/api-guidelines/naming.html#ad-hoc-conversions-follow-as_-to_-into_-conventions-c-conv
365 /// ### Why is this bad?
366 /// Consistency breeds readability. If you follow the
367 /// conventions, your users won't be surprised that they, e.g., need to supply a
368 /// mutable reference to a `as_..` function.
374 /// fn as_str(self) -> &'static str {
380 #[clippy::version = "pre 1.29.0"]
381 pub WRONG_SELF_CONVENTION,
383 "defining a method named with an established prefix (like \"into_\") that takes `self` with the wrong convention"
386 declare_clippy_lint! {
388 /// Checks for usage of `ok().expect(..)`.
390 /// ### Why is this bad?
391 /// Because you usually call `expect()` on the `Result`
392 /// directly to get a better error message.
394 /// ### Known problems
395 /// The error type needs to implement `Debug`
399 /// # let x = Ok::<_, ()>(());
400 /// x.ok().expect("why did I do this again?");
405 /// # let x = Ok::<_, ()>(());
406 /// x.expect("why did I do this again?");
408 #[clippy::version = "pre 1.29.0"]
411 "using `ok().expect()`, which gives worse error messages than calling `expect` directly on the Result"
414 declare_clippy_lint! {
416 /// Checks for `.err().expect()` calls on the `Result` type.
418 /// ### Why is this bad?
419 /// `.expect_err()` can be called directly to avoid the extra type conversion from `err()`.
423 /// let x: Result<u32, &str> = Ok(10);
424 /// x.err().expect("Testing err().expect()");
428 /// let x: Result<u32, &str> = Ok(10);
429 /// x.expect_err("Testing expect_err");
431 #[clippy::version = "1.62.0"]
434 r#"using `.err().expect("")` when `.expect_err("")` can be used"#
437 declare_clippy_lint! {
439 /// Checks for usages of `_.unwrap_or_else(Default::default)` on `Option` and
442 /// ### Why is this bad?
443 /// Readability, these can be written as `_.unwrap_or_default`, which is
444 /// simpler and more concise.
448 /// # let x = Some(1);
449 /// x.unwrap_or_else(Default::default);
450 /// x.unwrap_or_else(u32::default);
455 /// # let x = Some(1);
456 /// x.unwrap_or_default();
458 #[clippy::version = "1.56.0"]
459 pub UNWRAP_OR_ELSE_DEFAULT,
461 "using `.unwrap_or_else(Default::default)`, which is more succinctly expressed as `.unwrap_or_default()`"
464 declare_clippy_lint! {
466 /// Checks for usage of `option.map(_).unwrap_or(_)` or `option.map(_).unwrap_or_else(_)` or
467 /// `result.map(_).unwrap_or_else(_)`.
469 /// ### Why is this bad?
470 /// Readability, these can be written more concisely (resp.) as
471 /// `option.map_or(_, _)`, `option.map_or_else(_, _)` and `result.map_or_else(_, _)`.
473 /// ### Known problems
474 /// The order of the arguments is not in execution order
478 /// # let option = Some(1);
479 /// # let result: Result<usize, ()> = Ok(1);
480 /// # fn some_function(foo: ()) -> usize { 1 }
481 /// option.map(|a| a + 1).unwrap_or(0);
482 /// result.map(|a| a + 1).unwrap_or_else(some_function);
487 /// # let option = Some(1);
488 /// # let result: Result<usize, ()> = Ok(1);
489 /// # fn some_function(foo: ()) -> usize { 1 }
490 /// option.map_or(0, |a| a + 1);
491 /// result.map_or_else(some_function, |a| a + 1);
493 #[clippy::version = "1.45.0"]
496 "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)`"
499 declare_clippy_lint! {
501 /// Checks for usage of `_.map_or(None, _)`.
503 /// ### Why is this bad?
504 /// Readability, this can be written more concisely as
507 /// ### Known problems
508 /// The order of the arguments is not in execution order.
512 /// # let opt = Some(1);
513 /// opt.map_or(None, |a| Some(a + 1));
518 /// # let opt = Some(1);
519 /// opt.and_then(|a| Some(a + 1));
521 #[clippy::version = "pre 1.29.0"]
522 pub OPTION_MAP_OR_NONE,
524 "using `Option.map_or(None, f)`, which is more succinctly expressed as `and_then(f)`"
527 declare_clippy_lint! {
529 /// Checks for usage of `_.map_or(None, Some)`.
531 /// ### Why is this bad?
532 /// Readability, this can be written more concisely as
537 /// # let r: Result<u32, &str> = Ok(1);
538 /// assert_eq!(Some(1), r.map_or(None, Some));
543 /// # let r: Result<u32, &str> = Ok(1);
544 /// assert_eq!(Some(1), r.ok());
546 #[clippy::version = "1.44.0"]
547 pub RESULT_MAP_OR_INTO_OPTION,
549 "using `Result.map_or(None, Some)`, which is more succinctly expressed as `ok()`"
552 declare_clippy_lint! {
554 /// Checks for usage of `_.and_then(|x| Some(y))`, `_.and_then(|x| Ok(y))` or
555 /// `_.or_else(|x| Err(y))`.
557 /// ### Why is this bad?
558 /// Readability, this can be written more concisely as
559 /// `_.map(|x| y)` or `_.map_err(|x| y)`.
563 /// # fn opt() -> Option<&'static str> { Some("42") }
564 /// # fn res() -> Result<&'static str, &'static str> { Ok("42") }
565 /// let _ = opt().and_then(|s| Some(s.len()));
566 /// let _ = res().and_then(|s| if s.len() == 42 { Ok(10) } else { Ok(20) });
567 /// let _ = res().or_else(|s| if s.len() == 42 { Err(10) } else { Err(20) });
570 /// The correct use would be:
573 /// # fn opt() -> Option<&'static str> { Some("42") }
574 /// # fn res() -> Result<&'static str, &'static str> { Ok("42") }
575 /// let _ = opt().map(|s| s.len());
576 /// let _ = res().map(|s| if s.len() == 42 { 10 } else { 20 });
577 /// let _ = res().map_err(|s| if s.len() == 42 { 10 } else { 20 });
579 #[clippy::version = "1.45.0"]
580 pub BIND_INSTEAD_OF_MAP,
582 "using `Option.and_then(|x| Some(y))`, which is more succinctly expressed as `map(|x| y)`"
585 declare_clippy_lint! {
587 /// Checks for usage of `_.filter(_).next()`.
589 /// ### Why is this bad?
590 /// Readability, this can be written more concisely as
595 /// # let vec = vec![1];
596 /// vec.iter().filter(|x| **x == 0).next();
601 /// # let vec = vec![1];
602 /// vec.iter().find(|x| **x == 0);
604 #[clippy::version = "pre 1.29.0"]
607 "using `filter(p).next()`, which is more succinctly expressed as `.find(p)`"
610 declare_clippy_lint! {
612 /// Checks for usage of `_.skip_while(condition).next()`.
614 /// ### Why is this bad?
615 /// Readability, this can be written more concisely as
616 /// `_.find(!condition)`.
620 /// # let vec = vec![1];
621 /// vec.iter().skip_while(|x| **x == 0).next();
626 /// # let vec = vec![1];
627 /// vec.iter().find(|x| **x != 0);
629 #[clippy::version = "1.42.0"]
632 "using `skip_while(p).next()`, which is more succinctly expressed as `.find(!p)`"
635 declare_clippy_lint! {
637 /// Checks for usage of `_.map(_).flatten(_)` on `Iterator` and `Option`
639 /// ### Why is this bad?
640 /// Readability, this can be written more concisely as
641 /// `_.flat_map(_)` for `Iterator` or `_.and_then(_)` for `Option`
645 /// let vec = vec![vec![1]];
646 /// let opt = Some(5);
648 /// vec.iter().map(|x| x.iter()).flatten();
649 /// opt.map(|x| Some(x * 2)).flatten();
654 /// # let vec = vec![vec![1]];
655 /// # let opt = Some(5);
656 /// vec.iter().flat_map(|x| x.iter());
657 /// opt.and_then(|x| Some(x * 2));
659 #[clippy::version = "1.31.0"]
662 "using combinations of `flatten` and `map` which can usually be written as a single method call"
665 declare_clippy_lint! {
667 /// Checks for usage of `_.filter(_).map(_)` that can be written more simply
668 /// as `filter_map(_)`.
670 /// ### Why is this bad?
671 /// Redundant code in the `filter` and `map` operations is poor style and
676 /// # #![allow(unused)]
678 /// .filter(|n| n.checked_add(1).is_some())
679 /// .map(|n| n.checked_add(1).unwrap());
684 /// # #[allow(unused)]
685 /// (0_i32..10).filter_map(|n| n.checked_add(1));
687 #[clippy::version = "1.51.0"]
688 pub MANUAL_FILTER_MAP,
690 "using `_.filter(_).map(_)` in a way that can be written more simply as `filter_map(_)`"
693 declare_clippy_lint! {
695 /// Checks for usage of `_.find(_).map(_)` that can be written more simply
696 /// as `find_map(_)`.
698 /// ### Why is this bad?
699 /// Redundant code in the `find` and `map` operations is poor style and
705 /// .find(|n| n.checked_add(1).is_some())
706 /// .map(|n| n.checked_add(1).unwrap());
711 /// (0_i32..10).find_map(|n| n.checked_add(1));
713 #[clippy::version = "1.51.0"]
716 "using `_.find(_).map(_)` in a way that can be written more simply as `find_map(_)`"
719 declare_clippy_lint! {
721 /// Checks for usage of `_.filter_map(_).next()`.
723 /// ### Why is this bad?
724 /// Readability, this can be written more concisely as
729 /// (0..3).filter_map(|x| if x == 2 { Some(x) } else { None }).next();
731 /// Can be written as
734 /// (0..3).find_map(|x| if x == 2 { Some(x) } else { None });
736 #[clippy::version = "1.36.0"]
739 "using combination of `filter_map` and `next` which can usually be written as a single method call"
742 declare_clippy_lint! {
744 /// Checks for usage of `flat_map(|x| x)`.
746 /// ### Why is this bad?
747 /// Readability, this can be written more concisely by using `flatten`.
751 /// # let iter = vec![vec![0]].into_iter();
752 /// iter.flat_map(|x| x);
754 /// Can be written as
756 /// # let iter = vec![vec![0]].into_iter();
759 #[clippy::version = "1.39.0"]
760 pub FLAT_MAP_IDENTITY,
762 "call to `flat_map` where `flatten` is sufficient"
765 declare_clippy_lint! {
767 /// Checks for an iterator or string search (such as `find()`,
768 /// `position()`, or `rposition()`) followed by a call to `is_some()` or `is_none()`.
770 /// ### Why is this bad?
771 /// Readability, this can be written more concisely as:
772 /// * `_.any(_)`, or `_.contains(_)` for `is_some()`,
773 /// * `!_.any(_)`, or `!_.contains(_)` for `is_none()`.
777 /// # #![allow(unused)]
778 /// let vec = vec![1];
779 /// vec.iter().find(|x| **x == 0).is_some();
781 /// "hello world".find("world").is_none();
786 /// let vec = vec![1];
787 /// vec.iter().any(|x| *x == 0);
789 /// # #[allow(unused)]
790 /// !"hello world".contains("world");
792 #[clippy::version = "pre 1.29.0"]
795 "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()`)"
798 declare_clippy_lint! {
800 /// Checks for usage of `.chars().next()` on a `str` to check
801 /// if it starts with a given char.
803 /// ### Why is this bad?
804 /// Readability, this can be written more concisely as
805 /// `_.starts_with(_)`.
809 /// let name = "foo";
810 /// if name.chars().next() == Some('_') {};
815 /// let name = "foo";
816 /// if name.starts_with('_') {};
818 #[clippy::version = "pre 1.29.0"]
821 "using `.chars().next()` to check if a string starts with a char"
824 declare_clippy_lint! {
826 /// Checks for calls to `.or(foo(..))`, `.unwrap_or(foo(..))`,
827 /// `.or_insert(foo(..))` etc., and suggests to use `.or_else(|| foo(..))`,
828 /// `.unwrap_or_else(|| foo(..))`, `.unwrap_or_default()` or `.or_default()`
831 /// ### Why is this bad?
832 /// The function will always be called and potentially
833 /// allocate an object acting as the default.
835 /// ### Known problems
836 /// If the function has side-effects, not calling it will
837 /// change the semantic of the program, but you shouldn't rely on that anyway.
841 /// # let foo = Some(String::new());
842 /// foo.unwrap_or(String::new());
847 /// # let foo = Some(String::new());
848 /// foo.unwrap_or_else(String::new);
852 /// # let foo = Some(String::new());
853 /// foo.unwrap_or_default();
855 #[clippy::version = "pre 1.29.0"]
858 "using any `*or` method with a function call, which suggests `*or_else`"
861 declare_clippy_lint! {
863 /// Checks for `.or(…).unwrap()` calls to Options and Results.
865 /// ### Why is this bad?
866 /// You should use `.unwrap_or(…)` instead for clarity.
870 /// # let fallback = "fallback";
872 /// # type Error = &'static str;
873 /// # let result: Result<&str, Error> = Err("error");
874 /// let value = result.or::<Error>(Ok(fallback)).unwrap();
877 /// # let option: Option<&str> = None;
878 /// let value = option.or(Some(fallback)).unwrap();
882 /// # let fallback = "fallback";
884 /// # let result: Result<&str, &str> = Err("error");
885 /// let value = result.unwrap_or(fallback);
888 /// # let option: Option<&str> = None;
889 /// let value = option.unwrap_or(fallback);
891 #[clippy::version = "1.61.0"]
894 "checks for `.or(…).unwrap()` calls to Options and Results."
897 declare_clippy_lint! {
899 /// Checks for calls to `.expect(&format!(...))`, `.expect(foo(..))`,
900 /// etc., and suggests to use `unwrap_or_else` instead
902 /// ### Why is this bad?
903 /// The function will always be called.
905 /// ### Known problems
906 /// If the function has side-effects, not calling it will
907 /// change the semantics of the program, but you shouldn't rely on that anyway.
911 /// # let foo = Some(String::new());
912 /// # let err_code = "418";
913 /// # let err_msg = "I'm a teapot";
914 /// foo.expect(&format!("Err {}: {}", err_code, err_msg));
918 /// # let foo = Some(String::new());
919 /// foo.expect(format!("Err {}: {}", err_code, err_msg).as_str());
924 /// # let foo = Some(String::new());
925 /// # let err_code = "418";
926 /// # let err_msg = "I'm a teapot";
927 /// foo.unwrap_or_else(|| panic!("Err {}: {}", err_code, err_msg));
929 #[clippy::version = "pre 1.29.0"]
932 "using any `expect` method with a function call"
935 declare_clippy_lint! {
937 /// Checks for usage of `.clone()` on a `Copy` type.
939 /// ### Why is this bad?
940 /// The only reason `Copy` types implement `Clone` is for
941 /// generics, not for using the `clone` method on a concrete type.
947 #[clippy::version = "pre 1.29.0"]
950 "using `clone` on a `Copy` type"
953 declare_clippy_lint! {
955 /// Checks for usage of `.clone()` on a ref-counted pointer,
956 /// (`Rc`, `Arc`, `rc::Weak`, or `sync::Weak`), and suggests calling Clone via unified
957 /// function syntax instead (e.g., `Rc::clone(foo)`).
959 /// ### Why is this bad?
960 /// Calling '.clone()' on an Rc, Arc, or Weak
961 /// can obscure the fact that only the pointer is being cloned, not the underlying
966 /// # use std::rc::Rc;
967 /// let x = Rc::new(1);
974 /// # use std::rc::Rc;
975 /// # let x = Rc::new(1);
978 #[clippy::version = "pre 1.29.0"]
979 pub CLONE_ON_REF_PTR,
981 "using 'clone' on a ref-counted pointer"
984 declare_clippy_lint! {
986 /// Checks for usage of `.clone()` on an `&&T`.
988 /// ### Why is this bad?
989 /// Cloning an `&&T` copies the inner `&T`, instead of
990 /// cloning the underlying `T`.
997 /// let z = y.clone();
998 /// println!("{:p} {:p}", *y, z); // prints out the same pointer
1001 #[clippy::version = "pre 1.29.0"]
1002 pub CLONE_DOUBLE_REF,
1004 "using `clone` on `&&T`"
1007 declare_clippy_lint! {
1008 /// ### What it does
1009 /// Checks for usage of `.to_string()` on an `&&T` where
1010 /// `T` implements `ToString` directly (like `&&str` or `&&String`).
1012 /// ### Why is this bad?
1013 /// This bypasses the specialized implementation of
1014 /// `ToString` and instead goes through the more expensive string formatting
1019 /// // Generic implementation for `T: Display` is used (slow)
1020 /// ["foo", "bar"].iter().map(|s| s.to_string());
1022 /// // OK, the specialized impl is used
1023 /// ["foo", "bar"].iter().map(|&s| s.to_string());
1025 #[clippy::version = "1.40.0"]
1026 pub INEFFICIENT_TO_STRING,
1028 "using `to_string` on `&&T` where `T: ToString`"
1031 declare_clippy_lint! {
1032 /// ### What it does
1033 /// Checks for `new` not returning a type that contains `Self`.
1035 /// ### Why is this bad?
1036 /// As a convention, `new` methods are used to make a new
1037 /// instance of a type.
1040 /// In an impl block:
1043 /// # struct NotAFoo;
1045 /// fn new() -> NotAFoo {
1053 /// struct Bar(Foo);
1055 /// // Bad. The type name must contain `Self`
1056 /// fn new() -> Bar {
1064 /// # struct FooError;
1066 /// // Good. Return type contains `Self`
1067 /// fn new() -> Result<Foo, FooError> {
1073 /// Or in a trait definition:
1075 /// pub trait Trait {
1076 /// // Bad. The type name must contain `Self`
1082 /// pub trait Trait {
1083 /// // Good. Return type contains `Self`
1084 /// fn new() -> Self;
1087 #[clippy::version = "pre 1.29.0"]
1088 pub NEW_RET_NO_SELF,
1090 "not returning type containing `Self` in a `new` method"
1093 declare_clippy_lint! {
1094 /// ### What it does
1095 /// Checks for string methods that receive a single-character
1096 /// `str` as an argument, e.g., `_.split("x")`.
1098 /// ### Why is this bad?
1099 /// Performing these methods using a `char` is faster than
1102 /// ### Known problems
1103 /// Does not catch multi-byte unicode characters.
1114 #[clippy::version = "pre 1.29.0"]
1115 pub SINGLE_CHAR_PATTERN,
1117 "using a single-character str where a char could be used, e.g., `_.split(\"x\")`"
1120 declare_clippy_lint! {
1121 /// ### What it does
1122 /// Checks for calling `.step_by(0)` on iterators which panics.
1124 /// ### Why is this bad?
1125 /// This very much looks like an oversight. Use `panic!()` instead if you
1126 /// actually intend to panic.
1129 /// ```rust,should_panic
1130 /// for x in (0..100).step_by(0) {
1134 #[clippy::version = "pre 1.29.0"]
1135 pub ITERATOR_STEP_BY_ZERO,
1137 "using `Iterator::step_by(0)`, which will panic at runtime"
1140 declare_clippy_lint! {
1141 /// ### What it does
1142 /// Checks for indirect collection of populated `Option`
1144 /// ### Why is this bad?
1145 /// `Option` is like a collection of 0-1 things, so `flatten`
1146 /// automatically does this without suspicious-looking `unwrap` calls.
1150 /// let _ = std::iter::empty::<Option<i32>>().filter(Option::is_some).map(Option::unwrap);
1154 /// let _ = std::iter::empty::<Option<i32>>().flatten();
1156 #[clippy::version = "1.53.0"]
1157 pub OPTION_FILTER_MAP,
1159 "filtering `Option` for `Some` then force-unwrapping, which can be one type-safe operation"
1162 declare_clippy_lint! {
1163 /// ### What it does
1164 /// Checks for the use of `iter.nth(0)`.
1166 /// ### Why is this bad?
1167 /// `iter.next()` is equivalent to
1168 /// `iter.nth(0)`, as they both consume the next element,
1169 /// but is more readable.
1173 /// # use std::collections::HashSet;
1174 /// # let mut s = HashSet::new();
1176 /// let x = s.iter().nth(0);
1181 /// # use std::collections::HashSet;
1182 /// # let mut s = HashSet::new();
1184 /// let x = s.iter().next();
1186 #[clippy::version = "1.42.0"]
1189 "replace `iter.nth(0)` with `iter.next()`"
1192 declare_clippy_lint! {
1193 /// ### What it does
1194 /// Checks for use of `.iter().nth()` (and the related
1195 /// `.iter_mut().nth()`) on standard library types with *O*(1) element access.
1197 /// ### Why is this bad?
1198 /// `.get()` and `.get_mut()` are more efficient and more
1203 /// let some_vec = vec![0, 1, 2, 3];
1204 /// let bad_vec = some_vec.iter().nth(3);
1205 /// let bad_slice = &some_vec[..].iter().nth(3);
1207 /// The correct use would be:
1209 /// let some_vec = vec![0, 1, 2, 3];
1210 /// let bad_vec = some_vec.get(3);
1211 /// let bad_slice = &some_vec[..].get(3);
1213 #[clippy::version = "pre 1.29.0"]
1216 "using `.iter().nth()` on a standard library type with O(1) element access"
1219 declare_clippy_lint! {
1220 /// ### What it does
1221 /// Checks for use of `.skip(x).next()` on iterators.
1223 /// ### Why is this bad?
1224 /// `.nth(x)` is cleaner
1228 /// let some_vec = vec![0, 1, 2, 3];
1229 /// let bad_vec = some_vec.iter().skip(3).next();
1230 /// let bad_slice = &some_vec[..].iter().skip(3).next();
1232 /// The correct use would be:
1234 /// let some_vec = vec![0, 1, 2, 3];
1235 /// let bad_vec = some_vec.iter().nth(3);
1236 /// let bad_slice = &some_vec[..].iter().nth(3);
1238 #[clippy::version = "pre 1.29.0"]
1241 "using `.skip(x).next()` on an iterator"
1244 declare_clippy_lint! {
1245 /// ### What it does
1246 /// Checks for use of `.drain(..)` on `Vec` and `VecDeque` for iteration.
1248 /// ### Why is this bad?
1249 /// `.into_iter()` is simpler with better performance.
1253 /// # use std::collections::HashSet;
1254 /// let mut foo = vec![0, 1, 2, 3];
1255 /// let bar: HashSet<usize> = foo.drain(..).collect();
1259 /// # use std::collections::HashSet;
1260 /// let foo = vec![0, 1, 2, 3];
1261 /// let bar: HashSet<usize> = foo.into_iter().collect();
1263 #[clippy::version = "1.61.0"]
1264 pub ITER_WITH_DRAIN,
1266 "replace `.drain(..)` with `.into_iter()`"
1269 declare_clippy_lint! {
1270 /// ### What it does
1271 /// Checks for using `x.get(x.len() - 1)` instead of
1274 /// ### Why is this bad?
1275 /// Using `x.last()` is easier to read and has the same
1278 /// Note that using `x[x.len() - 1]` is semantically different from
1279 /// `x.last()`. Indexing into the array will panic on out-of-bounds
1280 /// accesses, while `x.get()` and `x.last()` will return `None`.
1282 /// There is another lint (get_unwrap) that covers the case of using
1283 /// `x.get(index).unwrap()` instead of `x[index]`.
1287 /// let x = vec![2, 3, 5];
1288 /// let last_element = x.get(x.len() - 1);
1293 /// let x = vec![2, 3, 5];
1294 /// let last_element = x.last();
1296 #[clippy::version = "1.37.0"]
1297 pub GET_LAST_WITH_LEN,
1299 "Using `x.get(x.len() - 1)` when `x.last()` is correct and simpler"
1302 declare_clippy_lint! {
1303 /// ### What it does
1304 /// Checks for use of `.get().unwrap()` (or
1305 /// `.get_mut().unwrap`) on a standard library type which implements `Index`
1307 /// ### Why is this bad?
1308 /// Using the Index trait (`[]`) is more clear and more
1311 /// ### Known problems
1312 /// Not a replacement for error handling: Using either
1313 /// `.unwrap()` or the Index trait (`[]`) carries the risk of causing a `panic`
1314 /// if the value being accessed is `None`. If the use of `.get().unwrap()` is a
1315 /// temporary placeholder for dealing with the `Option` type, then this does
1316 /// not mitigate the need for error handling. If there is a chance that `.get()`
1317 /// will be `None` in your program, then it is advisable that the `None` case
1318 /// is handled in a future refactor instead of using `.unwrap()` or the Index
1323 /// let mut some_vec = vec![0, 1, 2, 3];
1324 /// let last = some_vec.get(3).unwrap();
1325 /// *some_vec.get_mut(0).unwrap() = 1;
1327 /// The correct use would be:
1329 /// let mut some_vec = vec![0, 1, 2, 3];
1330 /// let last = some_vec[3];
1331 /// some_vec[0] = 1;
1333 #[clippy::version = "pre 1.29.0"]
1336 "using `.get().unwrap()` or `.get_mut().unwrap()` when using `[]` would work instead"
1339 declare_clippy_lint! {
1340 /// ### What it does
1341 /// Checks for occurrences where one vector gets extended instead of append
1343 /// ### Why is this bad?
1344 /// Using `append` instead of `extend` is more concise and faster
1348 /// let mut a = vec![1, 2, 3];
1349 /// let mut b = vec![4, 5, 6];
1351 /// a.extend(b.drain(..));
1356 /// let mut a = vec![1, 2, 3];
1357 /// let mut b = vec![4, 5, 6];
1359 /// a.append(&mut b);
1361 #[clippy::version = "1.55.0"]
1362 pub EXTEND_WITH_DRAIN,
1364 "using vec.append(&mut vec) to move the full range of a vector to another"
1367 declare_clippy_lint! {
1368 /// ### What it does
1369 /// Checks for the use of `.extend(s.chars())` where s is a
1370 /// `&str` or `String`.
1372 /// ### Why is this bad?
1373 /// `.push_str(s)` is clearer
1377 /// let abc = "abc";
1378 /// let def = String::from("def");
1379 /// let mut s = String::new();
1380 /// s.extend(abc.chars());
1381 /// s.extend(def.chars());
1383 /// The correct use would be:
1385 /// let abc = "abc";
1386 /// let def = String::from("def");
1387 /// let mut s = String::new();
1388 /// s.push_str(abc);
1389 /// s.push_str(&def);
1391 #[clippy::version = "pre 1.29.0"]
1392 pub STRING_EXTEND_CHARS,
1394 "using `x.extend(s.chars())` where s is a `&str` or `String`"
1397 declare_clippy_lint! {
1398 /// ### What it does
1399 /// Checks for the use of `.cloned().collect()` on slice to
1402 /// ### Why is this bad?
1403 /// `.to_vec()` is clearer
1407 /// let s = [1, 2, 3, 4, 5];
1408 /// let s2: Vec<isize> = s[..].iter().cloned().collect();
1410 /// The better use would be:
1412 /// let s = [1, 2, 3, 4, 5];
1413 /// let s2: Vec<isize> = s.to_vec();
1415 #[clippy::version = "pre 1.29.0"]
1416 pub ITER_CLONED_COLLECT,
1418 "using `.cloned().collect()` on slice to create a `Vec`"
1421 declare_clippy_lint! {
1422 /// ### What it does
1423 /// Checks for usage of `_.chars().last()` or
1424 /// `_.chars().next_back()` on a `str` to check if it ends with a given char.
1426 /// ### Why is this bad?
1427 /// Readability, this can be written more concisely as
1428 /// `_.ends_with(_)`.
1432 /// # let name = "_";
1433 /// name.chars().last() == Some('_') || name.chars().next_back() == Some('-');
1438 /// # let name = "_";
1439 /// name.ends_with('_') || name.ends_with('-');
1441 #[clippy::version = "pre 1.29.0"]
1444 "using `.chars().last()` or `.chars().next_back()` to check if a string ends with a char"
1447 declare_clippy_lint! {
1448 /// ### What it does
1449 /// Checks for usage of `.as_ref()` or `.as_mut()` where the
1450 /// types before and after the call are the same.
1452 /// ### Why is this bad?
1453 /// The call is unnecessary.
1457 /// # fn do_stuff(x: &[i32]) {}
1458 /// let x: &[i32] = &[1, 2, 3, 4, 5];
1459 /// do_stuff(x.as_ref());
1461 /// The correct use would be:
1463 /// # fn do_stuff(x: &[i32]) {}
1464 /// let x: &[i32] = &[1, 2, 3, 4, 5];
1467 #[clippy::version = "pre 1.29.0"]
1470 "using `as_ref` where the types before and after the call are the same"
1473 declare_clippy_lint! {
1474 /// ### What it does
1475 /// Checks for using `fold` when a more succinct alternative exists.
1476 /// Specifically, this checks for `fold`s which could be replaced by `any`, `all`,
1477 /// `sum` or `product`.
1479 /// ### Why is this bad?
1484 /// # #[allow(unused)]
1485 /// (0..3).fold(false, |acc, x| acc || x > 2);
1490 /// (0..3).any(|x| x > 2);
1492 #[clippy::version = "pre 1.29.0"]
1493 pub UNNECESSARY_FOLD,
1495 "using `fold` when a more succinct alternative exists"
1498 declare_clippy_lint! {
1499 /// ### What it does
1500 /// Checks for `filter_map` calls that could be replaced by `filter` or `map`.
1501 /// More specifically it checks if the closure provided is only performing one of the
1502 /// filter or map operations and suggests the appropriate option.
1504 /// ### Why is this bad?
1505 /// Complexity. The intent is also clearer if only a single
1506 /// operation is being performed.
1510 /// let _ = (0..3).filter_map(|x| if x > 2 { Some(x) } else { None });
1512 /// // As there is no transformation of the argument this could be written as:
1513 /// let _ = (0..3).filter(|&x| x > 2);
1517 /// let _ = (0..4).filter_map(|x| Some(x + 1));
1519 /// // As there is no conditional check on the argument this could be written as:
1520 /// let _ = (0..4).map(|x| x + 1);
1522 #[clippy::version = "1.31.0"]
1523 pub UNNECESSARY_FILTER_MAP,
1525 "using `filter_map` when a more succinct alternative exists"
1528 declare_clippy_lint! {
1529 /// ### What it does
1530 /// Checks for `find_map` calls that could be replaced by `find` or `map`. More
1531 /// specifically it checks if the closure provided is only performing one of the
1532 /// find or map operations and suggests the appropriate option.
1534 /// ### Why is this bad?
1535 /// Complexity. The intent is also clearer if only a single
1536 /// operation is being performed.
1540 /// let _ = (0..3).find_map(|x| if x > 2 { Some(x) } else { None });
1542 /// // As there is no transformation of the argument this could be written as:
1543 /// let _ = (0..3).find(|&x| x > 2);
1547 /// let _ = (0..4).find_map(|x| Some(x + 1));
1549 /// // As there is no conditional check on the argument this could be written as:
1550 /// let _ = (0..4).map(|x| x + 1).next();
1552 #[clippy::version = "1.61.0"]
1553 pub UNNECESSARY_FIND_MAP,
1555 "using `find_map` when a more succinct alternative exists"
1558 declare_clippy_lint! {
1559 /// ### What it does
1560 /// Checks for `into_iter` calls on references which should be replaced by `iter`
1563 /// ### Why is this bad?
1564 /// Readability. Calling `into_iter` on a reference will not move out its
1565 /// content into the resulting iterator, which is confusing. It is better just call `iter` or
1566 /// `iter_mut` directly.
1570 /// # let vec = vec![3, 4, 5];
1571 /// (&vec).into_iter();
1576 /// # let vec = vec![3, 4, 5];
1579 #[clippy::version = "1.32.0"]
1580 pub INTO_ITER_ON_REF,
1582 "using `.into_iter()` on a reference"
1585 declare_clippy_lint! {
1586 /// ### What it does
1587 /// Checks for calls to `map` followed by a `count`.
1589 /// ### Why is this bad?
1590 /// It looks suspicious. Maybe `map` was confused with `filter`.
1591 /// If the `map` call is intentional, this should be rewritten
1592 /// using `inspect`. Or, if you intend to drive the iterator to
1593 /// completion, you can just use `for_each` instead.
1597 /// let _ = (0..3).map(|x| x + 2).count();
1599 #[clippy::version = "1.39.0"]
1602 "suspicious usage of map"
1605 declare_clippy_lint! {
1606 /// ### What it does
1607 /// Checks for `MaybeUninit::uninit().assume_init()`.
1609 /// ### Why is this bad?
1610 /// For most types, this is undefined behavior.
1612 /// ### Known problems
1613 /// For now, we accept empty tuples and tuples / arrays
1614 /// of `MaybeUninit`. There may be other types that allow uninitialized
1615 /// data, but those are not yet rigorously defined.
1619 /// // Beware the UB
1620 /// use std::mem::MaybeUninit;
1622 /// let _: usize = unsafe { MaybeUninit::uninit().assume_init() };
1625 /// Note that the following is OK:
1628 /// use std::mem::MaybeUninit;
1630 /// let _: [MaybeUninit<bool>; 5] = unsafe {
1631 /// MaybeUninit::uninit().assume_init()
1634 #[clippy::version = "1.39.0"]
1635 pub UNINIT_ASSUMED_INIT,
1637 "`MaybeUninit::uninit().assume_init()`"
1640 declare_clippy_lint! {
1641 /// ### What it does
1642 /// Checks for `.checked_add/sub(x).unwrap_or(MAX/MIN)`.
1644 /// ### Why is this bad?
1645 /// These can be written simply with `saturating_add/sub` methods.
1649 /// # let y: u32 = 0;
1650 /// # let x: u32 = 100;
1651 /// let add = x.checked_add(y).unwrap_or(u32::MAX);
1652 /// let sub = x.checked_sub(y).unwrap_or(u32::MIN);
1655 /// can be written using dedicated methods for saturating addition/subtraction as:
1658 /// # let y: u32 = 0;
1659 /// # let x: u32 = 100;
1660 /// let add = x.saturating_add(y);
1661 /// let sub = x.saturating_sub(y);
1663 #[clippy::version = "1.39.0"]
1664 pub MANUAL_SATURATING_ARITHMETIC,
1666 "`.checked_add/sub(x).unwrap_or(MAX/MIN)`"
1669 declare_clippy_lint! {
1670 /// ### What it does
1671 /// Checks for `offset(_)`, `wrapping_`{`add`, `sub`}, etc. on raw pointers to
1672 /// zero-sized types
1674 /// ### Why is this bad?
1675 /// This is a no-op, and likely unintended
1679 /// unsafe { (&() as *const ()).offset(1) };
1681 #[clippy::version = "1.41.0"]
1684 "Check for offset calculations on raw pointers to zero-sized types"
1687 declare_clippy_lint! {
1688 /// ### What it does
1689 /// Checks for `FileType::is_file()`.
1691 /// ### Why is this bad?
1692 /// When people testing a file type with `FileType::is_file`
1693 /// they are testing whether a path is something they can get bytes from. But
1694 /// `is_file` doesn't cover special file types in unix-like systems, and doesn't cover
1695 /// symlink in windows. Using `!FileType::is_dir()` is a better way to that intention.
1700 /// let metadata = std::fs::metadata("foo.txt")?;
1701 /// let filetype = metadata.file_type();
1703 /// if filetype.is_file() {
1706 /// # Ok::<_, std::io::Error>(())
1710 /// should be written as:
1714 /// let metadata = std::fs::metadata("foo.txt")?;
1715 /// let filetype = metadata.file_type();
1717 /// if !filetype.is_dir() {
1720 /// # Ok::<_, std::io::Error>(())
1723 #[clippy::version = "1.42.0"]
1724 pub FILETYPE_IS_FILE,
1726 "`FileType::is_file` is not recommended to test for readable file type"
1729 declare_clippy_lint! {
1730 /// ### What it does
1731 /// Checks for usage of `_.as_ref().map(Deref::deref)` or it's aliases (such as String::as_str).
1733 /// ### Why is this bad?
1734 /// Readability, this can be written more concisely as
1739 /// # let opt = Some("".to_string());
1740 /// opt.as_ref().map(String::as_str)
1743 /// Can be written as
1745 /// # let opt = Some("".to_string());
1749 #[clippy::version = "1.42.0"]
1750 pub OPTION_AS_REF_DEREF,
1752 "using `as_ref().map(Deref::deref)`, which is more succinctly expressed as `as_deref()`"
1755 declare_clippy_lint! {
1756 /// ### What it does
1757 /// Checks for usage of `iter().next()` on a Slice or an Array
1759 /// ### Why is this bad?
1760 /// These can be shortened into `.get()`
1764 /// # let a = [1, 2, 3];
1765 /// # let b = vec![1, 2, 3];
1766 /// a[2..].iter().next();
1767 /// b.iter().next();
1769 /// should be written as:
1771 /// # let a = [1, 2, 3];
1772 /// # let b = vec![1, 2, 3];
1776 #[clippy::version = "1.46.0"]
1777 pub ITER_NEXT_SLICE,
1779 "using `.iter().next()` on a sliced array, which can be shortened to just `.get()`"
1782 declare_clippy_lint! {
1783 /// ### What it does
1784 /// Warns when using `push_str`/`insert_str` with a single-character string literal
1785 /// where `push`/`insert` with a `char` would work fine.
1787 /// ### Why is this bad?
1788 /// It's less clear that we are pushing a single character.
1792 /// # let mut string = String::new();
1793 /// string.insert_str(0, "R");
1794 /// string.push_str("R");
1799 /// # let mut string = String::new();
1800 /// string.insert(0, 'R');
1801 /// string.push('R');
1803 #[clippy::version = "1.49.0"]
1804 pub SINGLE_CHAR_ADD_STR,
1806 "`push_str()` or `insert_str()` used with a single-character string literal as parameter"
1809 declare_clippy_lint! {
1810 /// ### What it does
1811 /// As the counterpart to `or_fun_call`, this lint looks for unnecessary
1812 /// lazily evaluated closures on `Option` and `Result`.
1814 /// This lint suggests changing the following functions, when eager evaluation results in
1816 /// - `unwrap_or_else` to `unwrap_or`
1817 /// - `and_then` to `and`
1818 /// - `or_else` to `or`
1819 /// - `get_or_insert_with` to `get_or_insert`
1820 /// - `ok_or_else` to `ok_or`
1822 /// ### Why is this bad?
1823 /// Using eager evaluation is shorter and simpler in some cases.
1825 /// ### Known problems
1826 /// It is possible, but not recommended for `Deref` and `Index` to have
1827 /// side effects. Eagerly evaluating them can change the semantics of the program.
1831 /// // example code where clippy issues a warning
1832 /// let opt: Option<u32> = None;
1834 /// opt.unwrap_or_else(|| 42);
1838 /// let opt: Option<u32> = None;
1840 /// opt.unwrap_or(42);
1842 #[clippy::version = "1.48.0"]
1843 pub UNNECESSARY_LAZY_EVALUATIONS,
1845 "using unnecessary lazy evaluation, which can be replaced with simpler eager evaluation"
1848 declare_clippy_lint! {
1849 /// ### What it does
1850 /// Checks for usage of `_.map(_).collect::<Result<(), _>()`.
1852 /// ### Why is this bad?
1853 /// Using `try_for_each` instead is more readable and idiomatic.
1857 /// (0..3).map(|t| Err(t)).collect::<Result<(), _>>();
1861 /// (0..3).try_for_each(|t| Err(t));
1863 #[clippy::version = "1.49.0"]
1864 pub MAP_COLLECT_RESULT_UNIT,
1866 "using `.map(_).collect::<Result<(),_>()`, which can be replaced with `try_for_each`"
1869 declare_clippy_lint! {
1870 /// ### What it does
1871 /// Checks for `from_iter()` function calls on types that implement the `FromIterator`
1874 /// ### Why is this bad?
1875 /// It is recommended style to use collect. See
1876 /// [FromIterator documentation](https://doc.rust-lang.org/std/iter/trait.FromIterator.html)
1880 /// let five_fives = std::iter::repeat(5).take(5);
1882 /// let v = Vec::from_iter(five_fives);
1884 /// assert_eq!(v, vec![5, 5, 5, 5, 5]);
1888 /// let five_fives = std::iter::repeat(5).take(5);
1890 /// let v: Vec<i32> = five_fives.collect();
1892 /// assert_eq!(v, vec![5, 5, 5, 5, 5]);
1894 #[clippy::version = "1.49.0"]
1895 pub FROM_ITER_INSTEAD_OF_COLLECT,
1897 "use `.collect()` instead of `::from_iter()`"
1900 declare_clippy_lint! {
1901 /// ### What it does
1902 /// Checks for usage of `inspect().for_each()`.
1904 /// ### Why is this bad?
1905 /// It is the same as performing the computation
1906 /// inside `inspect` at the beginning of the closure in `for_each`.
1910 /// [1,2,3,4,5].iter()
1911 /// .inspect(|&x| println!("inspect the number: {}", x))
1912 /// .for_each(|&x| {
1913 /// assert!(x >= 0);
1916 /// Can be written as
1918 /// [1,2,3,4,5].iter()
1919 /// .for_each(|&x| {
1920 /// println!("inspect the number: {}", x);
1921 /// assert!(x >= 0);
1924 #[clippy::version = "1.51.0"]
1925 pub INSPECT_FOR_EACH,
1927 "using `.inspect().for_each()`, which can be replaced with `.for_each()`"
1930 declare_clippy_lint! {
1931 /// ### What it does
1932 /// Checks for usage of `filter_map(|x| x)`.
1934 /// ### Why is this bad?
1935 /// Readability, this can be written more concisely by using `flatten`.
1939 /// # let iter = vec![Some(1)].into_iter();
1940 /// iter.filter_map(|x| x);
1944 /// # let iter = vec![Some(1)].into_iter();
1947 #[clippy::version = "1.52.0"]
1948 pub FILTER_MAP_IDENTITY,
1950 "call to `filter_map` where `flatten` is sufficient"
1953 declare_clippy_lint! {
1954 /// ### What it does
1955 /// Checks for instances of `map(f)` where `f` is the identity function.
1957 /// ### Why is this bad?
1958 /// It can be written more concisely without the call to `map`.
1962 /// let x = [1, 2, 3];
1963 /// let y: Vec<_> = x.iter().map(|x| x).map(|x| 2*x).collect();
1967 /// let x = [1, 2, 3];
1968 /// let y: Vec<_> = x.iter().map(|x| 2*x).collect();
1970 #[clippy::version = "1.47.0"]
1973 "using iterator.map(|x| x)"
1976 declare_clippy_lint! {
1977 /// ### What it does
1978 /// Checks for the use of `.bytes().nth()`.
1980 /// ### Why is this bad?
1981 /// `.as_bytes().get()` is more efficient and more
1986 /// # #[allow(unused)]
1987 /// "Hello".bytes().nth(3);
1992 /// # #[allow(unused)]
1993 /// "Hello".as_bytes().get(3);
1995 #[clippy::version = "1.52.0"]
1998 "replace `.bytes().nth()` with `.as_bytes().get()`"
2001 declare_clippy_lint! {
2002 /// ### What it does
2003 /// Checks for the usage of `_.to_owned()`, `vec.to_vec()`, or similar when calling `_.clone()` would be clearer.
2005 /// ### Why is this bad?
2006 /// These methods do the same thing as `_.clone()` but may be confusing as
2007 /// to why we are calling `to_vec` on something that is already a `Vec` or calling `to_owned` on something that is already owned.
2011 /// let a = vec![1, 2, 3];
2012 /// let b = a.to_vec();
2013 /// let c = a.to_owned();
2017 /// let a = vec![1, 2, 3];
2018 /// let b = a.clone();
2019 /// let c = a.clone();
2021 #[clippy::version = "1.52.0"]
2024 "implicitly cloning a value by invoking a function on its dereferenced type"
2027 declare_clippy_lint! {
2028 /// ### What it does
2029 /// Checks for the use of `.iter().count()`.
2031 /// ### Why is this bad?
2032 /// `.len()` is more efficient and more
2037 /// # #![allow(unused)]
2038 /// let some_vec = vec![0, 1, 2, 3];
2040 /// some_vec.iter().count();
2041 /// &some_vec[..].iter().count();
2046 /// let some_vec = vec![0, 1, 2, 3];
2049 /// &some_vec[..].len();
2051 #[clippy::version = "1.52.0"]
2054 "replace `.iter().count()` with `.len()`"
2057 declare_clippy_lint! {
2058 /// ### What it does
2059 /// Checks for the usage of `_.to_owned()`, on a `Cow<'_, _>`.
2061 /// ### Why is this bad?
2062 /// Calling `to_owned()` on a `Cow` creates a clone of the `Cow`
2063 /// itself, without taking ownership of the `Cow` contents (i.e.
2064 /// it's equivalent to calling `Cow::clone`).
2065 /// The similarly named `into_owned` method, on the other hand,
2066 /// clones the `Cow` contents, effectively turning any `Cow::Borrowed`
2067 /// into a `Cow::Owned`.
2069 /// Given the potential ambiguity, consider replacing `to_owned`
2070 /// with `clone` for better readability or, if getting a `Cow::Owned`
2071 /// was the original intent, using `into_owned` instead.
2075 /// # use std::borrow::Cow;
2076 /// let s = "Hello world!";
2077 /// let cow = Cow::Borrowed(s);
2079 /// let data = cow.to_owned();
2080 /// assert!(matches!(data, Cow::Borrowed(_)))
2084 /// # use std::borrow::Cow;
2085 /// let s = "Hello world!";
2086 /// let cow = Cow::Borrowed(s);
2088 /// let data = cow.clone();
2089 /// assert!(matches!(data, Cow::Borrowed(_)))
2093 /// # use std::borrow::Cow;
2094 /// let s = "Hello world!";
2095 /// let cow = Cow::Borrowed(s);
2097 /// let data = cow.into_owned();
2098 /// assert!(matches!(data, String))
2100 #[clippy::version = "1.65.0"]
2101 pub SUSPICIOUS_TO_OWNED,
2103 "calls to `to_owned` on a `Cow<'_, _>` might not do what they are expected"
2106 declare_clippy_lint! {
2107 /// ### What it does
2108 /// Checks for calls to [`splitn`]
2109 /// (https://doc.rust-lang.org/std/primitive.str.html#method.splitn) and
2110 /// related functions with either zero or one splits.
2112 /// ### Why is this bad?
2113 /// These calls don't actually split the value and are
2114 /// likely to be intended as a different number.
2119 /// for x in s.splitn(1, ":") {
2127 /// for x in s.splitn(2, ":") {
2131 #[clippy::version = "1.54.0"]
2132 pub SUSPICIOUS_SPLITN,
2134 "checks for `.splitn(0, ..)` and `.splitn(1, ..)`"
2137 declare_clippy_lint! {
2138 /// ### What it does
2139 /// Checks for manual implementations of `str::repeat`
2141 /// ### Why is this bad?
2142 /// These are both harder to read, as well as less performant.
2146 /// let x: String = std::iter::repeat('x').take(10).collect();
2151 /// let x: String = "x".repeat(10);
2153 #[clippy::version = "1.54.0"]
2154 pub MANUAL_STR_REPEAT,
2156 "manual implementation of `str::repeat`"
2159 declare_clippy_lint! {
2160 /// ### What it does
2161 /// Checks for usages of `str::splitn(2, _)`
2163 /// ### Why is this bad?
2164 /// `split_once` is both clearer in intent and slightly more efficient.
2168 /// let s = "key=value=add";
2169 /// let (key, value) = s.splitn(2, '=').next_tuple()?;
2170 /// let value = s.splitn(2, '=').nth(1)?;
2172 /// let mut parts = s.splitn(2, '=');
2173 /// let key = parts.next()?;
2174 /// let value = parts.next()?;
2179 /// let s = "key=value=add";
2180 /// let (key, value) = s.split_once('=')?;
2181 /// let value = s.split_once('=')?.1;
2183 /// let (key, value) = s.split_once('=')?;
2187 /// The multiple statement variant currently only detects `iter.next()?`/`iter.next().unwrap()`
2188 /// in two separate `let` statements that immediately follow the `splitn()`
2189 #[clippy::version = "1.57.0"]
2190 pub MANUAL_SPLIT_ONCE,
2192 "replace `.splitn(2, pat)` with `.split_once(pat)`"
2195 declare_clippy_lint! {
2196 /// ### What it does
2197 /// Checks for usages of `str::splitn` (or `str::rsplitn`) where using `str::split` would be the same.
2198 /// ### Why is this bad?
2199 /// The function `split` is simpler and there is no performance difference in these cases, considering
2200 /// that both functions return a lazy iterator.
2203 /// let str = "key=value=add";
2204 /// let _ = str.splitn(3, '=').next().unwrap();
2209 /// let str = "key=value=add";
2210 /// let _ = str.split('=').next().unwrap();
2212 #[clippy::version = "1.59.0"]
2213 pub NEEDLESS_SPLITN,
2215 "usages of `str::splitn` that can be replaced with `str::split`"
2218 declare_clippy_lint! {
2219 /// ### What it does
2220 /// Checks for unnecessary calls to [`ToOwned::to_owned`](https://doc.rust-lang.org/std/borrow/trait.ToOwned.html#tymethod.to_owned)
2221 /// and other `to_owned`-like functions.
2223 /// ### Why is this bad?
2224 /// The unnecessary calls result in useless allocations.
2226 /// ### Known problems
2227 /// `unnecessary_to_owned` can falsely trigger if `IntoIterator::into_iter` is applied to an
2228 /// owned copy of a resource and the resource is later used mutably. See
2229 /// [#8148](https://github.com/rust-lang/rust-clippy/issues/8148).
2233 /// let path = std::path::Path::new("x");
2234 /// foo(&path.to_string_lossy().to_string());
2235 /// fn foo(s: &str) {}
2239 /// let path = std::path::Path::new("x");
2240 /// foo(&path.to_string_lossy());
2241 /// fn foo(s: &str) {}
2243 #[clippy::version = "1.59.0"]
2244 pub UNNECESSARY_TO_OWNED,
2246 "unnecessary calls to `to_owned`-like functions"
2249 declare_clippy_lint! {
2250 /// ### What it does
2251 /// Checks for use of `.collect::<Vec<String>>().join("")` on iterators.
2253 /// ### Why is this bad?
2254 /// `.collect::<String>()` is more concise and might be more performant
2258 /// let vector = vec!["hello", "world"];
2259 /// let output = vector.iter().map(|item| item.to_uppercase()).collect::<Vec<String>>().join("");
2260 /// println!("{}", output);
2262 /// The correct use would be:
2264 /// let vector = vec!["hello", "world"];
2265 /// let output = vector.iter().map(|item| item.to_uppercase()).collect::<String>();
2266 /// println!("{}", output);
2268 /// ### Known problems
2269 /// While `.collect::<String>()` is sometimes more performant, there are cases where
2270 /// using `.collect::<String>()` over `.collect::<Vec<String>>().join("")`
2271 /// will prevent loop unrolling and will result in a negative performance impact.
2273 /// Additionally, differences have been observed between aarch64 and x86_64 assembly output,
2274 /// with aarch64 tending to producing faster assembly in more cases when using `.collect::<String>()`
2275 #[clippy::version = "1.61.0"]
2276 pub UNNECESSARY_JOIN,
2278 "using `.collect::<Vec<String>>().join(\"\")` on an iterator"
2281 declare_clippy_lint! {
2282 /// ### What it does
2283 /// Checks for no-op uses of `Option::{as_deref, as_deref_mut}`,
2284 /// for example, `Option<&T>::as_deref()` returns the same type.
2286 /// ### Why is this bad?
2287 /// Redundant code and improving readability.
2291 /// let a = Some(&1);
2292 /// let b = a.as_deref(); // goes from Option<&i32> to Option<&i32>
2297 /// let a = Some(&1);
2300 #[clippy::version = "1.57.0"]
2301 pub NEEDLESS_OPTION_AS_DEREF,
2303 "no-op use of `deref` or `deref_mut` method to `Option`."
2306 declare_clippy_lint! {
2307 /// ### What it does
2308 /// Finds usages of [`char::is_digit`](https://doc.rust-lang.org/stable/std/primitive.char.html#method.is_digit) that
2309 /// can be replaced with [`is_ascii_digit`](https://doc.rust-lang.org/stable/std/primitive.char.html#method.is_ascii_digit) or
2310 /// [`is_ascii_hexdigit`](https://doc.rust-lang.org/stable/std/primitive.char.html#method.is_ascii_hexdigit).
2312 /// ### Why is this bad?
2313 /// `is_digit(..)` is slower and requires specifying the radix.
2317 /// let c: char = '6';
2323 /// let c: char = '6';
2324 /// c.is_ascii_digit();
2325 /// c.is_ascii_hexdigit();
2327 #[clippy::version = "1.62.0"]
2328 pub IS_DIGIT_ASCII_RADIX,
2330 "use of `char::is_digit(..)` with literal radix of 10 or 16"
2333 declare_clippy_lint! {
2334 /// ### What it does
2335 /// Checks for calling `take` function after `as_ref`.
2337 /// ### Why is this bad?
2338 /// Redundant code. `take` writes `None` to its argument.
2339 /// In this case the modification is useless as it's a temporary that cannot be read from afterwards.
2343 /// let x = Some(3);
2344 /// x.as_ref().take();
2348 /// let x = Some(3);
2351 #[clippy::version = "1.62.0"]
2352 pub NEEDLESS_OPTION_TAKE,
2354 "using `.as_ref().take()` on a temporary value"
2357 declare_clippy_lint! {
2358 /// ### What it does
2359 /// Checks for `replace` statements which have no effect.
2361 /// ### Why is this bad?
2362 /// It's either a mistake or confusing.
2366 /// "1234".replace("12", "12");
2367 /// "1234".replacen("12", "12", 1);
2369 #[clippy::version = "1.63.0"]
2370 pub NO_EFFECT_REPLACE,
2372 "replace with no effect"
2375 declare_clippy_lint! {
2376 /// ### What it does
2377 /// Checks for usages of `.then_some(..).unwrap_or(..)`
2379 /// ### Why is this bad?
2380 /// This can be written more clearly with `if .. else ..`
2383 /// This lint currently only looks for usages of
2384 /// `.then_some(..).unwrap_or(..)`, but will be expanded
2385 /// to account for similar patterns.
2390 /// x.then_some("a").unwrap_or("b");
2395 /// if x { "a" } else { "b" };
2397 #[clippy::version = "1.64.0"]
2398 pub OBFUSCATED_IF_ELSE,
2400 "use of `.then_some(..).unwrap_or(..)` can be written \
2401 more clearly with `if .. else ..`"
2404 declare_clippy_lint! {
2405 /// ### What it does
2407 /// Checks for calls to `iter`, `iter_mut` or `into_iter` on collections containing a single item
2409 /// ### Why is this bad?
2411 /// It is simpler to use the once function from the standard library:
2416 /// let a = [123].iter();
2417 /// let b = Some(123).into_iter();
2422 /// let a = iter::once(&123);
2423 /// let b = iter::once(123);
2426 /// ### Known problems
2428 /// The type of the resulting iterator might become incompatible with its usage
2429 #[clippy::version = "1.64.0"]
2430 pub ITER_ON_SINGLE_ITEMS,
2432 "Iterator for array of length 1"
2435 declare_clippy_lint! {
2436 /// ### What it does
2438 /// Checks for calls to `iter`, `iter_mut` or `into_iter` on empty collections
2440 /// ### Why is this bad?
2442 /// It is simpler to use the empty function from the standard library:
2447 /// use std::{slice, option};
2448 /// let a: slice::Iter<i32> = [].iter();
2449 /// let f: option::IntoIter<i32> = None.into_iter();
2454 /// let a: iter::Empty<i32> = iter::empty();
2455 /// let b: iter::Empty<i32> = iter::empty();
2458 /// ### Known problems
2460 /// The type of the resulting iterator might become incompatible with its usage
2461 #[clippy::version = "1.64.0"]
2462 pub ITER_ON_EMPTY_COLLECTIONS,
2464 "Iterator for empty array"
2467 declare_clippy_lint! {
2468 /// ### What it does
2469 /// Checks for naive byte counts
2471 /// ### Why is this bad?
2472 /// The [`bytecount`](https://crates.io/crates/bytecount)
2473 /// crate has methods to count your bytes faster, especially for large slices.
2475 /// ### Known problems
2476 /// If you have predominantly small slices, the
2477 /// `bytecount::count(..)` method may actually be slower. However, if you can
2478 /// ensure that less than 2³²-1 matches arise, the `naive_count_32(..)` can be
2479 /// faster in those cases.
2483 /// # let vec = vec![1_u8];
2484 /// let count = vec.iter().filter(|x| **x == 0u8).count();
2489 /// # let vec = vec![1_u8];
2490 /// let count = bytecount::count(&vec, 0u8);
2492 #[clippy::version = "pre 1.29.0"]
2493 pub NAIVE_BYTECOUNT,
2495 "use of naive `<slice>.filter(|&x| x == y).count()` to count byte values"
2498 declare_clippy_lint! {
2499 /// ### What it does
2500 /// It checks for `str::bytes().count()` and suggests replacing it with
2503 /// ### Why is this bad?
2504 /// `str::bytes().count()` is longer and may not be as performant as using
2509 /// "hello".bytes().count();
2510 /// String::from("hello").bytes().count();
2515 /// String::from("hello").len();
2517 #[clippy::version = "1.62.0"]
2518 pub BYTES_COUNT_TO_LEN,
2520 "Using `bytes().count()` when `len()` performs the same functionality"
2523 declare_clippy_lint! {
2524 /// ### What it does
2525 /// Checks for calls to `ends_with` with possible file extensions
2526 /// and suggests to use a case-insensitive approach instead.
2528 /// ### Why is this bad?
2529 /// `ends_with` is case-sensitive and may not detect files with a valid extension.
2533 /// fn is_rust_file(filename: &str) -> bool {
2534 /// filename.ends_with(".rs")
2539 /// fn is_rust_file(filename: &str) -> bool {
2540 /// let filename = std::path::Path::new(filename);
2541 /// filename.extension()
2542 /// .map_or(false, |ext| ext.eq_ignore_ascii_case("rs"))
2545 #[clippy::version = "1.51.0"]
2546 pub CASE_SENSITIVE_FILE_EXTENSION_COMPARISONS,
2548 "Checks for calls to ends_with with case-sensitive file extensions"
2551 declare_clippy_lint! {
2552 /// ### What it does
2553 /// Checks for using `x.get(0)` instead of
2556 /// ### Why is this bad?
2557 /// Using `x.first()` is easier to read and has the same
2562 /// let x = vec![2, 3, 5];
2563 /// let first_element = x.get(0);
2568 /// let x = vec![2, 3, 5];
2569 /// let first_element = x.first();
2571 #[clippy::version = "1.63.0"]
2574 "Using `x.get(0)` when `x.first()` is simpler"
2577 declare_clippy_lint! {
2578 /// ### What it does
2580 /// Finds patterns that reimplement `Option::ok_or`.
2582 /// ### Why is this bad?
2584 /// Concise code helps focusing on behavior instead of boilerplate.
2588 /// let foo: Option<i32> = None;
2589 /// foo.map_or(Err("error"), |v| Ok(v));
2594 /// let foo: Option<i32> = None;
2595 /// foo.ok_or("error");
2597 #[clippy::version = "1.49.0"]
2600 "finds patterns that can be encoded more concisely with `Option::ok_or`"
2603 declare_clippy_lint! {
2604 /// ### What it does
2605 /// Checks for usage of `map(|x| x.clone())` or
2606 /// dereferencing closures for `Copy` types, on `Iterator` or `Option`,
2607 /// and suggests `cloned()` or `copied()` instead
2609 /// ### Why is this bad?
2610 /// Readability, this can be written more concisely
2614 /// let x = vec![42, 43];
2615 /// let y = x.iter();
2616 /// let z = y.map(|i| *i);
2619 /// The correct use would be:
2622 /// let x = vec![42, 43];
2623 /// let y = x.iter();
2624 /// let z = y.cloned();
2626 #[clippy::version = "pre 1.29.0"]
2629 "using `iterator.map(|x| x.clone())`, or dereferencing closures for `Copy` types"
2632 declare_clippy_lint! {
2633 /// ### What it does
2634 /// Checks for instances of `map_err(|_| Some::Enum)`
2636 /// ### Why is this bad?
2637 /// This `map_err` throws away the original error rather than allowing the enum to contain and report the cause of the error
2644 /// #[derive(Debug)]
2650 /// impl fmt::Display for Error {
2651 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2653 /// Error::Indivisible => write!(f, "could not divide input by three"),
2654 /// Error::Remainder(remainder) => write!(
2656 /// "input is not divisible by three, remainder = {}",
2663 /// impl std::error::Error for Error {}
2665 /// fn divisible_by_3(input: &str) -> Result<(), Error> {
2668 /// .map_err(|_| Error::Indivisible)
2670 /// .and_then(|remainder| {
2671 /// if remainder == 0 {
2674 /// Err(Error::Remainder(remainder as u8))
2682 /// use std::{fmt, num::ParseIntError};
2684 /// #[derive(Debug)]
2686 /// Indivisible(ParseIntError),
2690 /// impl fmt::Display for Error {
2691 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2693 /// Error::Indivisible(_) => write!(f, "could not divide input by three"),
2694 /// Error::Remainder(remainder) => write!(
2696 /// "input is not divisible by three, remainder = {}",
2703 /// impl std::error::Error for Error {
2704 /// fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
2706 /// Error::Indivisible(source) => Some(source),
2712 /// fn divisible_by_3(input: &str) -> Result<(), Error> {
2715 /// .map_err(Error::Indivisible)
2717 /// .and_then(|remainder| {
2718 /// if remainder == 0 {
2721 /// Err(Error::Remainder(remainder as u8))
2726 #[clippy::version = "1.48.0"]
2729 "`map_err` should not ignore the original error"
2732 declare_clippy_lint! {
2733 /// ### What it does
2734 /// Checks for `&mut Mutex::lock` calls
2736 /// ### Why is this bad?
2737 /// `Mutex::lock` is less efficient than
2738 /// calling `Mutex::get_mut`. In addition you also have a statically
2739 /// guarantee that the mutex isn't locked, instead of just a runtime
2744 /// use std::sync::{Arc, Mutex};
2746 /// let mut value_rc = Arc::new(Mutex::new(42_u8));
2747 /// let value_mutex = Arc::get_mut(&mut value_rc).unwrap();
2749 /// let mut value = value_mutex.lock().unwrap();
2754 /// use std::sync::{Arc, Mutex};
2756 /// let mut value_rc = Arc::new(Mutex::new(42_u8));
2757 /// let value_mutex = Arc::get_mut(&mut value_rc).unwrap();
2759 /// let value = value_mutex.get_mut().unwrap();
2762 #[clippy::version = "1.49.0"]
2765 "`&mut Mutex::lock` does unnecessary locking"
2768 declare_clippy_lint! {
2769 /// ### What it does
2770 /// Checks for duplicate open options as well as combinations
2771 /// that make no sense.
2773 /// ### Why is this bad?
2774 /// In the best case, the code will be harder to read than
2775 /// necessary. I don't know the worst case.
2779 /// use std::fs::OpenOptions;
2781 /// OpenOptions::new().read(true).truncate(true);
2783 #[clippy::version = "pre 1.29.0"]
2784 pub NONSENSICAL_OPEN_OPTIONS,
2786 "nonsensical combination of options for opening a file"
2789 declare_clippy_lint! {
2790 /// ### What it does
2791 ///* Checks for [push](https://doc.rust-lang.org/std/path/struct.PathBuf.html#method.push)
2792 /// calls on `PathBuf` that can cause overwrites.
2794 /// ### Why is this bad?
2795 /// Calling `push` with a root path at the start can overwrite the
2796 /// previous defined path.
2800 /// use std::path::PathBuf;
2802 /// let mut x = PathBuf::from("/foo");
2804 /// assert_eq!(x, PathBuf::from("/bar"));
2806 /// Could be written:
2809 /// use std::path::PathBuf;
2811 /// let mut x = PathBuf::from("/foo");
2813 /// assert_eq!(x, PathBuf::from("/foo/bar"));
2815 #[clippy::version = "1.36.0"]
2816 pub PATH_BUF_PUSH_OVERWRITE,
2818 "calling `push` with file system root on `PathBuf` can overwrite it"
2821 declare_clippy_lint! {
2822 /// ### What it does
2823 /// Checks for zipping a collection with the range of
2826 /// ### Why is this bad?
2827 /// The code is better expressed with `.enumerate()`.
2831 /// # let x = vec![1];
2832 /// let _ = x.iter().zip(0..x.len());
2837 /// # let x = vec![1];
2838 /// let _ = x.iter().enumerate();
2840 #[clippy::version = "pre 1.29.0"]
2841 pub RANGE_ZIP_WITH_LEN,
2843 "zipping iterator with a range when `enumerate()` would do"
2846 declare_clippy_lint! {
2847 /// ### What it does
2848 /// Checks for usage of `.repeat(1)` and suggest the following method for each types.
2849 /// - `.to_string()` for `str`
2850 /// - `.clone()` for `String`
2851 /// - `.to_vec()` for `slice`
2853 /// The lint will evaluate constant expressions and values as arguments of `.repeat(..)` and emit a message if
2854 /// they are equivalent to `1`. (Related discussion in [rust-clippy#7306](https://github.com/rust-lang/rust-clippy/issues/7306))
2856 /// ### Why is this bad?
2857 /// For example, `String.repeat(1)` is equivalent to `.clone()`. If cloning
2858 /// the string is the intention behind this, `clone()` should be used.
2863 /// let x = String::from("hello world").repeat(1);
2869 /// let x = String::from("hello world").clone();
2872 #[clippy::version = "1.47.0"]
2875 "using `.repeat(1)` instead of `String.clone()`, `str.to_string()` or `slice.to_vec()` "
2878 declare_clippy_lint! {
2879 /// ### What it does
2880 /// When sorting primitive values (integers, bools, chars, as well
2881 /// as arrays, slices, and tuples of such items), it is typically better to
2882 /// use an unstable sort than a stable sort.
2884 /// ### Why is this bad?
2885 /// Typically, using a stable sort consumes more memory and cpu cycles.
2886 /// Because values which compare equal are identical, preserving their
2887 /// relative order (the guarantee that a stable sort provides) means
2888 /// nothing, while the extra costs still apply.
2890 /// ### Known problems
2892 /// As pointed out in
2893 /// [issue #8241](https://github.com/rust-lang/rust-clippy/issues/8241),
2894 /// a stable sort can instead be significantly faster for certain scenarios
2895 /// (eg. when a sorted vector is extended with new data and resorted).
2897 /// For more information and benchmarking results, please refer to the
2898 /// issue linked above.
2902 /// let mut vec = vec![2, 1, 3];
2907 /// let mut vec = vec![2, 1, 3];
2908 /// vec.sort_unstable();
2910 #[clippy::version = "1.47.0"]
2911 pub STABLE_SORT_PRIMITIVE,
2913 "use of sort() when sort_unstable() is equivalent"
2916 declare_clippy_lint! {
2917 /// ### What it does
2918 /// Detects `().hash(_)`.
2920 /// ### Why is this bad?
2921 /// Hashing a unit value doesn't do anything as the implementation of `Hash` for `()` is a no-op.
2925 /// # use std::hash::Hash;
2926 /// # use std::collections::hash_map::DefaultHasher;
2927 /// # enum Foo { Empty, WithValue(u8) }
2929 /// # let mut state = DefaultHasher::new();
2930 /// # let my_enum = Foo::Empty;
2932 /// Empty => ().hash(&mut state),
2933 /// WithValue(x) => x.hash(&mut state),
2938 /// # use std::hash::Hash;
2939 /// # use std::collections::hash_map::DefaultHasher;
2940 /// # enum Foo { Empty, WithValue(u8) }
2942 /// # let mut state = DefaultHasher::new();
2943 /// # let my_enum = Foo::Empty;
2945 /// Empty => 0_u8.hash(&mut state),
2946 /// WithValue(x) => x.hash(&mut state),
2949 #[clippy::version = "1.58.0"]
2952 "hashing a unit value, which does nothing"
2955 declare_clippy_lint! {
2956 /// ### What it does
2957 /// Detects uses of `Vec::sort_by` passing in a closure
2958 /// which compares the two arguments, either directly or indirectly.
2960 /// ### Why is this bad?
2961 /// It is more clear to use `Vec::sort_by_key` (or `Vec::sort` if
2962 /// possible) than to use `Vec::sort_by` and a more complicated
2965 /// ### Known problems
2966 /// If the suggested `Vec::sort_by_key` uses Reverse and it isn't already
2967 /// imported by a use statement, then it will need to be added manually.
2972 /// # impl A { fn foo(&self) {} }
2973 /// # let mut vec: Vec<A> = Vec::new();
2974 /// vec.sort_by(|a, b| a.foo().cmp(&b.foo()));
2979 /// # impl A { fn foo(&self) {} }
2980 /// # let mut vec: Vec<A> = Vec::new();
2981 /// vec.sort_by_key(|a| a.foo());
2983 #[clippy::version = "1.46.0"]
2984 pub UNNECESSARY_SORT_BY,
2986 "Use of `Vec::sort_by` when `Vec::sort_by_key` or `Vec::sort` would be clearer"
2989 declare_clippy_lint! {
2990 /// ### What it does
2991 /// Finds occurrences of `Vec::resize(0, an_int)`
2993 /// ### Why is this bad?
2994 /// This is probably an argument inversion mistake.
2998 /// vec!(1, 2, 3, 4, 5).resize(0, 5)
3003 /// vec!(1, 2, 3, 4, 5).clear()
3005 #[clippy::version = "1.46.0"]
3006 pub VEC_RESIZE_TO_ZERO,
3008 "emptying a vector with `resize(0, an_int)` instead of `clear()` is probably an argument inversion mistake"
3011 declare_clippy_lint! {
3012 /// ### What it does
3013 /// Checks for use of File::read_to_end and File::read_to_string.
3015 /// ### Why is this bad?
3016 /// `fs::{read, read_to_string}` provide the same functionality when `buf` is empty with fewer imports and no intermediate values.
3017 /// 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)
3021 /// # use std::io::Read;
3022 /// # use std::fs::File;
3023 /// let mut f = File::open("foo.txt").unwrap();
3024 /// let mut bytes = Vec::new();
3025 /// f.read_to_end(&mut bytes).unwrap();
3027 /// Can be written more concisely as
3030 /// let mut bytes = fs::read("foo.txt").unwrap();
3032 #[clippy::version = "1.44.0"]
3033 pub VERBOSE_FILE_READS,
3035 "use of `File::read_to_end` or `File::read_to_string`"
3038 declare_clippy_lint! {
3039 /// ### What it does
3041 /// Checks for iterating a map (`HashMap` or `BTreeMap`) and
3042 /// ignoring either the keys or values.
3044 /// ### Why is this bad?
3046 /// Readability. There are `keys` and `values` methods that
3047 /// can be used to express that we only need the keys or the values.
3052 /// # use std::collections::HashMap;
3053 /// let map: HashMap<u32, u32> = HashMap::new();
3054 /// let values = map.iter().map(|(_, value)| value).collect::<Vec<_>>();
3059 /// # use std::collections::HashMap;
3060 /// let map: HashMap<u32, u32> = HashMap::new();
3061 /// let values = map.values().collect::<Vec<_>>();
3063 #[clippy::version = "1.65.0"]
3066 "iterating on map using `iter` when `keys` or `values` would do"
3069 pub struct Methods {
3070 avoid_breaking_exported_api: bool,
3071 msrv: Option<RustcVersion>,
3072 allow_expect_in_tests: bool,
3073 allow_unwrap_in_tests: bool,
3079 avoid_breaking_exported_api: bool,
3080 msrv: Option<RustcVersion>,
3081 allow_expect_in_tests: bool,
3082 allow_unwrap_in_tests: bool,
3085 avoid_breaking_exported_api,
3087 allow_expect_in_tests,
3088 allow_unwrap_in_tests,
3093 impl_lint_pass!(Methods => [
3096 SHOULD_IMPLEMENT_TRAIT,
3097 WRONG_SELF_CONVENTION,
3099 UNWRAP_OR_ELSE_DEFAULT,
3101 RESULT_MAP_OR_INTO_OPTION,
3103 BIND_INSTEAD_OF_MAP,
3112 COLLAPSIBLE_STR_REPLACE,
3113 ITER_OVEREAGER_CLONED,
3114 CLONED_INSTEAD_OF_COPIED,
3116 INEFFICIENT_TO_STRING,
3118 SINGLE_CHAR_PATTERN,
3119 SINGLE_CHAR_ADD_STR,
3123 FILTER_MAP_IDENTITY,
3131 ITERATOR_STEP_BY_ZERO,
3140 STRING_EXTEND_CHARS,
3141 ITER_CLONED_COLLECT,
3145 UNNECESSARY_FILTER_MAP,
3146 UNNECESSARY_FIND_MAP,
3149 UNINIT_ASSUMED_INIT,
3150 MANUAL_SATURATING_ARITHMETIC,
3153 OPTION_AS_REF_DEREF,
3154 UNNECESSARY_LAZY_EVALUATIONS,
3155 MAP_COLLECT_RESULT_UNIT,
3156 FROM_ITER_INSTEAD_OF_COLLECT,
3159 SUSPICIOUS_TO_OWNED,
3165 UNNECESSARY_TO_OWNED,
3168 NEEDLESS_OPTION_AS_DEREF,
3169 IS_DIGIT_ASCII_RADIX,
3170 NEEDLESS_OPTION_TAKE,
3173 ITER_ON_SINGLE_ITEMS,
3174 ITER_ON_EMPTY_COLLECTIONS,
3177 CASE_SENSITIVE_FILE_EXTENSION_COMPARISONS,
3183 NONSENSICAL_OPEN_OPTIONS,
3184 PATH_BUF_PUSH_OVERWRITE,
3187 STABLE_SORT_PRIMITIVE,
3189 UNNECESSARY_SORT_BY,
3195 /// Extracts a method call name, args, and `Span` of the method name.
3196 fn method_call<'tcx>(
3197 recv: &'tcx hir::Expr<'tcx>,
3198 ) -> Option<(&'tcx str, &'tcx hir::Expr<'tcx>, &'tcx [hir::Expr<'tcx>], Span)> {
3199 if let ExprKind::MethodCall(path, receiver, args, _) = recv.kind {
3200 if !args.iter().any(|e| e.span.from_expansion()) && !receiver.span.from_expansion() {
3201 let name = path.ident.name.as_str();
3202 return Some((name, receiver, args, path.ident.span));
3208 impl<'tcx> LateLintPass<'tcx> for Methods {
3209 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) {
3210 if expr.span.from_expansion() {
3214 self.check_methods(cx, expr);
3217 hir::ExprKind::Call(func, args) => {
3218 from_iter_instead_of_collect::check(cx, expr, args, func);
3220 hir::ExprKind::MethodCall(method_call, receiver, args, _) => {
3221 let method_span = method_call.ident.span;
3222 or_fun_call::check(cx, expr, method_span, method_call.ident.as_str(), receiver, args);
3223 expect_fun_call::check(cx, expr, method_span, method_call.ident.as_str(), receiver, args);
3224 clone_on_copy::check(cx, expr, method_call.ident.name, receiver, args);
3225 clone_on_ref_ptr::check(cx, expr, method_call.ident.name, receiver, args);
3226 inefficient_to_string::check(cx, expr, method_call.ident.name, receiver, args);
3227 single_char_add_str::check(cx, expr, receiver, args);
3228 into_iter_on_ref::check(cx, expr, method_span, method_call.ident.name, receiver);
3229 single_char_pattern::check(cx, expr, method_call.ident.name, receiver, args);
3230 unnecessary_to_owned::check(cx, expr, method_call.ident.name, receiver, args, self.msrv);
3232 hir::ExprKind::Binary(op, lhs, rhs) if op.node == hir::BinOpKind::Eq || op.node == hir::BinOpKind::Ne => {
3233 let mut info = BinaryExprInfo {
3237 eq: op.node == hir::BinOpKind::Eq,
3239 lint_binary_expr_with_method_call(cx, &mut info);
3245 #[allow(clippy::too_many_lines)]
3246 fn check_impl_item(&mut self, cx: &LateContext<'tcx>, impl_item: &'tcx hir::ImplItem<'_>) {
3247 if in_external_macro(cx.sess(), impl_item.span) {
3250 let name = impl_item.ident.name.as_str();
3251 let parent = cx.tcx.hir().get_parent_item(impl_item.hir_id()).def_id;
3252 let item = cx.tcx.hir().expect_item(parent);
3253 let self_ty = cx.tcx.type_of(item.owner_id);
3255 let implements_trait = matches!(item.kind, hir::ItemKind::Impl(hir::Impl { of_trait: Some(_), .. }));
3256 if let hir::ImplItemKind::Fn(ref sig, id) = impl_item.kind {
3257 let method_sig = cx.tcx.fn_sig(impl_item.owner_id);
3258 let method_sig = cx.tcx.erase_late_bound_regions(method_sig);
3259 let first_arg_ty_opt = method_sig.inputs().iter().next().copied();
3260 // if this impl block implements a trait, lint in trait definition instead
3261 if !implements_trait && cx.effective_visibilities.is_exported(impl_item.owner_id.def_id) {
3262 // check missing trait implementations
3263 for method_config in &TRAIT_METHODS {
3264 if name == method_config.method_name
3265 && sig.decl.inputs.len() == method_config.param_count
3266 && method_config.output_type.matches(&sig.decl.output)
3267 // in case there is no first arg, since we already have checked the number of arguments
3268 // it's should be always true
3269 && first_arg_ty_opt.map_or(true, |first_arg_ty| method_config
3270 .self_kind.matches(cx, self_ty, first_arg_ty)
3272 && fn_header_equals(method_config.fn_header, sig.header)
3273 && method_config.lifetime_param_cond(impl_item)
3277 SHOULD_IMPLEMENT_TRAIT,
3280 "method `{}` can be confused for the standard trait method `{}::{}`",
3281 method_config.method_name, method_config.trait_name, method_config.method_name
3285 "consider implementing the trait `{}` or choosing a less ambiguous method name",
3286 method_config.trait_name
3293 if sig.decl.implicit_self.has_implicit_self()
3294 && !(self.avoid_breaking_exported_api
3295 && cx.effective_visibilities.is_exported(impl_item.owner_id.def_id))
3296 && let Some(first_arg) = iter_input_pats(sig.decl, cx.tcx.hir().body(id)).next()
3297 && let Some(first_arg_ty) = first_arg_ty_opt
3299 wrong_self_convention::check(
3311 // if this impl block implements a trait, lint in trait definition instead
3312 if implements_trait {
3316 if let hir::ImplItemKind::Fn(_, _) = impl_item.kind {
3317 let ret_ty = return_ty(cx, impl_item.hir_id());
3319 // walk the return type and check for Self (this does not check associated types)
3320 if let Some(self_adt) = self_ty.ty_adt_def() {
3321 if contains_adt_constructor(ret_ty, self_adt) {
3324 } else if ret_ty.contains(self_ty) {
3328 // if return type is impl trait, check the associated types
3329 if let ty::Opaque(def_id, _) = *ret_ty.kind() {
3330 // one of the associated types must be Self
3331 for &(predicate, _span) in cx.tcx.explicit_item_bounds(def_id) {
3332 if let ty::PredicateKind::Projection(projection_predicate) = predicate.kind().skip_binder() {
3333 let assoc_ty = match projection_predicate.term.unpack() {
3334 ty::TermKind::Ty(ty) => ty,
3335 ty::TermKind::Const(_c) => continue,
3337 // walk the associated type and check for Self
3338 if let Some(self_adt) = self_ty.ty_adt_def() {
3339 if contains_adt_constructor(assoc_ty, self_adt) {
3342 } else if assoc_ty.contains(self_ty) {
3349 if name == "new" && ret_ty != self_ty {
3354 "methods called `new` usually return `Self`",
3360 fn check_trait_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx TraitItem<'_>) {
3361 if in_external_macro(cx.tcx.sess, item.span) {
3366 if let TraitItemKind::Fn(ref sig, _) = item.kind;
3367 if sig.decl.implicit_self.has_implicit_self();
3368 if let Some(first_arg_ty) = sig.decl.inputs.iter().next();
3371 let first_arg_span = first_arg_ty.span;
3372 let first_arg_ty = hir_ty_to_ty(cx.tcx, first_arg_ty);
3373 let self_ty = TraitRef::identity(cx.tcx, item.owner_id.to_def_id())
3376 wrong_self_convention::check(
3378 item.ident.name.as_str(),
3389 if item.ident.name == sym::new;
3390 if let TraitItemKind::Fn(_, _) = item.kind;
3391 let ret_ty = return_ty(cx, item.hir_id());
3392 let self_ty = TraitRef::identity(cx.tcx, item.owner_id.to_def_id())
3395 if !ret_ty.contains(self_ty);
3402 "methods called `new` usually return `Self`",
3408 extract_msrv_attr!(LateContext);
3412 #[allow(clippy::too_many_lines)]
3413 fn check_methods<'tcx>(&self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
3414 if let Some((name, recv, args, span)) = method_call(expr) {
3415 match (name, args) {
3416 ("add" | "offset" | "sub" | "wrapping_offset" | "wrapping_add" | "wrapping_sub", [_arg]) => {
3417 zst_offset::check(cx, expr, recv);
3419 ("and_then", [arg]) => {
3420 let biom_option_linted = bind_instead_of_map::OptionAndThenSome::check(cx, expr, recv, arg);
3421 let biom_result_linted = bind_instead_of_map::ResultAndThenOk::check(cx, expr, recv, arg);
3422 if !biom_option_linted && !biom_result_linted {
3423 unnecessary_lazy_eval::check(cx, expr, recv, arg, "and");
3426 ("as_deref" | "as_deref_mut", []) => {
3427 needless_option_as_deref::check(cx, expr, recv, name);
3429 ("as_mut", []) => useless_asref::check(cx, expr, "as_mut", recv),
3430 ("as_ref", []) => useless_asref::check(cx, expr, "as_ref", recv),
3431 ("assume_init", []) => uninit_assumed_init::check(cx, expr, recv),
3432 ("cloned", []) => cloned_instead_of_copied::check(cx, expr, recv, span, self.msrv),
3433 ("collect", []) => match method_call(recv) {
3434 Some((name @ ("cloned" | "copied"), recv2, [], _)) => {
3435 iter_cloned_collect::check(cx, name, expr, recv2);
3437 Some(("map", m_recv, [m_arg], _)) => {
3438 map_collect_result_unit::check(cx, expr, m_recv, m_arg, recv);
3440 Some(("take", take_self_arg, [take_arg], _)) => {
3441 if meets_msrv(self.msrv, msrvs::STR_REPEAT) {
3442 manual_str_repeat::check(cx, expr, recv, take_self_arg, take_arg);
3447 ("count", []) if is_trait_method(cx, expr, sym::Iterator) => match method_call(recv) {
3448 Some(("cloned", recv2, [], _)) => iter_overeager_cloned::check(cx, expr, recv, recv2, true, false),
3449 Some((name2 @ ("into_iter" | "iter" | "iter_mut"), recv2, [], _)) => {
3450 iter_count::check(cx, expr, recv2, name2);
3452 Some(("map", _, [arg], _)) => suspicious_map::check(cx, expr, recv, arg),
3453 Some(("filter", recv2, [arg], _)) => bytecount::check(cx, expr, recv2, arg),
3454 Some(("bytes", recv2, [], _)) => bytes_count_to_len::check(cx, expr, recv, recv2),
3457 ("drain", [arg]) => {
3458 iter_with_drain::check(cx, expr, recv, span, arg);
3460 ("ends_with", [arg]) => {
3461 if let ExprKind::MethodCall(.., span) = expr.kind {
3462 case_sensitive_file_extension_comparisons::check(cx, expr, span, recv, arg);
3465 ("expect", [_]) => match method_call(recv) {
3466 Some(("ok", recv, [], _)) => ok_expect::check(cx, expr, recv),
3467 Some(("err", recv, [], err_span)) => err_expect::check(cx, expr, recv, self.msrv, span, err_span),
3468 _ => expect_used::check(cx, expr, recv, false, self.allow_expect_in_tests),
3470 ("expect_err", [_]) => expect_used::check(cx, expr, recv, true, self.allow_expect_in_tests),
3471 ("extend", [arg]) => {
3472 string_extend_chars::check(cx, expr, recv, arg);
3473 extend_with_drain::check(cx, expr, recv, arg);
3475 ("filter_map", [arg]) => {
3476 unnecessary_filter_map::check(cx, expr, arg, name);
3477 filter_map_identity::check(cx, expr, arg, span);
3479 ("find_map", [arg]) => {
3480 unnecessary_filter_map::check(cx, expr, arg, name);
3482 ("flat_map", [arg]) => {
3483 flat_map_identity::check(cx, expr, arg, span);
3484 flat_map_option::check(cx, expr, arg, span);
3486 ("flatten", []) => match method_call(recv) {
3487 Some(("map", recv, [map_arg], map_span)) => map_flatten::check(cx, expr, recv, map_arg, map_span),
3488 Some(("cloned", recv2, [], _)) => iter_overeager_cloned::check(cx, expr, recv, recv2, false, true),
3491 ("fold", [init, acc]) => unnecessary_fold::check(cx, expr, init, acc, span),
3492 ("for_each", [_]) => {
3493 if let Some(("inspect", _, [_], span2)) = method_call(recv) {
3494 inspect_for_each::check(cx, expr, span2);
3498 get_first::check(cx, expr, recv, arg);
3499 get_last_with_len::check(cx, expr, recv, arg);
3501 ("get_or_insert_with", [arg]) => unnecessary_lazy_eval::check(cx, expr, recv, arg, "get_or_insert"),
3502 ("hash", [arg]) => {
3503 unit_hash::check(cx, expr, recv, arg);
3505 ("is_file", []) => filetype_is_file::check(cx, expr, recv),
3506 ("is_digit", [radix]) => is_digit_ascii_radix::check(cx, expr, recv, radix, self.msrv),
3507 ("is_none", []) => check_is_some_is_none(cx, expr, recv, false),
3508 ("is_some", []) => check_is_some_is_none(cx, expr, recv, true),
3509 ("iter" | "iter_mut" | "into_iter", []) => {
3510 iter_on_single_or_empty_collections::check(cx, expr, name, recv);
3512 ("join", [join_arg]) => {
3513 if let Some(("collect", _, _, span)) = method_call(recv) {
3514 unnecessary_join::check(cx, expr, recv, join_arg, span);
3517 ("last", []) | ("skip", [_]) => {
3518 if let Some((name2, recv2, args2, _span2)) = method_call(recv) {
3519 if let ("cloned", []) = (name2, args2) {
3520 iter_overeager_cloned::check(cx, expr, recv, recv2, false, false);
3525 mut_mutex_lock::check(cx, expr, recv, span);
3527 (name @ ("map" | "map_err"), [m_arg]) => {
3529 map_clone::check(cx, expr, recv, m_arg, self.msrv);
3530 if let Some((map_name @ ("iter" | "into_iter"), recv2, _, _)) = method_call(recv) {
3531 iter_kv_map::check(cx, map_name, expr, recv2, m_arg);
3534 map_err_ignore::check(cx, expr, m_arg);
3536 if let Some((name, recv2, args, span2)) = method_call(recv) {
3537 match (name, args) {
3538 ("as_mut", []) => option_as_ref_deref::check(cx, expr, recv2, m_arg, true, self.msrv),
3539 ("as_ref", []) => option_as_ref_deref::check(cx, expr, recv2, m_arg, false, self.msrv),
3540 ("filter", [f_arg]) => {
3541 filter_map::check(cx, expr, recv2, f_arg, span2, recv, m_arg, span, false);
3543 ("find", [f_arg]) => {
3544 filter_map::check(cx, expr, recv2, f_arg, span2, recv, m_arg, span, true);
3549 map_identity::check(cx, expr, recv, m_arg, name, span);
3551 ("map_or", [def, map]) => {
3552 option_map_or_none::check(cx, expr, recv, def, map);
3553 manual_ok_or::check(cx, expr, recv, def, map);
3556 if let Some((name2, recv2, args2, _)) = method_call(recv) {
3557 match (name2, args2) {
3558 ("cloned", []) => iter_overeager_cloned::check(cx, expr, recv, recv2, false, false),
3559 ("filter", [arg]) => filter_next::check(cx, expr, recv2, arg),
3560 ("filter_map", [arg]) => filter_map_next::check(cx, expr, recv2, arg, self.msrv),
3561 ("iter", []) => iter_next_slice::check(cx, expr, recv2),
3562 ("skip", [arg]) => iter_skip_next::check(cx, expr, recv2, arg),
3563 ("skip_while", [_]) => skip_while_next::check(cx, expr),
3568 ("nth", [n_arg]) => match method_call(recv) {
3569 Some(("bytes", recv2, [], _)) => bytes_nth::check(cx, expr, recv2, n_arg),
3570 Some(("cloned", recv2, [], _)) => iter_overeager_cloned::check(cx, expr, recv, recv2, false, false),
3571 Some(("iter", recv2, [], _)) => iter_nth::check(cx, expr, recv2, recv, n_arg, false),
3572 Some(("iter_mut", recv2, [], _)) => iter_nth::check(cx, expr, recv2, recv, n_arg, true),
3573 _ => iter_nth_zero::check(cx, expr, recv, n_arg),
3575 ("ok_or_else", [arg]) => unnecessary_lazy_eval::check(cx, expr, recv, arg, "ok_or"),
3577 open_options::check(cx, expr, recv);
3579 ("or_else", [arg]) => {
3580 if !bind_instead_of_map::ResultOrElseErrInfo::check(cx, expr, recv, arg) {
3581 unnecessary_lazy_eval::check(cx, expr, recv, arg, "or");
3584 ("push", [arg]) => {
3585 path_buf_push_overwrite::check(cx, expr, arg);
3587 ("read_to_end", [_]) => {
3588 verbose_file_reads::check(cx, expr, recv, verbose_file_reads::READ_TO_END_MSG);
3590 ("read_to_string", [_]) => {
3591 verbose_file_reads::check(cx, expr, recv, verbose_file_reads::READ_TO_STRING_MSG);
3593 ("repeat", [arg]) => {
3594 repeat_once::check(cx, expr, recv, arg);
3596 (name @ ("replace" | "replacen"), [arg1, arg2] | [arg1, arg2, _]) => {
3597 no_effect_replace::check(cx, expr, arg1, arg2);
3599 // Check for repeated `str::replace` calls to perform `collapsible_str_replace` lint
3600 if name == "replace" && let Some(("replace", ..)) = method_call(recv) {
3601 collapsible_str_replace::check(cx, expr, arg1, arg2);
3604 ("resize", [count_arg, default_arg]) => {
3605 vec_resize_to_zero::check(cx, expr, count_arg, default_arg, span);
3608 stable_sort_primitive::check(cx, expr, recv);
3610 ("sort_by", [arg]) => {
3611 unnecessary_sort_by::check(cx, expr, recv, arg, false);
3613 ("sort_unstable_by", [arg]) => {
3614 unnecessary_sort_by::check(cx, expr, recv, arg, true);
3616 ("splitn" | "rsplitn", [count_arg, pat_arg]) => {
3617 if let Some((Constant::Int(count), _)) = constant(cx, cx.typeck_results(), count_arg) {
3618 suspicious_splitn::check(cx, name, expr, recv, count);
3619 str_splitn::check(cx, name, expr, recv, pat_arg, count, self.msrv);
3622 ("splitn_mut" | "rsplitn_mut", [count_arg, _]) => {
3623 if let Some((Constant::Int(count), _)) = constant(cx, cx.typeck_results(), count_arg) {
3624 suspicious_splitn::check(cx, name, expr, recv, count);
3627 ("step_by", [arg]) => iterator_step_by_zero::check(cx, expr, arg),
3628 ("take", [_arg]) => {
3629 if let Some((name2, recv2, args2, _span2)) = method_call(recv) {
3630 if let ("cloned", []) = (name2, args2) {
3631 iter_overeager_cloned::check(cx, expr, recv, recv2, false, false);
3635 ("take", []) => needless_option_take::check(cx, expr, recv),
3636 ("then", [arg]) => {
3637 if !meets_msrv(self.msrv, msrvs::BOOL_THEN_SOME) {
3640 unnecessary_lazy_eval::check(cx, expr, recv, arg, "then_some");
3642 ("to_owned", []) => {
3643 if !suspicious_to_owned::check(cx, expr, recv) {
3644 implicit_clone::check(cx, name, expr, recv);
3647 ("to_os_string" | "to_path_buf" | "to_vec", []) => {
3648 implicit_clone::check(cx, name, expr, recv);
3651 match method_call(recv) {
3652 Some(("get", recv, [get_arg], _)) => {
3653 get_unwrap::check(cx, expr, recv, get_arg, false);
3655 Some(("get_mut", recv, [get_arg], _)) => {
3656 get_unwrap::check(cx, expr, recv, get_arg, true);
3658 Some(("or", recv, [or_arg], or_span)) => {
3659 or_then_unwrap::check(cx, expr, recv, or_arg, or_span);
3663 unwrap_used::check(cx, expr, recv, false, self.allow_unwrap_in_tests);
3665 ("unwrap_err", []) => unwrap_used::check(cx, expr, recv, true, self.allow_unwrap_in_tests),
3666 ("unwrap_or", [u_arg]) => match method_call(recv) {
3667 Some((arith @ ("checked_add" | "checked_sub" | "checked_mul"), lhs, [rhs], _)) => {
3668 manual_saturating_arithmetic::check(cx, expr, lhs, rhs, u_arg, &arith["checked_".len()..]);
3670 Some(("map", m_recv, [m_arg], span)) => {
3671 option_map_unwrap_or::check(cx, expr, m_recv, m_arg, recv, u_arg, span);
3673 Some(("then_some", t_recv, [t_arg], _)) => {
3674 obfuscated_if_else::check(cx, expr, t_recv, t_arg, u_arg);
3678 ("unwrap_or_else", [u_arg]) => match method_call(recv) {
3679 Some(("map", recv, [map_arg], _))
3680 if map_unwrap_or::check(cx, expr, recv, map_arg, u_arg, self.msrv) => {},
3682 unwrap_or_else_default::check(cx, expr, recv, u_arg);
3683 unnecessary_lazy_eval::check(cx, expr, recv, u_arg, "unwrap_or");
3687 if let ExprKind::MethodCall(name, iter_recv, [], _) = recv.kind
3688 && name.ident.name == sym::iter
3690 range_zip_with_len::check(cx, expr, iter_recv, arg);
3699 fn check_is_some_is_none(cx: &LateContext<'_>, expr: &Expr<'_>, recv: &Expr<'_>, is_some: bool) {
3700 if let Some((name @ ("find" | "position" | "rposition"), f_recv, [arg], span)) = method_call(recv) {
3701 search_is_some::check(cx, expr, name, is_some, f_recv, arg, recv, span);
3705 /// Used for `lint_binary_expr_with_method_call`.
3706 #[derive(Copy, Clone)]
3707 struct BinaryExprInfo<'a> {
3708 expr: &'a hir::Expr<'a>,
3709 chain: &'a hir::Expr<'a>,
3710 other: &'a hir::Expr<'a>,
3714 /// Checks for the `CHARS_NEXT_CMP` and `CHARS_LAST_CMP` lints.
3715 fn lint_binary_expr_with_method_call(cx: &LateContext<'_>, info: &mut BinaryExprInfo<'_>) {
3716 macro_rules! lint_with_both_lhs_and_rhs {
3717 ($func:expr, $cx:expr, $info:ident) => {
3718 if !$func($cx, $info) {
3719 ::std::mem::swap(&mut $info.chain, &mut $info.other);
3720 if $func($cx, $info) {
3727 lint_with_both_lhs_and_rhs!(chars_next_cmp::check, cx, info);
3728 lint_with_both_lhs_and_rhs!(chars_last_cmp::check, cx, info);
3729 lint_with_both_lhs_and_rhs!(chars_next_cmp_with_unwrap::check, cx, info);
3730 lint_with_both_lhs_and_rhs!(chars_last_cmp_with_unwrap::check, cx, info);
3733 const FN_HEADER: hir::FnHeader = hir::FnHeader {
3734 unsafety: hir::Unsafety::Normal,
3735 constness: hir::Constness::NotConst,
3736 asyncness: hir::IsAsync::NotAsync,
3737 abi: rustc_target::spec::abi::Abi::Rust,
3740 struct ShouldImplTraitCase {
3741 trait_name: &'static str,
3742 method_name: &'static str,
3744 fn_header: hir::FnHeader,
3745 // implicit self kind expected (none, self, &self, ...)
3746 self_kind: SelfKind,
3747 // checks against the output type
3748 output_type: OutType,
3749 // certain methods with explicit lifetimes can't implement the equivalent trait method
3750 lint_explicit_lifetime: bool,
3752 impl ShouldImplTraitCase {
3754 trait_name: &'static str,
3755 method_name: &'static str,
3757 fn_header: hir::FnHeader,
3758 self_kind: SelfKind,
3759 output_type: OutType,
3760 lint_explicit_lifetime: bool,
3761 ) -> ShouldImplTraitCase {
3762 ShouldImplTraitCase {
3769 lint_explicit_lifetime,
3773 fn lifetime_param_cond(&self, impl_item: &hir::ImplItem<'_>) -> bool {
3774 self.lint_explicit_lifetime
3775 || !impl_item.generics.params.iter().any(|p| {
3778 hir::GenericParamKind::Lifetime {
3779 kind: hir::LifetimeParamKind::Explicit
3787 const TRAIT_METHODS: [ShouldImplTraitCase; 30] = [
3788 ShouldImplTraitCase::new("std::ops::Add", "add", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3789 ShouldImplTraitCase::new("std::convert::AsMut", "as_mut", 1, FN_HEADER, SelfKind::RefMut, OutType::Ref, true),
3790 ShouldImplTraitCase::new("std::convert::AsRef", "as_ref", 1, FN_HEADER, SelfKind::Ref, OutType::Ref, true),
3791 ShouldImplTraitCase::new("std::ops::BitAnd", "bitand", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3792 ShouldImplTraitCase::new("std::ops::BitOr", "bitor", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3793 ShouldImplTraitCase::new("std::ops::BitXor", "bitxor", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3794 ShouldImplTraitCase::new("std::borrow::Borrow", "borrow", 1, FN_HEADER, SelfKind::Ref, OutType::Ref, true),
3795 ShouldImplTraitCase::new("std::borrow::BorrowMut", "borrow_mut", 1, FN_HEADER, SelfKind::RefMut, OutType::Ref, true),
3796 ShouldImplTraitCase::new("std::clone::Clone", "clone", 1, FN_HEADER, SelfKind::Ref, OutType::Any, true),
3797 ShouldImplTraitCase::new("std::cmp::Ord", "cmp", 2, FN_HEADER, SelfKind::Ref, OutType::Any, true),
3798 ShouldImplTraitCase::new("std::default::Default", "default", 0, FN_HEADER, SelfKind::No, OutType::Any, true),
3799 ShouldImplTraitCase::new("std::ops::Deref", "deref", 1, FN_HEADER, SelfKind::Ref, OutType::Ref, true),
3800 ShouldImplTraitCase::new("std::ops::DerefMut", "deref_mut", 1, FN_HEADER, SelfKind::RefMut, OutType::Ref, true),
3801 ShouldImplTraitCase::new("std::ops::Div", "div", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3802 ShouldImplTraitCase::new("std::ops::Drop", "drop", 1, FN_HEADER, SelfKind::RefMut, OutType::Unit, true),
3803 ShouldImplTraitCase::new("std::cmp::PartialEq", "eq", 2, FN_HEADER, SelfKind::Ref, OutType::Bool, true),
3804 ShouldImplTraitCase::new("std::iter::FromIterator", "from_iter", 1, FN_HEADER, SelfKind::No, OutType::Any, true),
3805 ShouldImplTraitCase::new("std::str::FromStr", "from_str", 1, FN_HEADER, SelfKind::No, OutType::Any, true),
3806 ShouldImplTraitCase::new("std::hash::Hash", "hash", 2, FN_HEADER, SelfKind::Ref, OutType::Unit, true),
3807 ShouldImplTraitCase::new("std::ops::Index", "index", 2, FN_HEADER, SelfKind::Ref, OutType::Ref, true),
3808 ShouldImplTraitCase::new("std::ops::IndexMut", "index_mut", 2, FN_HEADER, SelfKind::RefMut, OutType::Ref, true),
3809 ShouldImplTraitCase::new("std::iter::IntoIterator", "into_iter", 1, FN_HEADER, SelfKind::Value, OutType::Any, true),
3810 ShouldImplTraitCase::new("std::ops::Mul", "mul", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3811 ShouldImplTraitCase::new("std::ops::Neg", "neg", 1, FN_HEADER, SelfKind::Value, OutType::Any, true),
3812 ShouldImplTraitCase::new("std::iter::Iterator", "next", 1, FN_HEADER, SelfKind::RefMut, OutType::Any, false),
3813 ShouldImplTraitCase::new("std::ops::Not", "not", 1, FN_HEADER, SelfKind::Value, OutType::Any, true),
3814 ShouldImplTraitCase::new("std::ops::Rem", "rem", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3815 ShouldImplTraitCase::new("std::ops::Shl", "shl", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3816 ShouldImplTraitCase::new("std::ops::Shr", "shr", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3817 ShouldImplTraitCase::new("std::ops::Sub", "sub", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3820 #[derive(Clone, Copy, PartialEq, Eq, Debug)]
3825 No, // When we want the first argument type to be different than `Self`
3829 fn matches<'a>(self, cx: &LateContext<'a>, parent_ty: Ty<'a>, ty: Ty<'a>) -> bool {
3830 fn matches_value<'a>(cx: &LateContext<'a>, parent_ty: Ty<'a>, ty: Ty<'a>) -> bool {
3831 if ty == parent_ty {
3833 } else if ty.is_box() {
3834 ty.boxed_ty() == parent_ty
3835 } else if is_type_diagnostic_item(cx, ty, sym::Rc) || is_type_diagnostic_item(cx, ty, sym::Arc) {
3836 if let ty::Adt(_, substs) = ty.kind() {
3837 substs.types().next().map_or(false, |t| t == parent_ty)
3846 fn matches_ref<'a>(cx: &LateContext<'a>, mutability: hir::Mutability, parent_ty: Ty<'a>, ty: Ty<'a>) -> bool {
3847 if let ty::Ref(_, t, m) = *ty.kind() {
3848 return m == mutability && t == parent_ty;
3851 let trait_sym = match mutability {
3852 hir::Mutability::Not => sym::AsRef,
3853 hir::Mutability::Mut => sym::AsMut,
3856 let Some(trait_def_id) = cx.tcx.get_diagnostic_item(trait_sym) else {
3859 implements_trait(cx, ty, trait_def_id, &[parent_ty.into()])
3862 fn matches_none<'a>(cx: &LateContext<'a>, parent_ty: Ty<'a>, ty: Ty<'a>) -> bool {
3863 !matches_value(cx, parent_ty, ty)
3864 && !matches_ref(cx, hir::Mutability::Not, parent_ty, ty)
3865 && !matches_ref(cx, hir::Mutability::Mut, parent_ty, ty)
3869 Self::Value => matches_value(cx, parent_ty, ty),
3870 Self::Ref => matches_ref(cx, hir::Mutability::Not, parent_ty, ty) || ty == parent_ty && is_copy(cx, ty),
3871 Self::RefMut => matches_ref(cx, hir::Mutability::Mut, parent_ty, ty),
3872 Self::No => matches_none(cx, parent_ty, ty),
3877 fn description(self) -> &'static str {
3879 Self::Value => "`self` by value",
3880 Self::Ref => "`self` by reference",
3881 Self::RefMut => "`self` by mutable reference",
3882 Self::No => "no `self`",
3887 #[derive(Clone, Copy)]
3896 fn matches(self, ty: &hir::FnRetTy<'_>) -> bool {
3897 let is_unit = |ty: &hir::Ty<'_>| matches!(ty.kind, hir::TyKind::Tup(&[]));
3899 (Self::Unit, &hir::FnRetTy::DefaultReturn(_)) => true,
3900 (Self::Unit, &hir::FnRetTy::Return(ty)) if is_unit(ty) => true,
3901 (Self::Bool, &hir::FnRetTy::Return(ty)) if is_bool(ty) => true,
3902 (Self::Any, &hir::FnRetTy::Return(ty)) if !is_unit(ty) => true,
3903 (Self::Ref, &hir::FnRetTy::Return(ty)) => matches!(ty.kind, hir::TyKind::Rptr(_, _)),
3909 fn is_bool(ty: &hir::Ty<'_>) -> bool {
3910 if let hir::TyKind::Path(QPath::Resolved(_, path)) = ty.kind {
3911 matches!(path.res, Res::PrimTy(PrimTy::Bool))
3917 fn fn_header_equals(expected: hir::FnHeader, actual: hir::FnHeader) -> bool {
3918 expected.constness == actual.constness
3919 && expected.unsafety == actual.unsafety
3920 && expected.asyncness == actual.asyncness