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};
106 contains_return, get_trait_def_id, is_trait_method, iter_input_pats, meets_msrv, msrvs, paths, return_ty,
108 use if_chain::if_chain;
109 use rustc_hir as hir;
110 use rustc_hir::def::Res;
111 use rustc_hir::{Expr, ExprKind, PrimTy, QPath, TraitItem, TraitItemKind};
112 use rustc_lint::{LateContext, LateLintPass, LintContext};
113 use rustc_middle::lint::in_external_macro;
114 use rustc_middle::ty::{self, TraitRef, Ty};
115 use rustc_semver::RustcVersion;
116 use rustc_session::{declare_tool_lint, impl_lint_pass};
117 use rustc_span::{sym, Span};
118 use rustc_hir_analysis::hir_ty_to_ty;
120 declare_clippy_lint! {
122 /// Checks for usages of `cloned()` on an `Iterator` or `Option` where
123 /// `copied()` could be used instead.
125 /// ### Why is this bad?
126 /// `copied()` is better because it guarantees that the type being cloned
127 /// implements `Copy`.
131 /// [1, 2, 3].iter().cloned();
135 /// [1, 2, 3].iter().copied();
137 #[clippy::version = "1.53.0"]
138 pub CLONED_INSTEAD_OF_COPIED,
140 "used `cloned` where `copied` could be used instead"
143 declare_clippy_lint! {
145 /// Checks for consecutive calls to `str::replace` (2 or more)
146 /// that can be collapsed into a single call.
148 /// ### Why is this bad?
149 /// Consecutive `str::replace` calls scan the string multiple times
150 /// with repetitive code.
154 /// let hello = "hesuo worpd"
155 /// .replace('s', "l")
156 /// .replace("u", "l")
157 /// .replace('p', "l");
161 /// let hello = "hesuo worpd".replace(&['s', 'u', 'p'], "l");
163 #[clippy::version = "1.64.0"]
164 pub COLLAPSIBLE_STR_REPLACE,
166 "collapse consecutive calls to str::replace (2 or more) into a single call"
169 declare_clippy_lint! {
171 /// Checks for usage of `_.cloned().<func>()` where call to `.cloned()` can be postponed.
173 /// ### Why is this bad?
174 /// It's often inefficient to clone all elements of an iterator, when eventually, only some
175 /// of them will be consumed.
177 /// ### Known Problems
178 /// This `lint` removes the side of effect of cloning items in the iterator.
179 /// A code that relies on that side-effect could fail.
183 /// # let vec = vec!["string".to_string()];
184 /// vec.iter().cloned().take(10);
185 /// vec.iter().cloned().last();
190 /// # let vec = vec!["string".to_string()];
191 /// vec.iter().take(10).cloned();
192 /// vec.iter().last().cloned();
194 #[clippy::version = "1.60.0"]
195 pub ITER_OVEREAGER_CLONED,
197 "using `cloned()` early with `Iterator::iter()` can lead to some performance inefficiencies"
200 declare_clippy_lint! {
202 /// Checks for usages of `Iterator::flat_map()` where `filter_map()` could be
205 /// ### Why is this bad?
206 /// When applicable, `filter_map()` is more clear since it shows that
207 /// `Option` is used to produce 0 or 1 items.
211 /// let nums: Vec<i32> = ["1", "2", "whee!"].iter().flat_map(|x| x.parse().ok()).collect();
215 /// let nums: Vec<i32> = ["1", "2", "whee!"].iter().filter_map(|x| x.parse().ok()).collect();
217 #[clippy::version = "1.53.0"]
220 "used `flat_map` where `filter_map` could be used instead"
223 declare_clippy_lint! {
225 /// Checks for `.unwrap()` or `.unwrap_err()` calls on `Result`s and `.unwrap()` call on `Option`s.
227 /// ### Why is this bad?
228 /// It is better to handle the `None` or `Err` case,
229 /// or at least call `.expect(_)` with a more helpful message. Still, for a lot of
230 /// quick-and-dirty code, `unwrap` is a good choice, which is why this lint is
231 /// `Allow` by default.
233 /// `result.unwrap()` will let the thread panic on `Err` values.
234 /// Normally, you want to implement more sophisticated error handling,
235 /// and propagate errors upwards with `?` operator.
237 /// Even if you want to panic on errors, not all `Error`s implement good
238 /// messages on display. Therefore, it may be beneficial to look at the places
239 /// where they may get displayed. Activate this lint to do just that.
243 /// # let option = Some(1);
244 /// # let result: Result<usize, ()> = Ok(1);
251 /// # let option = Some(1);
252 /// # let result: Result<usize, ()> = Ok(1);
253 /// option.expect("more helpful message");
254 /// result.expect("more helpful message");
257 /// If [expect_used](#expect_used) is enabled, instead:
259 /// # let option = Some(1);
260 /// # let result: Result<usize, ()> = Ok(1);
267 #[clippy::version = "1.45.0"]
270 "using `.unwrap()` on `Result` or `Option`, which should at least get a better message using `expect()`"
273 declare_clippy_lint! {
275 /// Checks for `.expect()` or `.expect_err()` calls on `Result`s and `.expect()` call on `Option`s.
277 /// ### Why is this bad?
278 /// Usually it is better to handle the `None` or `Err` case.
279 /// Still, for a lot of quick-and-dirty code, `expect` is a good choice, which is why
280 /// this lint is `Allow` by default.
282 /// `result.expect()` will let the thread panic on `Err`
283 /// values. Normally, you want to implement more sophisticated error handling,
284 /// and propagate errors upwards with `?` operator.
288 /// # let option = Some(1);
289 /// # let result: Result<usize, ()> = Ok(1);
290 /// option.expect("one");
291 /// result.expect("one");
296 /// # let option = Some(1);
297 /// # let result: Result<usize, ()> = Ok(1);
304 #[clippy::version = "1.45.0"]
307 "using `.expect()` on `Result` or `Option`, which might be better handled"
310 declare_clippy_lint! {
312 /// Checks for methods that should live in a trait
313 /// implementation of a `std` trait (see [llogiq's blog
314 /// post](http://llogiq.github.io/2015/07/30/traits.html) for further
315 /// information) instead of an inherent implementation.
317 /// ### Why is this bad?
318 /// Implementing the traits improve ergonomics for users of
319 /// the code, often with very little cost. Also people seeing a `mul(...)`
321 /// may expect `*` to work equally, so you should have good reason to disappoint
328 /// fn add(&self, other: &X) -> X {
334 #[clippy::version = "pre 1.29.0"]
335 pub SHOULD_IMPLEMENT_TRAIT,
337 "defining a method that should be implementing a std trait"
340 declare_clippy_lint! {
342 /// Checks for methods with certain name prefixes and which
343 /// doesn't match how self is taken. The actual rules are:
345 /// |Prefix |Postfix |`self` taken | `self` type |
346 /// |-------|------------|-------------------------------|--------------|
347 /// |`as_` | none |`&self` or `&mut self` | any |
348 /// |`from_`| none | none | any |
349 /// |`into_`| none |`self` | any |
350 /// |`is_` | none |`&mut self` or `&self` or none | any |
351 /// |`to_` | `_mut` |`&mut self` | any |
352 /// |`to_` | not `_mut` |`self` | `Copy` |
353 /// |`to_` | not `_mut` |`&self` | not `Copy` |
355 /// Note: Clippy doesn't trigger methods with `to_` prefix in:
356 /// - Traits definition.
357 /// Clippy can not tell if a type that implements a trait is `Copy` or not.
358 /// - Traits implementation, when `&self` is taken.
359 /// The method signature is controlled by the trait and often `&self` is required for all types that implement the trait
360 /// (see e.g. the `std::string::ToString` trait).
362 /// Clippy allows `Pin<&Self>` and `Pin<&mut Self>` if `&self` and `&mut self` is required.
364 /// Please find more info here:
365 /// https://rust-lang.github.io/api-guidelines/naming.html#ad-hoc-conversions-follow-as_-to_-into_-conventions-c-conv
367 /// ### Why is this bad?
368 /// Consistency breeds readability. If you follow the
369 /// conventions, your users won't be surprised that they, e.g., need to supply a
370 /// mutable reference to a `as_..` function.
376 /// fn as_str(self) -> &'static str {
382 #[clippy::version = "pre 1.29.0"]
383 pub WRONG_SELF_CONVENTION,
385 "defining a method named with an established prefix (like \"into_\") that takes `self` with the wrong convention"
388 declare_clippy_lint! {
390 /// Checks for usage of `ok().expect(..)`.
392 /// ### Why is this bad?
393 /// Because you usually call `expect()` on the `Result`
394 /// directly to get a better error message.
396 /// ### Known problems
397 /// The error type needs to implement `Debug`
401 /// # let x = Ok::<_, ()>(());
402 /// x.ok().expect("why did I do this again?");
407 /// # let x = Ok::<_, ()>(());
408 /// x.expect("why did I do this again?");
410 #[clippy::version = "pre 1.29.0"]
413 "using `ok().expect()`, which gives worse error messages than calling `expect` directly on the Result"
416 declare_clippy_lint! {
418 /// Checks for `.err().expect()` calls on the `Result` type.
420 /// ### Why is this bad?
421 /// `.expect_err()` can be called directly to avoid the extra type conversion from `err()`.
425 /// let x: Result<u32, &str> = Ok(10);
426 /// x.err().expect("Testing err().expect()");
430 /// let x: Result<u32, &str> = Ok(10);
431 /// x.expect_err("Testing expect_err");
433 #[clippy::version = "1.62.0"]
436 r#"using `.err().expect("")` when `.expect_err("")` can be used"#
439 declare_clippy_lint! {
441 /// Checks for usages of `_.unwrap_or_else(Default::default)` on `Option` and
444 /// ### Why is this bad?
445 /// Readability, these can be written as `_.unwrap_or_default`, which is
446 /// simpler and more concise.
450 /// # let x = Some(1);
451 /// x.unwrap_or_else(Default::default);
452 /// x.unwrap_or_else(u32::default);
457 /// # let x = Some(1);
458 /// x.unwrap_or_default();
460 #[clippy::version = "1.56.0"]
461 pub UNWRAP_OR_ELSE_DEFAULT,
463 "using `.unwrap_or_else(Default::default)`, which is more succinctly expressed as `.unwrap_or_default()`"
466 declare_clippy_lint! {
468 /// Checks for usage of `option.map(_).unwrap_or(_)` or `option.map(_).unwrap_or_else(_)` or
469 /// `result.map(_).unwrap_or_else(_)`.
471 /// ### Why is this bad?
472 /// Readability, these can be written more concisely (resp.) as
473 /// `option.map_or(_, _)`, `option.map_or_else(_, _)` and `result.map_or_else(_, _)`.
475 /// ### Known problems
476 /// The order of the arguments is not in execution order
480 /// # let option = Some(1);
481 /// # let result: Result<usize, ()> = Ok(1);
482 /// # fn some_function(foo: ()) -> usize { 1 }
483 /// option.map(|a| a + 1).unwrap_or(0);
484 /// result.map(|a| a + 1).unwrap_or_else(some_function);
489 /// # let option = Some(1);
490 /// # let result: Result<usize, ()> = Ok(1);
491 /// # fn some_function(foo: ()) -> usize { 1 }
492 /// option.map_or(0, |a| a + 1);
493 /// result.map_or_else(some_function, |a| a + 1);
495 #[clippy::version = "1.45.0"]
498 "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)`"
501 declare_clippy_lint! {
503 /// Checks for usage of `_.map_or(None, _)`.
505 /// ### Why is this bad?
506 /// Readability, this can be written more concisely as
509 /// ### Known problems
510 /// The order of the arguments is not in execution order.
514 /// # let opt = Some(1);
515 /// opt.map_or(None, |a| Some(a + 1));
520 /// # let opt = Some(1);
521 /// opt.and_then(|a| Some(a + 1));
523 #[clippy::version = "pre 1.29.0"]
524 pub OPTION_MAP_OR_NONE,
526 "using `Option.map_or(None, f)`, which is more succinctly expressed as `and_then(f)`"
529 declare_clippy_lint! {
531 /// Checks for usage of `_.map_or(None, Some)`.
533 /// ### Why is this bad?
534 /// Readability, this can be written more concisely as
539 /// # let r: Result<u32, &str> = Ok(1);
540 /// assert_eq!(Some(1), r.map_or(None, Some));
545 /// # let r: Result<u32, &str> = Ok(1);
546 /// assert_eq!(Some(1), r.ok());
548 #[clippy::version = "1.44.0"]
549 pub RESULT_MAP_OR_INTO_OPTION,
551 "using `Result.map_or(None, Some)`, which is more succinctly expressed as `ok()`"
554 declare_clippy_lint! {
556 /// Checks for usage of `_.and_then(|x| Some(y))`, `_.and_then(|x| Ok(y))` or
557 /// `_.or_else(|x| Err(y))`.
559 /// ### Why is this bad?
560 /// Readability, this can be written more concisely as
561 /// `_.map(|x| y)` or `_.map_err(|x| y)`.
565 /// # fn opt() -> Option<&'static str> { Some("42") }
566 /// # fn res() -> Result<&'static str, &'static str> { Ok("42") }
567 /// let _ = opt().and_then(|s| Some(s.len()));
568 /// let _ = res().and_then(|s| if s.len() == 42 { Ok(10) } else { Ok(20) });
569 /// let _ = res().or_else(|s| if s.len() == 42 { Err(10) } else { Err(20) });
572 /// The correct use would be:
575 /// # fn opt() -> Option<&'static str> { Some("42") }
576 /// # fn res() -> Result<&'static str, &'static str> { Ok("42") }
577 /// let _ = opt().map(|s| s.len());
578 /// let _ = res().map(|s| if s.len() == 42 { 10 } else { 20 });
579 /// let _ = res().map_err(|s| if s.len() == 42 { 10 } else { 20 });
581 #[clippy::version = "1.45.0"]
582 pub BIND_INSTEAD_OF_MAP,
584 "using `Option.and_then(|x| Some(y))`, which is more succinctly expressed as `map(|x| y)`"
587 declare_clippy_lint! {
589 /// Checks for usage of `_.filter(_).next()`.
591 /// ### Why is this bad?
592 /// Readability, this can be written more concisely as
597 /// # let vec = vec![1];
598 /// vec.iter().filter(|x| **x == 0).next();
603 /// # let vec = vec![1];
604 /// vec.iter().find(|x| **x == 0);
606 #[clippy::version = "pre 1.29.0"]
609 "using `filter(p).next()`, which is more succinctly expressed as `.find(p)`"
612 declare_clippy_lint! {
614 /// Checks for usage of `_.skip_while(condition).next()`.
616 /// ### Why is this bad?
617 /// Readability, this can be written more concisely as
618 /// `_.find(!condition)`.
622 /// # let vec = vec![1];
623 /// vec.iter().skip_while(|x| **x == 0).next();
628 /// # let vec = vec![1];
629 /// vec.iter().find(|x| **x != 0);
631 #[clippy::version = "1.42.0"]
634 "using `skip_while(p).next()`, which is more succinctly expressed as `.find(!p)`"
637 declare_clippy_lint! {
639 /// Checks for usage of `_.map(_).flatten(_)` on `Iterator` and `Option`
641 /// ### Why is this bad?
642 /// Readability, this can be written more concisely as
643 /// `_.flat_map(_)` for `Iterator` or `_.and_then(_)` for `Option`
647 /// let vec = vec![vec![1]];
648 /// let opt = Some(5);
650 /// vec.iter().map(|x| x.iter()).flatten();
651 /// opt.map(|x| Some(x * 2)).flatten();
656 /// # let vec = vec![vec![1]];
657 /// # let opt = Some(5);
658 /// vec.iter().flat_map(|x| x.iter());
659 /// opt.and_then(|x| Some(x * 2));
661 #[clippy::version = "1.31.0"]
664 "using combinations of `flatten` and `map` which can usually be written as a single method call"
667 declare_clippy_lint! {
669 /// Checks for usage of `_.filter(_).map(_)` that can be written more simply
670 /// as `filter_map(_)`.
672 /// ### Why is this bad?
673 /// Redundant code in the `filter` and `map` operations is poor style and
678 /// # #![allow(unused)]
680 /// .filter(|n| n.checked_add(1).is_some())
681 /// .map(|n| n.checked_add(1).unwrap());
686 /// # #[allow(unused)]
687 /// (0_i32..10).filter_map(|n| n.checked_add(1));
689 #[clippy::version = "1.51.0"]
690 pub MANUAL_FILTER_MAP,
692 "using `_.filter(_).map(_)` in a way that can be written more simply as `filter_map(_)`"
695 declare_clippy_lint! {
697 /// Checks for usage of `_.find(_).map(_)` that can be written more simply
698 /// as `find_map(_)`.
700 /// ### Why is this bad?
701 /// Redundant code in the `find` and `map` operations is poor style and
707 /// .find(|n| n.checked_add(1).is_some())
708 /// .map(|n| n.checked_add(1).unwrap());
713 /// (0_i32..10).find_map(|n| n.checked_add(1));
715 #[clippy::version = "1.51.0"]
718 "using `_.find(_).map(_)` in a way that can be written more simply as `find_map(_)`"
721 declare_clippy_lint! {
723 /// Checks for usage of `_.filter_map(_).next()`.
725 /// ### Why is this bad?
726 /// Readability, this can be written more concisely as
731 /// (0..3).filter_map(|x| if x == 2 { Some(x) } else { None }).next();
733 /// Can be written as
736 /// (0..3).find_map(|x| if x == 2 { Some(x) } else { None });
738 #[clippy::version = "1.36.0"]
741 "using combination of `filter_map` and `next` which can usually be written as a single method call"
744 declare_clippy_lint! {
746 /// Checks for usage of `flat_map(|x| x)`.
748 /// ### Why is this bad?
749 /// Readability, this can be written more concisely by using `flatten`.
753 /// # let iter = vec![vec![0]].into_iter();
754 /// iter.flat_map(|x| x);
756 /// Can be written as
758 /// # let iter = vec![vec![0]].into_iter();
761 #[clippy::version = "1.39.0"]
762 pub FLAT_MAP_IDENTITY,
764 "call to `flat_map` where `flatten` is sufficient"
767 declare_clippy_lint! {
769 /// Checks for an iterator or string search (such as `find()`,
770 /// `position()`, or `rposition()`) followed by a call to `is_some()` or `is_none()`.
772 /// ### Why is this bad?
773 /// Readability, this can be written more concisely as:
774 /// * `_.any(_)`, or `_.contains(_)` for `is_some()`,
775 /// * `!_.any(_)`, or `!_.contains(_)` for `is_none()`.
779 /// # #![allow(unused)]
780 /// let vec = vec![1];
781 /// vec.iter().find(|x| **x == 0).is_some();
783 /// "hello world".find("world").is_none();
788 /// let vec = vec![1];
789 /// vec.iter().any(|x| *x == 0);
791 /// # #[allow(unused)]
792 /// !"hello world".contains("world");
794 #[clippy::version = "pre 1.29.0"]
797 "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()`)"
800 declare_clippy_lint! {
802 /// Checks for usage of `.chars().next()` on a `str` to check
803 /// if it starts with a given char.
805 /// ### Why is this bad?
806 /// Readability, this can be written more concisely as
807 /// `_.starts_with(_)`.
811 /// let name = "foo";
812 /// if name.chars().next() == Some('_') {};
817 /// let name = "foo";
818 /// if name.starts_with('_') {};
820 #[clippy::version = "pre 1.29.0"]
823 "using `.chars().next()` to check if a string starts with a char"
826 declare_clippy_lint! {
828 /// Checks for calls to `.or(foo(..))`, `.unwrap_or(foo(..))`,
829 /// `.or_insert(foo(..))` etc., and suggests to use `.or_else(|| foo(..))`,
830 /// `.unwrap_or_else(|| foo(..))`, `.unwrap_or_default()` or `.or_default()`
833 /// ### Why is this bad?
834 /// The function will always be called and potentially
835 /// allocate an object acting as the default.
837 /// ### Known problems
838 /// If the function has side-effects, not calling it will
839 /// change the semantic of the program, but you shouldn't rely on that anyway.
843 /// # let foo = Some(String::new());
844 /// foo.unwrap_or(String::new());
849 /// # let foo = Some(String::new());
850 /// foo.unwrap_or_else(String::new);
854 /// # let foo = Some(String::new());
855 /// foo.unwrap_or_default();
857 #[clippy::version = "pre 1.29.0"]
860 "using any `*or` method with a function call, which suggests `*or_else`"
863 declare_clippy_lint! {
865 /// Checks for `.or(…).unwrap()` calls to Options and Results.
867 /// ### Why is this bad?
868 /// You should use `.unwrap_or(…)` instead for clarity.
872 /// # let fallback = "fallback";
874 /// # type Error = &'static str;
875 /// # let result: Result<&str, Error> = Err("error");
876 /// let value = result.or::<Error>(Ok(fallback)).unwrap();
879 /// # let option: Option<&str> = None;
880 /// let value = option.or(Some(fallback)).unwrap();
884 /// # let fallback = "fallback";
886 /// # let result: Result<&str, &str> = Err("error");
887 /// let value = result.unwrap_or(fallback);
890 /// # let option: Option<&str> = None;
891 /// let value = option.unwrap_or(fallback);
893 #[clippy::version = "1.61.0"]
896 "checks for `.or(…).unwrap()` calls to Options and Results."
899 declare_clippy_lint! {
901 /// Checks for calls to `.expect(&format!(...))`, `.expect(foo(..))`,
902 /// etc., and suggests to use `unwrap_or_else` instead
904 /// ### Why is this bad?
905 /// The function will always be called.
907 /// ### Known problems
908 /// If the function has side-effects, not calling it will
909 /// change the semantics of the program, but you shouldn't rely on that anyway.
913 /// # let foo = Some(String::new());
914 /// # let err_code = "418";
915 /// # let err_msg = "I'm a teapot";
916 /// foo.expect(&format!("Err {}: {}", err_code, err_msg));
920 /// # let foo = Some(String::new());
921 /// foo.expect(format!("Err {}: {}", err_code, err_msg).as_str());
926 /// # let foo = Some(String::new());
927 /// # let err_code = "418";
928 /// # let err_msg = "I'm a teapot";
929 /// foo.unwrap_or_else(|| panic!("Err {}: {}", err_code, err_msg));
931 #[clippy::version = "pre 1.29.0"]
934 "using any `expect` method with a function call"
937 declare_clippy_lint! {
939 /// Checks for usage of `.clone()` on a `Copy` type.
941 /// ### Why is this bad?
942 /// The only reason `Copy` types implement `Clone` is for
943 /// generics, not for using the `clone` method on a concrete type.
949 #[clippy::version = "pre 1.29.0"]
952 "using `clone` on a `Copy` type"
955 declare_clippy_lint! {
957 /// Checks for usage of `.clone()` on a ref-counted pointer,
958 /// (`Rc`, `Arc`, `rc::Weak`, or `sync::Weak`), and suggests calling Clone via unified
959 /// function syntax instead (e.g., `Rc::clone(foo)`).
961 /// ### Why is this bad?
962 /// Calling '.clone()' on an Rc, Arc, or Weak
963 /// can obscure the fact that only the pointer is being cloned, not the underlying
968 /// # use std::rc::Rc;
969 /// let x = Rc::new(1);
976 /// # use std::rc::Rc;
977 /// # let x = Rc::new(1);
980 #[clippy::version = "pre 1.29.0"]
981 pub CLONE_ON_REF_PTR,
983 "using 'clone' on a ref-counted pointer"
986 declare_clippy_lint! {
988 /// Checks for usage of `.clone()` on an `&&T`.
990 /// ### Why is this bad?
991 /// Cloning an `&&T` copies the inner `&T`, instead of
992 /// cloning the underlying `T`.
999 /// let z = y.clone();
1000 /// println!("{:p} {:p}", *y, z); // prints out the same pointer
1003 #[clippy::version = "pre 1.29.0"]
1004 pub CLONE_DOUBLE_REF,
1006 "using `clone` on `&&T`"
1009 declare_clippy_lint! {
1010 /// ### What it does
1011 /// Checks for usage of `.to_string()` on an `&&T` where
1012 /// `T` implements `ToString` directly (like `&&str` or `&&String`).
1014 /// ### Why is this bad?
1015 /// This bypasses the specialized implementation of
1016 /// `ToString` and instead goes through the more expensive string formatting
1021 /// // Generic implementation for `T: Display` is used (slow)
1022 /// ["foo", "bar"].iter().map(|s| s.to_string());
1024 /// // OK, the specialized impl is used
1025 /// ["foo", "bar"].iter().map(|&s| s.to_string());
1027 #[clippy::version = "1.40.0"]
1028 pub INEFFICIENT_TO_STRING,
1030 "using `to_string` on `&&T` where `T: ToString`"
1033 declare_clippy_lint! {
1034 /// ### What it does
1035 /// Checks for `new` not returning a type that contains `Self`.
1037 /// ### Why is this bad?
1038 /// As a convention, `new` methods are used to make a new
1039 /// instance of a type.
1042 /// In an impl block:
1045 /// # struct NotAFoo;
1047 /// fn new() -> NotAFoo {
1055 /// struct Bar(Foo);
1057 /// // Bad. The type name must contain `Self`
1058 /// fn new() -> Bar {
1066 /// # struct FooError;
1068 /// // Good. Return type contains `Self`
1069 /// fn new() -> Result<Foo, FooError> {
1075 /// Or in a trait definition:
1077 /// pub trait Trait {
1078 /// // Bad. The type name must contain `Self`
1084 /// pub trait Trait {
1085 /// // Good. Return type contains `Self`
1086 /// fn new() -> Self;
1089 #[clippy::version = "pre 1.29.0"]
1090 pub NEW_RET_NO_SELF,
1092 "not returning type containing `Self` in a `new` method"
1095 declare_clippy_lint! {
1096 /// ### What it does
1097 /// Checks for string methods that receive a single-character
1098 /// `str` as an argument, e.g., `_.split("x")`.
1100 /// ### Why is this bad?
1101 /// Performing these methods using a `char` is faster than
1104 /// ### Known problems
1105 /// Does not catch multi-byte unicode characters.
1116 #[clippy::version = "pre 1.29.0"]
1117 pub SINGLE_CHAR_PATTERN,
1119 "using a single-character str where a char could be used, e.g., `_.split(\"x\")`"
1122 declare_clippy_lint! {
1123 /// ### What it does
1124 /// Checks for calling `.step_by(0)` on iterators which panics.
1126 /// ### Why is this bad?
1127 /// This very much looks like an oversight. Use `panic!()` instead if you
1128 /// actually intend to panic.
1131 /// ```rust,should_panic
1132 /// for x in (0..100).step_by(0) {
1136 #[clippy::version = "pre 1.29.0"]
1137 pub ITERATOR_STEP_BY_ZERO,
1139 "using `Iterator::step_by(0)`, which will panic at runtime"
1142 declare_clippy_lint! {
1143 /// ### What it does
1144 /// Checks for indirect collection of populated `Option`
1146 /// ### Why is this bad?
1147 /// `Option` is like a collection of 0-1 things, so `flatten`
1148 /// automatically does this without suspicious-looking `unwrap` calls.
1152 /// let _ = std::iter::empty::<Option<i32>>().filter(Option::is_some).map(Option::unwrap);
1156 /// let _ = std::iter::empty::<Option<i32>>().flatten();
1158 #[clippy::version = "1.53.0"]
1159 pub OPTION_FILTER_MAP,
1161 "filtering `Option` for `Some` then force-unwrapping, which can be one type-safe operation"
1164 declare_clippy_lint! {
1165 /// ### What it does
1166 /// Checks for the use of `iter.nth(0)`.
1168 /// ### Why is this bad?
1169 /// `iter.next()` is equivalent to
1170 /// `iter.nth(0)`, as they both consume the next element,
1171 /// but is more readable.
1175 /// # use std::collections::HashSet;
1176 /// # let mut s = HashSet::new();
1178 /// let x = s.iter().nth(0);
1183 /// # use std::collections::HashSet;
1184 /// # let mut s = HashSet::new();
1186 /// let x = s.iter().next();
1188 #[clippy::version = "1.42.0"]
1191 "replace `iter.nth(0)` with `iter.next()`"
1194 declare_clippy_lint! {
1195 /// ### What it does
1196 /// Checks for use of `.iter().nth()` (and the related
1197 /// `.iter_mut().nth()`) on standard library types with *O*(1) element access.
1199 /// ### Why is this bad?
1200 /// `.get()` and `.get_mut()` are more efficient and more
1205 /// let some_vec = vec![0, 1, 2, 3];
1206 /// let bad_vec = some_vec.iter().nth(3);
1207 /// let bad_slice = &some_vec[..].iter().nth(3);
1209 /// The correct use would be:
1211 /// let some_vec = vec![0, 1, 2, 3];
1212 /// let bad_vec = some_vec.get(3);
1213 /// let bad_slice = &some_vec[..].get(3);
1215 #[clippy::version = "pre 1.29.0"]
1218 "using `.iter().nth()` on a standard library type with O(1) element access"
1221 declare_clippy_lint! {
1222 /// ### What it does
1223 /// Checks for use of `.skip(x).next()` on iterators.
1225 /// ### Why is this bad?
1226 /// `.nth(x)` is cleaner
1230 /// let some_vec = vec![0, 1, 2, 3];
1231 /// let bad_vec = some_vec.iter().skip(3).next();
1232 /// let bad_slice = &some_vec[..].iter().skip(3).next();
1234 /// The correct use would be:
1236 /// let some_vec = vec![0, 1, 2, 3];
1237 /// let bad_vec = some_vec.iter().nth(3);
1238 /// let bad_slice = &some_vec[..].iter().nth(3);
1240 #[clippy::version = "pre 1.29.0"]
1243 "using `.skip(x).next()` on an iterator"
1246 declare_clippy_lint! {
1247 /// ### What it does
1248 /// Checks for use of `.drain(..)` on `Vec` and `VecDeque` for iteration.
1250 /// ### Why is this bad?
1251 /// `.into_iter()` is simpler with better performance.
1255 /// # use std::collections::HashSet;
1256 /// let mut foo = vec![0, 1, 2, 3];
1257 /// let bar: HashSet<usize> = foo.drain(..).collect();
1261 /// # use std::collections::HashSet;
1262 /// let foo = vec![0, 1, 2, 3];
1263 /// let bar: HashSet<usize> = foo.into_iter().collect();
1265 #[clippy::version = "1.61.0"]
1266 pub ITER_WITH_DRAIN,
1268 "replace `.drain(..)` with `.into_iter()`"
1271 declare_clippy_lint! {
1272 /// ### What it does
1273 /// Checks for using `x.get(x.len() - 1)` instead of
1276 /// ### Why is this bad?
1277 /// Using `x.last()` is easier to read and has the same
1280 /// Note that using `x[x.len() - 1]` is semantically different from
1281 /// `x.last()`. Indexing into the array will panic on out-of-bounds
1282 /// accesses, while `x.get()` and `x.last()` will return `None`.
1284 /// There is another lint (get_unwrap) that covers the case of using
1285 /// `x.get(index).unwrap()` instead of `x[index]`.
1289 /// let x = vec![2, 3, 5];
1290 /// let last_element = x.get(x.len() - 1);
1295 /// let x = vec![2, 3, 5];
1296 /// let last_element = x.last();
1298 #[clippy::version = "1.37.0"]
1299 pub GET_LAST_WITH_LEN,
1301 "Using `x.get(x.len() - 1)` when `x.last()` is correct and simpler"
1304 declare_clippy_lint! {
1305 /// ### What it does
1306 /// Checks for use of `.get().unwrap()` (or
1307 /// `.get_mut().unwrap`) on a standard library type which implements `Index`
1309 /// ### Why is this bad?
1310 /// Using the Index trait (`[]`) is more clear and more
1313 /// ### Known problems
1314 /// Not a replacement for error handling: Using either
1315 /// `.unwrap()` or the Index trait (`[]`) carries the risk of causing a `panic`
1316 /// if the value being accessed is `None`. If the use of `.get().unwrap()` is a
1317 /// temporary placeholder for dealing with the `Option` type, then this does
1318 /// not mitigate the need for error handling. If there is a chance that `.get()`
1319 /// will be `None` in your program, then it is advisable that the `None` case
1320 /// is handled in a future refactor instead of using `.unwrap()` or the Index
1325 /// let mut some_vec = vec![0, 1, 2, 3];
1326 /// let last = some_vec.get(3).unwrap();
1327 /// *some_vec.get_mut(0).unwrap() = 1;
1329 /// The correct use would be:
1331 /// let mut some_vec = vec![0, 1, 2, 3];
1332 /// let last = some_vec[3];
1333 /// some_vec[0] = 1;
1335 #[clippy::version = "pre 1.29.0"]
1338 "using `.get().unwrap()` or `.get_mut().unwrap()` when using `[]` would work instead"
1341 declare_clippy_lint! {
1342 /// ### What it does
1343 /// Checks for occurrences where one vector gets extended instead of append
1345 /// ### Why is this bad?
1346 /// Using `append` instead of `extend` is more concise and faster
1350 /// let mut a = vec![1, 2, 3];
1351 /// let mut b = vec![4, 5, 6];
1353 /// a.extend(b.drain(..));
1358 /// let mut a = vec![1, 2, 3];
1359 /// let mut b = vec![4, 5, 6];
1361 /// a.append(&mut b);
1363 #[clippy::version = "1.55.0"]
1364 pub EXTEND_WITH_DRAIN,
1366 "using vec.append(&mut vec) to move the full range of a vector to another"
1369 declare_clippy_lint! {
1370 /// ### What it does
1371 /// Checks for the use of `.extend(s.chars())` where s is a
1372 /// `&str` or `String`.
1374 /// ### Why is this bad?
1375 /// `.push_str(s)` is clearer
1379 /// let abc = "abc";
1380 /// let def = String::from("def");
1381 /// let mut s = String::new();
1382 /// s.extend(abc.chars());
1383 /// s.extend(def.chars());
1385 /// The correct use would be:
1387 /// let abc = "abc";
1388 /// let def = String::from("def");
1389 /// let mut s = String::new();
1390 /// s.push_str(abc);
1391 /// s.push_str(&def);
1393 #[clippy::version = "pre 1.29.0"]
1394 pub STRING_EXTEND_CHARS,
1396 "using `x.extend(s.chars())` where s is a `&str` or `String`"
1399 declare_clippy_lint! {
1400 /// ### What it does
1401 /// Checks for the use of `.cloned().collect()` on slice to
1404 /// ### Why is this bad?
1405 /// `.to_vec()` is clearer
1409 /// let s = [1, 2, 3, 4, 5];
1410 /// let s2: Vec<isize> = s[..].iter().cloned().collect();
1412 /// The better use would be:
1414 /// let s = [1, 2, 3, 4, 5];
1415 /// let s2: Vec<isize> = s.to_vec();
1417 #[clippy::version = "pre 1.29.0"]
1418 pub ITER_CLONED_COLLECT,
1420 "using `.cloned().collect()` on slice to create a `Vec`"
1423 declare_clippy_lint! {
1424 /// ### What it does
1425 /// Checks for usage of `_.chars().last()` or
1426 /// `_.chars().next_back()` on a `str` to check if it ends with a given char.
1428 /// ### Why is this bad?
1429 /// Readability, this can be written more concisely as
1430 /// `_.ends_with(_)`.
1434 /// # let name = "_";
1435 /// name.chars().last() == Some('_') || name.chars().next_back() == Some('-');
1440 /// # let name = "_";
1441 /// name.ends_with('_') || name.ends_with('-');
1443 #[clippy::version = "pre 1.29.0"]
1446 "using `.chars().last()` or `.chars().next_back()` to check if a string ends with a char"
1449 declare_clippy_lint! {
1450 /// ### What it does
1451 /// Checks for usage of `.as_ref()` or `.as_mut()` where the
1452 /// types before and after the call are the same.
1454 /// ### Why is this bad?
1455 /// The call is unnecessary.
1459 /// # fn do_stuff(x: &[i32]) {}
1460 /// let x: &[i32] = &[1, 2, 3, 4, 5];
1461 /// do_stuff(x.as_ref());
1463 /// The correct use would be:
1465 /// # fn do_stuff(x: &[i32]) {}
1466 /// let x: &[i32] = &[1, 2, 3, 4, 5];
1469 #[clippy::version = "pre 1.29.0"]
1472 "using `as_ref` where the types before and after the call are the same"
1475 declare_clippy_lint! {
1476 /// ### What it does
1477 /// Checks for using `fold` when a more succinct alternative exists.
1478 /// Specifically, this checks for `fold`s which could be replaced by `any`, `all`,
1479 /// `sum` or `product`.
1481 /// ### Why is this bad?
1486 /// # #[allow(unused)]
1487 /// (0..3).fold(false, |acc, x| acc || x > 2);
1492 /// (0..3).any(|x| x > 2);
1494 #[clippy::version = "pre 1.29.0"]
1495 pub UNNECESSARY_FOLD,
1497 "using `fold` when a more succinct alternative exists"
1500 declare_clippy_lint! {
1501 /// ### What it does
1502 /// Checks for `filter_map` calls that could be replaced by `filter` or `map`.
1503 /// More specifically it checks if the closure provided is only performing one of the
1504 /// filter or map operations and suggests the appropriate option.
1506 /// ### Why is this bad?
1507 /// Complexity. The intent is also clearer if only a single
1508 /// operation is being performed.
1512 /// let _ = (0..3).filter_map(|x| if x > 2 { Some(x) } else { None });
1514 /// // As there is no transformation of the argument this could be written as:
1515 /// let _ = (0..3).filter(|&x| x > 2);
1519 /// let _ = (0..4).filter_map(|x| Some(x + 1));
1521 /// // As there is no conditional check on the argument this could be written as:
1522 /// let _ = (0..4).map(|x| x + 1);
1524 #[clippy::version = "1.31.0"]
1525 pub UNNECESSARY_FILTER_MAP,
1527 "using `filter_map` when a more succinct alternative exists"
1530 declare_clippy_lint! {
1531 /// ### What it does
1532 /// Checks for `find_map` calls that could be replaced by `find` or `map`. More
1533 /// specifically it checks if the closure provided is only performing one of the
1534 /// find or map operations and suggests the appropriate option.
1536 /// ### Why is this bad?
1537 /// Complexity. The intent is also clearer if only a single
1538 /// operation is being performed.
1542 /// let _ = (0..3).find_map(|x| if x > 2 { Some(x) } else { None });
1544 /// // As there is no transformation of the argument this could be written as:
1545 /// let _ = (0..3).find(|&x| x > 2);
1549 /// let _ = (0..4).find_map(|x| Some(x + 1));
1551 /// // As there is no conditional check on the argument this could be written as:
1552 /// let _ = (0..4).map(|x| x + 1).next();
1554 #[clippy::version = "1.61.0"]
1555 pub UNNECESSARY_FIND_MAP,
1557 "using `find_map` when a more succinct alternative exists"
1560 declare_clippy_lint! {
1561 /// ### What it does
1562 /// Checks for `into_iter` calls on references which should be replaced by `iter`
1565 /// ### Why is this bad?
1566 /// Readability. Calling `into_iter` on a reference will not move out its
1567 /// content into the resulting iterator, which is confusing. It is better just call `iter` or
1568 /// `iter_mut` directly.
1572 /// # let vec = vec![3, 4, 5];
1573 /// (&vec).into_iter();
1578 /// # let vec = vec![3, 4, 5];
1581 #[clippy::version = "1.32.0"]
1582 pub INTO_ITER_ON_REF,
1584 "using `.into_iter()` on a reference"
1587 declare_clippy_lint! {
1588 /// ### What it does
1589 /// Checks for calls to `map` followed by a `count`.
1591 /// ### Why is this bad?
1592 /// It looks suspicious. Maybe `map` was confused with `filter`.
1593 /// If the `map` call is intentional, this should be rewritten
1594 /// using `inspect`. Or, if you intend to drive the iterator to
1595 /// completion, you can just use `for_each` instead.
1599 /// let _ = (0..3).map(|x| x + 2).count();
1601 #[clippy::version = "1.39.0"]
1604 "suspicious usage of map"
1607 declare_clippy_lint! {
1608 /// ### What it does
1609 /// Checks for `MaybeUninit::uninit().assume_init()`.
1611 /// ### Why is this bad?
1612 /// For most types, this is undefined behavior.
1614 /// ### Known problems
1615 /// For now, we accept empty tuples and tuples / arrays
1616 /// of `MaybeUninit`. There may be other types that allow uninitialized
1617 /// data, but those are not yet rigorously defined.
1621 /// // Beware the UB
1622 /// use std::mem::MaybeUninit;
1624 /// let _: usize = unsafe { MaybeUninit::uninit().assume_init() };
1627 /// Note that the following is OK:
1630 /// use std::mem::MaybeUninit;
1632 /// let _: [MaybeUninit<bool>; 5] = unsafe {
1633 /// MaybeUninit::uninit().assume_init()
1636 #[clippy::version = "1.39.0"]
1637 pub UNINIT_ASSUMED_INIT,
1639 "`MaybeUninit::uninit().assume_init()`"
1642 declare_clippy_lint! {
1643 /// ### What it does
1644 /// Checks for `.checked_add/sub(x).unwrap_or(MAX/MIN)`.
1646 /// ### Why is this bad?
1647 /// These can be written simply with `saturating_add/sub` methods.
1651 /// # let y: u32 = 0;
1652 /// # let x: u32 = 100;
1653 /// let add = x.checked_add(y).unwrap_or(u32::MAX);
1654 /// let sub = x.checked_sub(y).unwrap_or(u32::MIN);
1657 /// can be written using dedicated methods for saturating addition/subtraction as:
1660 /// # let y: u32 = 0;
1661 /// # let x: u32 = 100;
1662 /// let add = x.saturating_add(y);
1663 /// let sub = x.saturating_sub(y);
1665 #[clippy::version = "1.39.0"]
1666 pub MANUAL_SATURATING_ARITHMETIC,
1668 "`.checked_add/sub(x).unwrap_or(MAX/MIN)`"
1671 declare_clippy_lint! {
1672 /// ### What it does
1673 /// Checks for `offset(_)`, `wrapping_`{`add`, `sub`}, etc. on raw pointers to
1674 /// zero-sized types
1676 /// ### Why is this bad?
1677 /// This is a no-op, and likely unintended
1681 /// unsafe { (&() as *const ()).offset(1) };
1683 #[clippy::version = "1.41.0"]
1686 "Check for offset calculations on raw pointers to zero-sized types"
1689 declare_clippy_lint! {
1690 /// ### What it does
1691 /// Checks for `FileType::is_file()`.
1693 /// ### Why is this bad?
1694 /// When people testing a file type with `FileType::is_file`
1695 /// they are testing whether a path is something they can get bytes from. But
1696 /// `is_file` doesn't cover special file types in unix-like systems, and doesn't cover
1697 /// symlink in windows. Using `!FileType::is_dir()` is a better way to that intention.
1702 /// let metadata = std::fs::metadata("foo.txt")?;
1703 /// let filetype = metadata.file_type();
1705 /// if filetype.is_file() {
1708 /// # Ok::<_, std::io::Error>(())
1712 /// should be written as:
1716 /// let metadata = std::fs::metadata("foo.txt")?;
1717 /// let filetype = metadata.file_type();
1719 /// if !filetype.is_dir() {
1722 /// # Ok::<_, std::io::Error>(())
1725 #[clippy::version = "1.42.0"]
1726 pub FILETYPE_IS_FILE,
1728 "`FileType::is_file` is not recommended to test for readable file type"
1731 declare_clippy_lint! {
1732 /// ### What it does
1733 /// Checks for usage of `_.as_ref().map(Deref::deref)` or it's aliases (such as String::as_str).
1735 /// ### Why is this bad?
1736 /// Readability, this can be written more concisely as
1741 /// # let opt = Some("".to_string());
1742 /// opt.as_ref().map(String::as_str)
1745 /// Can be written as
1747 /// # let opt = Some("".to_string());
1751 #[clippy::version = "1.42.0"]
1752 pub OPTION_AS_REF_DEREF,
1754 "using `as_ref().map(Deref::deref)`, which is more succinctly expressed as `as_deref()`"
1757 declare_clippy_lint! {
1758 /// ### What it does
1759 /// Checks for usage of `iter().next()` on a Slice or an Array
1761 /// ### Why is this bad?
1762 /// These can be shortened into `.get()`
1766 /// # let a = [1, 2, 3];
1767 /// # let b = vec![1, 2, 3];
1768 /// a[2..].iter().next();
1769 /// b.iter().next();
1771 /// should be written as:
1773 /// # let a = [1, 2, 3];
1774 /// # let b = vec![1, 2, 3];
1778 #[clippy::version = "1.46.0"]
1779 pub ITER_NEXT_SLICE,
1781 "using `.iter().next()` on a sliced array, which can be shortened to just `.get()`"
1784 declare_clippy_lint! {
1785 /// ### What it does
1786 /// Warns when using `push_str`/`insert_str` with a single-character string literal
1787 /// where `push`/`insert` with a `char` would work fine.
1789 /// ### Why is this bad?
1790 /// It's less clear that we are pushing a single character.
1794 /// # let mut string = String::new();
1795 /// string.insert_str(0, "R");
1796 /// string.push_str("R");
1801 /// # let mut string = String::new();
1802 /// string.insert(0, 'R');
1803 /// string.push('R');
1805 #[clippy::version = "1.49.0"]
1806 pub SINGLE_CHAR_ADD_STR,
1808 "`push_str()` or `insert_str()` used with a single-character string literal as parameter"
1811 declare_clippy_lint! {
1812 /// ### What it does
1813 /// As the counterpart to `or_fun_call`, this lint looks for unnecessary
1814 /// lazily evaluated closures on `Option` and `Result`.
1816 /// This lint suggests changing the following functions, when eager evaluation results in
1818 /// - `unwrap_or_else` to `unwrap_or`
1819 /// - `and_then` to `and`
1820 /// - `or_else` to `or`
1821 /// - `get_or_insert_with` to `get_or_insert`
1822 /// - `ok_or_else` to `ok_or`
1824 /// ### Why is this bad?
1825 /// Using eager evaluation is shorter and simpler in some cases.
1827 /// ### Known problems
1828 /// It is possible, but not recommended for `Deref` and `Index` to have
1829 /// side effects. Eagerly evaluating them can change the semantics of the program.
1833 /// // example code where clippy issues a warning
1834 /// let opt: Option<u32> = None;
1836 /// opt.unwrap_or_else(|| 42);
1840 /// let opt: Option<u32> = None;
1842 /// opt.unwrap_or(42);
1844 #[clippy::version = "1.48.0"]
1845 pub UNNECESSARY_LAZY_EVALUATIONS,
1847 "using unnecessary lazy evaluation, which can be replaced with simpler eager evaluation"
1850 declare_clippy_lint! {
1851 /// ### What it does
1852 /// Checks for usage of `_.map(_).collect::<Result<(), _>()`.
1854 /// ### Why is this bad?
1855 /// Using `try_for_each` instead is more readable and idiomatic.
1859 /// (0..3).map(|t| Err(t)).collect::<Result<(), _>>();
1863 /// (0..3).try_for_each(|t| Err(t));
1865 #[clippy::version = "1.49.0"]
1866 pub MAP_COLLECT_RESULT_UNIT,
1868 "using `.map(_).collect::<Result<(),_>()`, which can be replaced with `try_for_each`"
1871 declare_clippy_lint! {
1872 /// ### What it does
1873 /// Checks for `from_iter()` function calls on types that implement the `FromIterator`
1876 /// ### Why is this bad?
1877 /// It is recommended style to use collect. See
1878 /// [FromIterator documentation](https://doc.rust-lang.org/std/iter/trait.FromIterator.html)
1882 /// let five_fives = std::iter::repeat(5).take(5);
1884 /// let v = Vec::from_iter(five_fives);
1886 /// assert_eq!(v, vec![5, 5, 5, 5, 5]);
1890 /// let five_fives = std::iter::repeat(5).take(5);
1892 /// let v: Vec<i32> = five_fives.collect();
1894 /// assert_eq!(v, vec![5, 5, 5, 5, 5]);
1896 #[clippy::version = "1.49.0"]
1897 pub FROM_ITER_INSTEAD_OF_COLLECT,
1899 "use `.collect()` instead of `::from_iter()`"
1902 declare_clippy_lint! {
1903 /// ### What it does
1904 /// Checks for usage of `inspect().for_each()`.
1906 /// ### Why is this bad?
1907 /// It is the same as performing the computation
1908 /// inside `inspect` at the beginning of the closure in `for_each`.
1912 /// [1,2,3,4,5].iter()
1913 /// .inspect(|&x| println!("inspect the number: {}", x))
1914 /// .for_each(|&x| {
1915 /// assert!(x >= 0);
1918 /// Can be written as
1920 /// [1,2,3,4,5].iter()
1921 /// .for_each(|&x| {
1922 /// println!("inspect the number: {}", x);
1923 /// assert!(x >= 0);
1926 #[clippy::version = "1.51.0"]
1927 pub INSPECT_FOR_EACH,
1929 "using `.inspect().for_each()`, which can be replaced with `.for_each()`"
1932 declare_clippy_lint! {
1933 /// ### What it does
1934 /// Checks for usage of `filter_map(|x| x)`.
1936 /// ### Why is this bad?
1937 /// Readability, this can be written more concisely by using `flatten`.
1941 /// # let iter = vec![Some(1)].into_iter();
1942 /// iter.filter_map(|x| x);
1946 /// # let iter = vec![Some(1)].into_iter();
1949 #[clippy::version = "1.52.0"]
1950 pub FILTER_MAP_IDENTITY,
1952 "call to `filter_map` where `flatten` is sufficient"
1955 declare_clippy_lint! {
1956 /// ### What it does
1957 /// Checks for instances of `map(f)` where `f` is the identity function.
1959 /// ### Why is this bad?
1960 /// It can be written more concisely without the call to `map`.
1964 /// let x = [1, 2, 3];
1965 /// let y: Vec<_> = x.iter().map(|x| x).map(|x| 2*x).collect();
1969 /// let x = [1, 2, 3];
1970 /// let y: Vec<_> = x.iter().map(|x| 2*x).collect();
1972 #[clippy::version = "1.47.0"]
1975 "using iterator.map(|x| x)"
1978 declare_clippy_lint! {
1979 /// ### What it does
1980 /// Checks for the use of `.bytes().nth()`.
1982 /// ### Why is this bad?
1983 /// `.as_bytes().get()` is more efficient and more
1988 /// # #[allow(unused)]
1989 /// "Hello".bytes().nth(3);
1994 /// # #[allow(unused)]
1995 /// "Hello".as_bytes().get(3);
1997 #[clippy::version = "1.52.0"]
2000 "replace `.bytes().nth()` with `.as_bytes().get()`"
2003 declare_clippy_lint! {
2004 /// ### What it does
2005 /// Checks for the usage of `_.to_owned()`, `vec.to_vec()`, or similar when calling `_.clone()` would be clearer.
2007 /// ### Why is this bad?
2008 /// These methods do the same thing as `_.clone()` but may be confusing as
2009 /// to why we are calling `to_vec` on something that is already a `Vec` or calling `to_owned` on something that is already owned.
2013 /// let a = vec![1, 2, 3];
2014 /// let b = a.to_vec();
2015 /// let c = a.to_owned();
2019 /// let a = vec![1, 2, 3];
2020 /// let b = a.clone();
2021 /// let c = a.clone();
2023 #[clippy::version = "1.52.0"]
2026 "implicitly cloning a value by invoking a function on its dereferenced type"
2029 declare_clippy_lint! {
2030 /// ### What it does
2031 /// Checks for the use of `.iter().count()`.
2033 /// ### Why is this bad?
2034 /// `.len()` is more efficient and more
2039 /// # #![allow(unused)]
2040 /// let some_vec = vec![0, 1, 2, 3];
2042 /// some_vec.iter().count();
2043 /// &some_vec[..].iter().count();
2048 /// let some_vec = vec![0, 1, 2, 3];
2051 /// &some_vec[..].len();
2053 #[clippy::version = "1.52.0"]
2056 "replace `.iter().count()` with `.len()`"
2059 declare_clippy_lint! {
2060 /// ### What it does
2061 /// Checks for the usage of `_.to_owned()`, on a `Cow<'_, _>`.
2063 /// ### Why is this bad?
2064 /// Calling `to_owned()` on a `Cow` creates a clone of the `Cow`
2065 /// itself, without taking ownership of the `Cow` contents (i.e.
2066 /// it's equivalent to calling `Cow::clone`).
2067 /// The similarly named `into_owned` method, on the other hand,
2068 /// clones the `Cow` contents, effectively turning any `Cow::Borrowed`
2069 /// into a `Cow::Owned`.
2071 /// Given the potential ambiguity, consider replacing `to_owned`
2072 /// with `clone` for better readability or, if getting a `Cow::Owned`
2073 /// was the original intent, using `into_owned` instead.
2077 /// # use std::borrow::Cow;
2078 /// let s = "Hello world!";
2079 /// let cow = Cow::Borrowed(s);
2081 /// let data = cow.to_owned();
2082 /// assert!(matches!(data, Cow::Borrowed(_)))
2086 /// # use std::borrow::Cow;
2087 /// let s = "Hello world!";
2088 /// let cow = Cow::Borrowed(s);
2090 /// let data = cow.clone();
2091 /// assert!(matches!(data, Cow::Borrowed(_)))
2095 /// # use std::borrow::Cow;
2096 /// let s = "Hello world!";
2097 /// let cow = Cow::Borrowed(s);
2099 /// let data = cow.into_owned();
2100 /// assert!(matches!(data, String))
2102 #[clippy::version = "1.65.0"]
2103 pub SUSPICIOUS_TO_OWNED,
2105 "calls to `to_owned` on a `Cow<'_, _>` might not do what they are expected"
2108 declare_clippy_lint! {
2109 /// ### What it does
2110 /// Checks for calls to [`splitn`]
2111 /// (https://doc.rust-lang.org/std/primitive.str.html#method.splitn) and
2112 /// related functions with either zero or one splits.
2114 /// ### Why is this bad?
2115 /// These calls don't actually split the value and are
2116 /// likely to be intended as a different number.
2121 /// for x in s.splitn(1, ":") {
2129 /// for x in s.splitn(2, ":") {
2133 #[clippy::version = "1.54.0"]
2134 pub SUSPICIOUS_SPLITN,
2136 "checks for `.splitn(0, ..)` and `.splitn(1, ..)`"
2139 declare_clippy_lint! {
2140 /// ### What it does
2141 /// Checks for manual implementations of `str::repeat`
2143 /// ### Why is this bad?
2144 /// These are both harder to read, as well as less performant.
2148 /// let x: String = std::iter::repeat('x').take(10).collect();
2153 /// let x: String = "x".repeat(10);
2155 #[clippy::version = "1.54.0"]
2156 pub MANUAL_STR_REPEAT,
2158 "manual implementation of `str::repeat`"
2161 declare_clippy_lint! {
2162 /// ### What it does
2163 /// Checks for usages of `str::splitn(2, _)`
2165 /// ### Why is this bad?
2166 /// `split_once` is both clearer in intent and slightly more efficient.
2170 /// let s = "key=value=add";
2171 /// let (key, value) = s.splitn(2, '=').next_tuple()?;
2172 /// let value = s.splitn(2, '=').nth(1)?;
2174 /// let mut parts = s.splitn(2, '=');
2175 /// let key = parts.next()?;
2176 /// let value = parts.next()?;
2181 /// let s = "key=value=add";
2182 /// let (key, value) = s.split_once('=')?;
2183 /// let value = s.split_once('=')?.1;
2185 /// let (key, value) = s.split_once('=')?;
2189 /// The multiple statement variant currently only detects `iter.next()?`/`iter.next().unwrap()`
2190 /// in two separate `let` statements that immediately follow the `splitn()`
2191 #[clippy::version = "1.57.0"]
2192 pub MANUAL_SPLIT_ONCE,
2194 "replace `.splitn(2, pat)` with `.split_once(pat)`"
2197 declare_clippy_lint! {
2198 /// ### What it does
2199 /// Checks for usages of `str::splitn` (or `str::rsplitn`) where using `str::split` would be the same.
2200 /// ### Why is this bad?
2201 /// The function `split` is simpler and there is no performance difference in these cases, considering
2202 /// that both functions return a lazy iterator.
2205 /// let str = "key=value=add";
2206 /// let _ = str.splitn(3, '=').next().unwrap();
2211 /// let str = "key=value=add";
2212 /// let _ = str.split('=').next().unwrap();
2214 #[clippy::version = "1.59.0"]
2215 pub NEEDLESS_SPLITN,
2217 "usages of `str::splitn` that can be replaced with `str::split`"
2220 declare_clippy_lint! {
2221 /// ### What it does
2222 /// Checks for unnecessary calls to [`ToOwned::to_owned`](https://doc.rust-lang.org/std/borrow/trait.ToOwned.html#tymethod.to_owned)
2223 /// and other `to_owned`-like functions.
2225 /// ### Why is this bad?
2226 /// The unnecessary calls result in useless allocations.
2228 /// ### Known problems
2229 /// `unnecessary_to_owned` can falsely trigger if `IntoIterator::into_iter` is applied to an
2230 /// owned copy of a resource and the resource is later used mutably. See
2231 /// [#8148](https://github.com/rust-lang/rust-clippy/issues/8148).
2235 /// let path = std::path::Path::new("x");
2236 /// foo(&path.to_string_lossy().to_string());
2237 /// fn foo(s: &str) {}
2241 /// let path = std::path::Path::new("x");
2242 /// foo(&path.to_string_lossy());
2243 /// fn foo(s: &str) {}
2245 #[clippy::version = "1.59.0"]
2246 pub UNNECESSARY_TO_OWNED,
2248 "unnecessary calls to `to_owned`-like functions"
2251 declare_clippy_lint! {
2252 /// ### What it does
2253 /// Checks for use of `.collect::<Vec<String>>().join("")` on iterators.
2255 /// ### Why is this bad?
2256 /// `.collect::<String>()` is more concise and might be more performant
2260 /// let vector = vec!["hello", "world"];
2261 /// let output = vector.iter().map(|item| item.to_uppercase()).collect::<Vec<String>>().join("");
2262 /// println!("{}", output);
2264 /// The correct use would be:
2266 /// let vector = vec!["hello", "world"];
2267 /// let output = vector.iter().map(|item| item.to_uppercase()).collect::<String>();
2268 /// println!("{}", output);
2270 /// ### Known problems
2271 /// While `.collect::<String>()` is sometimes more performant, there are cases where
2272 /// using `.collect::<String>()` over `.collect::<Vec<String>>().join("")`
2273 /// will prevent loop unrolling and will result in a negative performance impact.
2275 /// Additionally, differences have been observed between aarch64 and x86_64 assembly output,
2276 /// with aarch64 tending to producing faster assembly in more cases when using `.collect::<String>()`
2277 #[clippy::version = "1.61.0"]
2278 pub UNNECESSARY_JOIN,
2280 "using `.collect::<Vec<String>>().join(\"\")` on an iterator"
2283 declare_clippy_lint! {
2284 /// ### What it does
2285 /// Checks for no-op uses of `Option::{as_deref, as_deref_mut}`,
2286 /// for example, `Option<&T>::as_deref()` returns the same type.
2288 /// ### Why is this bad?
2289 /// Redundant code and improving readability.
2293 /// let a = Some(&1);
2294 /// let b = a.as_deref(); // goes from Option<&i32> to Option<&i32>
2299 /// let a = Some(&1);
2302 #[clippy::version = "1.57.0"]
2303 pub NEEDLESS_OPTION_AS_DEREF,
2305 "no-op use of `deref` or `deref_mut` method to `Option`."
2308 declare_clippy_lint! {
2309 /// ### What it does
2310 /// Finds usages of [`char::is_digit`](https://doc.rust-lang.org/stable/std/primitive.char.html#method.is_digit) that
2311 /// can be replaced with [`is_ascii_digit`](https://doc.rust-lang.org/stable/std/primitive.char.html#method.is_ascii_digit) or
2312 /// [`is_ascii_hexdigit`](https://doc.rust-lang.org/stable/std/primitive.char.html#method.is_ascii_hexdigit).
2314 /// ### Why is this bad?
2315 /// `is_digit(..)` is slower and requires specifying the radix.
2319 /// let c: char = '6';
2325 /// let c: char = '6';
2326 /// c.is_ascii_digit();
2327 /// c.is_ascii_hexdigit();
2329 #[clippy::version = "1.62.0"]
2330 pub IS_DIGIT_ASCII_RADIX,
2332 "use of `char::is_digit(..)` with literal radix of 10 or 16"
2335 declare_clippy_lint! {
2336 /// ### What it does
2337 /// Checks for calling `take` function after `as_ref`.
2339 /// ### Why is this bad?
2340 /// Redundant code. `take` writes `None` to its argument.
2341 /// In this case the modification is useless as it's a temporary that cannot be read from afterwards.
2345 /// let x = Some(3);
2346 /// x.as_ref().take();
2350 /// let x = Some(3);
2353 #[clippy::version = "1.62.0"]
2354 pub NEEDLESS_OPTION_TAKE,
2356 "using `.as_ref().take()` on a temporary value"
2359 declare_clippy_lint! {
2360 /// ### What it does
2361 /// Checks for `replace` statements which have no effect.
2363 /// ### Why is this bad?
2364 /// It's either a mistake or confusing.
2368 /// "1234".replace("12", "12");
2369 /// "1234".replacen("12", "12", 1);
2371 #[clippy::version = "1.63.0"]
2372 pub NO_EFFECT_REPLACE,
2374 "replace with no effect"
2377 declare_clippy_lint! {
2378 /// ### What it does
2379 /// Checks for usages of `.then_some(..).unwrap_or(..)`
2381 /// ### Why is this bad?
2382 /// This can be written more clearly with `if .. else ..`
2385 /// This lint currently only looks for usages of
2386 /// `.then_some(..).unwrap_or(..)`, but will be expanded
2387 /// to account for similar patterns.
2392 /// x.then_some("a").unwrap_or("b");
2397 /// if x { "a" } else { "b" };
2399 #[clippy::version = "1.64.0"]
2400 pub OBFUSCATED_IF_ELSE,
2402 "use of `.then_some(..).unwrap_or(..)` can be written \
2403 more clearly with `if .. else ..`"
2406 declare_clippy_lint! {
2407 /// ### What it does
2409 /// Checks for calls to `iter`, `iter_mut` or `into_iter` on collections containing a single item
2411 /// ### Why is this bad?
2413 /// It is simpler to use the once function from the standard library:
2418 /// let a = [123].iter();
2419 /// let b = Some(123).into_iter();
2424 /// let a = iter::once(&123);
2425 /// let b = iter::once(123);
2428 /// ### Known problems
2430 /// The type of the resulting iterator might become incompatible with its usage
2431 #[clippy::version = "1.64.0"]
2432 pub ITER_ON_SINGLE_ITEMS,
2434 "Iterator for array of length 1"
2437 declare_clippy_lint! {
2438 /// ### What it does
2440 /// Checks for calls to `iter`, `iter_mut` or `into_iter` on empty collections
2442 /// ### Why is this bad?
2444 /// It is simpler to use the empty function from the standard library:
2449 /// use std::{slice, option};
2450 /// let a: slice::Iter<i32> = [].iter();
2451 /// let f: option::IntoIter<i32> = None.into_iter();
2456 /// let a: iter::Empty<i32> = iter::empty();
2457 /// let b: iter::Empty<i32> = iter::empty();
2460 /// ### Known problems
2462 /// The type of the resulting iterator might become incompatible with its usage
2463 #[clippy::version = "1.64.0"]
2464 pub ITER_ON_EMPTY_COLLECTIONS,
2466 "Iterator for empty array"
2469 declare_clippy_lint! {
2470 /// ### What it does
2471 /// Checks for naive byte counts
2473 /// ### Why is this bad?
2474 /// The [`bytecount`](https://crates.io/crates/bytecount)
2475 /// crate has methods to count your bytes faster, especially for large slices.
2477 /// ### Known problems
2478 /// If you have predominantly small slices, the
2479 /// `bytecount::count(..)` method may actually be slower. However, if you can
2480 /// ensure that less than 2³²-1 matches arise, the `naive_count_32(..)` can be
2481 /// faster in those cases.
2485 /// # let vec = vec![1_u8];
2486 /// let count = vec.iter().filter(|x| **x == 0u8).count();
2491 /// # let vec = vec![1_u8];
2492 /// let count = bytecount::count(&vec, 0u8);
2494 #[clippy::version = "pre 1.29.0"]
2495 pub NAIVE_BYTECOUNT,
2497 "use of naive `<slice>.filter(|&x| x == y).count()` to count byte values"
2500 declare_clippy_lint! {
2501 /// ### What it does
2502 /// It checks for `str::bytes().count()` and suggests replacing it with
2505 /// ### Why is this bad?
2506 /// `str::bytes().count()` is longer and may not be as performant as using
2511 /// "hello".bytes().count();
2512 /// String::from("hello").bytes().count();
2517 /// String::from("hello").len();
2519 #[clippy::version = "1.62.0"]
2520 pub BYTES_COUNT_TO_LEN,
2522 "Using `bytes().count()` when `len()` performs the same functionality"
2525 declare_clippy_lint! {
2526 /// ### What it does
2527 /// Checks for calls to `ends_with` with possible file extensions
2528 /// and suggests to use a case-insensitive approach instead.
2530 /// ### Why is this bad?
2531 /// `ends_with` is case-sensitive and may not detect files with a valid extension.
2535 /// fn is_rust_file(filename: &str) -> bool {
2536 /// filename.ends_with(".rs")
2541 /// fn is_rust_file(filename: &str) -> bool {
2542 /// let filename = std::path::Path::new(filename);
2543 /// filename.extension()
2544 /// .map_or(false, |ext| ext.eq_ignore_ascii_case("rs"))
2547 #[clippy::version = "1.51.0"]
2548 pub CASE_SENSITIVE_FILE_EXTENSION_COMPARISONS,
2550 "Checks for calls to ends_with with case-sensitive file extensions"
2553 declare_clippy_lint! {
2554 /// ### What it does
2555 /// Checks for using `x.get(0)` instead of
2558 /// ### Why is this bad?
2559 /// Using `x.first()` is easier to read and has the same
2564 /// let x = vec![2, 3, 5];
2565 /// let first_element = x.get(0);
2570 /// let x = vec![2, 3, 5];
2571 /// let first_element = x.first();
2573 #[clippy::version = "1.63.0"]
2576 "Using `x.get(0)` when `x.first()` is simpler"
2579 declare_clippy_lint! {
2580 /// ### What it does
2582 /// Finds patterns that reimplement `Option::ok_or`.
2584 /// ### Why is this bad?
2586 /// Concise code helps focusing on behavior instead of boilerplate.
2590 /// let foo: Option<i32> = None;
2591 /// foo.map_or(Err("error"), |v| Ok(v));
2596 /// let foo: Option<i32> = None;
2597 /// foo.ok_or("error");
2599 #[clippy::version = "1.49.0"]
2602 "finds patterns that can be encoded more concisely with `Option::ok_or`"
2605 declare_clippy_lint! {
2606 /// ### What it does
2607 /// Checks for usage of `map(|x| x.clone())` or
2608 /// dereferencing closures for `Copy` types, on `Iterator` or `Option`,
2609 /// and suggests `cloned()` or `copied()` instead
2611 /// ### Why is this bad?
2612 /// Readability, this can be written more concisely
2616 /// let x = vec![42, 43];
2617 /// let y = x.iter();
2618 /// let z = y.map(|i| *i);
2621 /// The correct use would be:
2624 /// let x = vec![42, 43];
2625 /// let y = x.iter();
2626 /// let z = y.cloned();
2628 #[clippy::version = "pre 1.29.0"]
2631 "using `iterator.map(|x| x.clone())`, or dereferencing closures for `Copy` types"
2634 declare_clippy_lint! {
2635 /// ### What it does
2636 /// Checks for instances of `map_err(|_| Some::Enum)`
2638 /// ### Why is this bad?
2639 /// This `map_err` throws away the original error rather than allowing the enum to contain and report the cause of the error
2646 /// #[derive(Debug)]
2652 /// impl fmt::Display for Error {
2653 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2655 /// Error::Indivisible => write!(f, "could not divide input by three"),
2656 /// Error::Remainder(remainder) => write!(
2658 /// "input is not divisible by three, remainder = {}",
2665 /// impl std::error::Error for Error {}
2667 /// fn divisible_by_3(input: &str) -> Result<(), Error> {
2670 /// .map_err(|_| Error::Indivisible)
2672 /// .and_then(|remainder| {
2673 /// if remainder == 0 {
2676 /// Err(Error::Remainder(remainder as u8))
2684 /// use std::{fmt, num::ParseIntError};
2686 /// #[derive(Debug)]
2688 /// Indivisible(ParseIntError),
2692 /// impl fmt::Display for Error {
2693 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2695 /// Error::Indivisible(_) => write!(f, "could not divide input by three"),
2696 /// Error::Remainder(remainder) => write!(
2698 /// "input is not divisible by three, remainder = {}",
2705 /// impl std::error::Error for Error {
2706 /// fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
2708 /// Error::Indivisible(source) => Some(source),
2714 /// fn divisible_by_3(input: &str) -> Result<(), Error> {
2717 /// .map_err(Error::Indivisible)
2719 /// .and_then(|remainder| {
2720 /// if remainder == 0 {
2723 /// Err(Error::Remainder(remainder as u8))
2728 #[clippy::version = "1.48.0"]
2731 "`map_err` should not ignore the original error"
2734 declare_clippy_lint! {
2735 /// ### What it does
2736 /// Checks for `&mut Mutex::lock` calls
2738 /// ### Why is this bad?
2739 /// `Mutex::lock` is less efficient than
2740 /// calling `Mutex::get_mut`. In addition you also have a statically
2741 /// guarantee that the mutex isn't locked, instead of just a runtime
2746 /// use std::sync::{Arc, Mutex};
2748 /// let mut value_rc = Arc::new(Mutex::new(42_u8));
2749 /// let value_mutex = Arc::get_mut(&mut value_rc).unwrap();
2751 /// let mut value = value_mutex.lock().unwrap();
2756 /// use std::sync::{Arc, Mutex};
2758 /// let mut value_rc = Arc::new(Mutex::new(42_u8));
2759 /// let value_mutex = Arc::get_mut(&mut value_rc).unwrap();
2761 /// let value = value_mutex.get_mut().unwrap();
2764 #[clippy::version = "1.49.0"]
2767 "`&mut Mutex::lock` does unnecessary locking"
2770 declare_clippy_lint! {
2771 /// ### What it does
2772 /// Checks for duplicate open options as well as combinations
2773 /// that make no sense.
2775 /// ### Why is this bad?
2776 /// In the best case, the code will be harder to read than
2777 /// necessary. I don't know the worst case.
2781 /// use std::fs::OpenOptions;
2783 /// OpenOptions::new().read(true).truncate(true);
2785 #[clippy::version = "pre 1.29.0"]
2786 pub NONSENSICAL_OPEN_OPTIONS,
2788 "nonsensical combination of options for opening a file"
2791 declare_clippy_lint! {
2792 /// ### What it does
2793 ///* Checks for [push](https://doc.rust-lang.org/std/path/struct.PathBuf.html#method.push)
2794 /// calls on `PathBuf` that can cause overwrites.
2796 /// ### Why is this bad?
2797 /// Calling `push` with a root path at the start can overwrite the
2798 /// previous defined path.
2802 /// use std::path::PathBuf;
2804 /// let mut x = PathBuf::from("/foo");
2806 /// assert_eq!(x, PathBuf::from("/bar"));
2808 /// Could be written:
2811 /// use std::path::PathBuf;
2813 /// let mut x = PathBuf::from("/foo");
2815 /// assert_eq!(x, PathBuf::from("/foo/bar"));
2817 #[clippy::version = "1.36.0"]
2818 pub PATH_BUF_PUSH_OVERWRITE,
2820 "calling `push` with file system root on `PathBuf` can overwrite it"
2823 declare_clippy_lint! {
2824 /// ### What it does
2825 /// Checks for zipping a collection with the range of
2828 /// ### Why is this bad?
2829 /// The code is better expressed with `.enumerate()`.
2833 /// # let x = vec![1];
2834 /// let _ = x.iter().zip(0..x.len());
2839 /// # let x = vec![1];
2840 /// let _ = x.iter().enumerate();
2842 #[clippy::version = "pre 1.29.0"]
2843 pub RANGE_ZIP_WITH_LEN,
2845 "zipping iterator with a range when `enumerate()` would do"
2848 declare_clippy_lint! {
2849 /// ### What it does
2850 /// Checks for usage of `.repeat(1)` and suggest the following method for each types.
2851 /// - `.to_string()` for `str`
2852 /// - `.clone()` for `String`
2853 /// - `.to_vec()` for `slice`
2855 /// The lint will evaluate constant expressions and values as arguments of `.repeat(..)` and emit a message if
2856 /// they are equivalent to `1`. (Related discussion in [rust-clippy#7306](https://github.com/rust-lang/rust-clippy/issues/7306))
2858 /// ### Why is this bad?
2859 /// For example, `String.repeat(1)` is equivalent to `.clone()`. If cloning
2860 /// the string is the intention behind this, `clone()` should be used.
2865 /// let x = String::from("hello world").repeat(1);
2871 /// let x = String::from("hello world").clone();
2874 #[clippy::version = "1.47.0"]
2877 "using `.repeat(1)` instead of `String.clone()`, `str.to_string()` or `slice.to_vec()` "
2880 declare_clippy_lint! {
2881 /// ### What it does
2882 /// When sorting primitive values (integers, bools, chars, as well
2883 /// as arrays, slices, and tuples of such items), it is typically better to
2884 /// use an unstable sort than a stable sort.
2886 /// ### Why is this bad?
2887 /// Typically, using a stable sort consumes more memory and cpu cycles.
2888 /// Because values which compare equal are identical, preserving their
2889 /// relative order (the guarantee that a stable sort provides) means
2890 /// nothing, while the extra costs still apply.
2892 /// ### Known problems
2894 /// As pointed out in
2895 /// [issue #8241](https://github.com/rust-lang/rust-clippy/issues/8241),
2896 /// a stable sort can instead be significantly faster for certain scenarios
2897 /// (eg. when a sorted vector is extended with new data and resorted).
2899 /// For more information and benchmarking results, please refer to the
2900 /// issue linked above.
2904 /// let mut vec = vec![2, 1, 3];
2909 /// let mut vec = vec![2, 1, 3];
2910 /// vec.sort_unstable();
2912 #[clippy::version = "1.47.0"]
2913 pub STABLE_SORT_PRIMITIVE,
2915 "use of sort() when sort_unstable() is equivalent"
2918 declare_clippy_lint! {
2919 /// ### What it does
2920 /// Detects `().hash(_)`.
2922 /// ### Why is this bad?
2923 /// Hashing a unit value doesn't do anything as the implementation of `Hash` for `()` is a no-op.
2927 /// # use std::hash::Hash;
2928 /// # use std::collections::hash_map::DefaultHasher;
2929 /// # enum Foo { Empty, WithValue(u8) }
2931 /// # let mut state = DefaultHasher::new();
2932 /// # let my_enum = Foo::Empty;
2934 /// Empty => ().hash(&mut state),
2935 /// WithValue(x) => x.hash(&mut state),
2940 /// # use std::hash::Hash;
2941 /// # use std::collections::hash_map::DefaultHasher;
2942 /// # enum Foo { Empty, WithValue(u8) }
2944 /// # let mut state = DefaultHasher::new();
2945 /// # let my_enum = Foo::Empty;
2947 /// Empty => 0_u8.hash(&mut state),
2948 /// WithValue(x) => x.hash(&mut state),
2951 #[clippy::version = "1.58.0"]
2954 "hashing a unit value, which does nothing"
2957 declare_clippy_lint! {
2958 /// ### What it does
2959 /// Detects uses of `Vec::sort_by` passing in a closure
2960 /// which compares the two arguments, either directly or indirectly.
2962 /// ### Why is this bad?
2963 /// It is more clear to use `Vec::sort_by_key` (or `Vec::sort` if
2964 /// possible) than to use `Vec::sort_by` and a more complicated
2967 /// ### Known problems
2968 /// If the suggested `Vec::sort_by_key` uses Reverse and it isn't already
2969 /// imported by a use statement, then it will need to be added manually.
2974 /// # impl A { fn foo(&self) {} }
2975 /// # let mut vec: Vec<A> = Vec::new();
2976 /// vec.sort_by(|a, b| a.foo().cmp(&b.foo()));
2981 /// # impl A { fn foo(&self) {} }
2982 /// # let mut vec: Vec<A> = Vec::new();
2983 /// vec.sort_by_key(|a| a.foo());
2985 #[clippy::version = "1.46.0"]
2986 pub UNNECESSARY_SORT_BY,
2988 "Use of `Vec::sort_by` when `Vec::sort_by_key` or `Vec::sort` would be clearer"
2991 declare_clippy_lint! {
2992 /// ### What it does
2993 /// Finds occurrences of `Vec::resize(0, an_int)`
2995 /// ### Why is this bad?
2996 /// This is probably an argument inversion mistake.
3000 /// vec!(1, 2, 3, 4, 5).resize(0, 5)
3005 /// vec!(1, 2, 3, 4, 5).clear()
3007 #[clippy::version = "1.46.0"]
3008 pub VEC_RESIZE_TO_ZERO,
3010 "emptying a vector with `resize(0, an_int)` instead of `clear()` is probably an argument inversion mistake"
3013 declare_clippy_lint! {
3014 /// ### What it does
3015 /// Checks for use of File::read_to_end and File::read_to_string.
3017 /// ### Why is this bad?
3018 /// `fs::{read, read_to_string}` provide the same functionality when `buf` is empty with fewer imports and no intermediate values.
3019 /// See also: [fs::read docs](https://doc.rust-lang.org/std/fs/fn.read.html), [fs::read_to_string docs](https://doc.rust-lang.org/std/fs/fn.read_to_string.html)
3023 /// # use std::io::Read;
3024 /// # use std::fs::File;
3025 /// let mut f = File::open("foo.txt").unwrap();
3026 /// let mut bytes = Vec::new();
3027 /// f.read_to_end(&mut bytes).unwrap();
3029 /// Can be written more concisely as
3032 /// let mut bytes = fs::read("foo.txt").unwrap();
3034 #[clippy::version = "1.44.0"]
3035 pub VERBOSE_FILE_READS,
3037 "use of `File::read_to_end` or `File::read_to_string`"
3040 declare_clippy_lint! {
3041 /// ### What it does
3043 /// Checks for iterating a map (`HashMap` or `BTreeMap`) and
3044 /// ignoring either the keys or values.
3046 /// ### Why is this bad?
3048 /// Readability. There are `keys` and `values` methods that
3049 /// can be used to express that we only need the keys or the values.
3054 /// # use std::collections::HashMap;
3055 /// let map: HashMap<u32, u32> = HashMap::new();
3056 /// let values = map.iter().map(|(_, value)| value).collect::<Vec<_>>();
3061 /// # use std::collections::HashMap;
3062 /// let map: HashMap<u32, u32> = HashMap::new();
3063 /// let values = map.values().collect::<Vec<_>>();
3065 #[clippy::version = "1.65.0"]
3068 "iterating on map using `iter` when `keys` or `values` would do"
3071 pub struct Methods {
3072 avoid_breaking_exported_api: bool,
3073 msrv: Option<RustcVersion>,
3074 allow_expect_in_tests: bool,
3075 allow_unwrap_in_tests: bool,
3081 avoid_breaking_exported_api: bool,
3082 msrv: Option<RustcVersion>,
3083 allow_expect_in_tests: bool,
3084 allow_unwrap_in_tests: bool,
3087 avoid_breaking_exported_api,
3089 allow_expect_in_tests,
3090 allow_unwrap_in_tests,
3095 impl_lint_pass!(Methods => [
3098 SHOULD_IMPLEMENT_TRAIT,
3099 WRONG_SELF_CONVENTION,
3101 UNWRAP_OR_ELSE_DEFAULT,
3103 RESULT_MAP_OR_INTO_OPTION,
3105 BIND_INSTEAD_OF_MAP,
3114 COLLAPSIBLE_STR_REPLACE,
3115 ITER_OVEREAGER_CLONED,
3116 CLONED_INSTEAD_OF_COPIED,
3118 INEFFICIENT_TO_STRING,
3120 SINGLE_CHAR_PATTERN,
3121 SINGLE_CHAR_ADD_STR,
3125 FILTER_MAP_IDENTITY,
3133 ITERATOR_STEP_BY_ZERO,
3142 STRING_EXTEND_CHARS,
3143 ITER_CLONED_COLLECT,
3147 UNNECESSARY_FILTER_MAP,
3148 UNNECESSARY_FIND_MAP,
3151 UNINIT_ASSUMED_INIT,
3152 MANUAL_SATURATING_ARITHMETIC,
3155 OPTION_AS_REF_DEREF,
3156 UNNECESSARY_LAZY_EVALUATIONS,
3157 MAP_COLLECT_RESULT_UNIT,
3158 FROM_ITER_INSTEAD_OF_COLLECT,
3161 SUSPICIOUS_TO_OWNED,
3167 UNNECESSARY_TO_OWNED,
3170 NEEDLESS_OPTION_AS_DEREF,
3171 IS_DIGIT_ASCII_RADIX,
3172 NEEDLESS_OPTION_TAKE,
3175 ITER_ON_SINGLE_ITEMS,
3176 ITER_ON_EMPTY_COLLECTIONS,
3179 CASE_SENSITIVE_FILE_EXTENSION_COMPARISONS,
3185 NONSENSICAL_OPEN_OPTIONS,
3186 PATH_BUF_PUSH_OVERWRITE,
3189 STABLE_SORT_PRIMITIVE,
3191 UNNECESSARY_SORT_BY,
3197 /// Extracts a method call name, args, and `Span` of the method name.
3198 fn method_call<'tcx>(
3199 recv: &'tcx hir::Expr<'tcx>,
3200 ) -> Option<(&'tcx str, &'tcx hir::Expr<'tcx>, &'tcx [hir::Expr<'tcx>], Span)> {
3201 if let ExprKind::MethodCall(path, receiver, args, _) = recv.kind {
3202 if !args.iter().any(|e| e.span.from_expansion()) && !receiver.span.from_expansion() {
3203 let name = path.ident.name.as_str();
3204 return Some((name, receiver, args, path.ident.span));
3210 impl<'tcx> LateLintPass<'tcx> for Methods {
3211 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) {
3212 if expr.span.from_expansion() {
3216 self.check_methods(cx, expr);
3219 hir::ExprKind::Call(func, args) => {
3220 from_iter_instead_of_collect::check(cx, expr, args, func);
3222 hir::ExprKind::MethodCall(method_call, receiver, args, _) => {
3223 let method_span = method_call.ident.span;
3224 or_fun_call::check(cx, expr, method_span, method_call.ident.as_str(), receiver, args);
3225 expect_fun_call::check(cx, expr, method_span, method_call.ident.as_str(), receiver, args);
3226 clone_on_copy::check(cx, expr, method_call.ident.name, receiver, args);
3227 clone_on_ref_ptr::check(cx, expr, method_call.ident.name, receiver, args);
3228 inefficient_to_string::check(cx, expr, method_call.ident.name, receiver, args);
3229 single_char_add_str::check(cx, expr, receiver, args);
3230 into_iter_on_ref::check(cx, expr, method_span, method_call.ident.name, receiver);
3231 single_char_pattern::check(cx, expr, method_call.ident.name, receiver, args);
3232 unnecessary_to_owned::check(cx, expr, method_call.ident.name, receiver, args, self.msrv);
3234 hir::ExprKind::Binary(op, lhs, rhs) if op.node == hir::BinOpKind::Eq || op.node == hir::BinOpKind::Ne => {
3235 let mut info = BinaryExprInfo {
3239 eq: op.node == hir::BinOpKind::Eq,
3241 lint_binary_expr_with_method_call(cx, &mut info);
3247 #[allow(clippy::too_many_lines)]
3248 fn check_impl_item(&mut self, cx: &LateContext<'tcx>, impl_item: &'tcx hir::ImplItem<'_>) {
3249 if in_external_macro(cx.sess(), impl_item.span) {
3252 let name = impl_item.ident.name.as_str();
3253 let parent = cx.tcx.hir().get_parent_item(impl_item.hir_id()).def_id;
3254 let item = cx.tcx.hir().expect_item(parent);
3255 let self_ty = cx.tcx.type_of(item.def_id);
3257 let implements_trait = matches!(item.kind, hir::ItemKind::Impl(hir::Impl { of_trait: Some(_), .. }));
3259 if let hir::ImplItemKind::Fn(ref sig, id) = impl_item.kind;
3260 if let Some(first_arg) = iter_input_pats(sig.decl, cx.tcx.hir().body(id)).next();
3262 let method_sig = cx.tcx.fn_sig(impl_item.def_id.def_id);
3263 let method_sig = cx.tcx.erase_late_bound_regions(method_sig);
3265 let first_arg_ty = method_sig.inputs().iter().next();
3267 // check conventions w.r.t. conversion method names and predicates
3268 if let Some(first_arg_ty) = first_arg_ty;
3271 // if this impl block implements a trait, lint in trait definition instead
3272 if !implements_trait && cx.access_levels.is_exported(impl_item.def_id.def_id) {
3273 // check missing trait implementations
3274 for method_config in &TRAIT_METHODS {
3275 if name == method_config.method_name &&
3276 sig.decl.inputs.len() == method_config.param_count &&
3277 method_config.output_type.matches(&sig.decl.output) &&
3278 method_config.self_kind.matches(cx, self_ty, *first_arg_ty) &&
3279 fn_header_equals(method_config.fn_header, sig.header) &&
3280 method_config.lifetime_param_cond(impl_item)
3284 SHOULD_IMPLEMENT_TRAIT,
3287 "method `{}` can be confused for the standard trait method `{}::{}`",
3288 method_config.method_name,
3289 method_config.trait_name,
3290 method_config.method_name
3294 "consider implementing the trait `{}` or choosing a less ambiguous method name",
3295 method_config.trait_name
3302 if sig.decl.implicit_self.has_implicit_self()
3303 && !(self.avoid_breaking_exported_api
3304 && cx.access_levels.is_exported(impl_item.def_id.def_id))
3306 wrong_self_convention::check(
3319 // if this impl block implements a trait, lint in trait definition instead
3320 if implements_trait {
3324 if let hir::ImplItemKind::Fn(_, _) = impl_item.kind {
3325 let ret_ty = return_ty(cx, impl_item.hir_id());
3327 // walk the return type and check for Self (this does not check associated types)
3328 if let Some(self_adt) = self_ty.ty_adt_def() {
3329 if contains_adt_constructor(ret_ty, self_adt) {
3332 } else if ret_ty.contains(self_ty) {
3336 // if return type is impl trait, check the associated types
3337 if let ty::Opaque(def_id, _) = *ret_ty.kind() {
3338 // one of the associated types must be Self
3339 for &(predicate, _span) in cx.tcx.explicit_item_bounds(def_id) {
3340 if let ty::PredicateKind::Projection(projection_predicate) = predicate.kind().skip_binder() {
3341 let assoc_ty = match projection_predicate.term.unpack() {
3342 ty::TermKind::Ty(ty) => ty,
3343 ty::TermKind::Const(_c) => continue,
3345 // walk the associated type and check for Self
3346 if let Some(self_adt) = self_ty.ty_adt_def() {
3347 if contains_adt_constructor(assoc_ty, self_adt) {
3350 } else if assoc_ty.contains(self_ty) {
3357 if name == "new" && ret_ty != self_ty {
3362 "methods called `new` usually return `Self`",
3368 fn check_trait_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx TraitItem<'_>) {
3369 if in_external_macro(cx.tcx.sess, item.span) {
3374 if let TraitItemKind::Fn(ref sig, _) = item.kind;
3375 if sig.decl.implicit_self.has_implicit_self();
3376 if let Some(first_arg_ty) = sig.decl.inputs.iter().next();
3379 let first_arg_span = first_arg_ty.span;
3380 let first_arg_ty = hir_ty_to_ty(cx.tcx, first_arg_ty);
3381 let self_ty = TraitRef::identity(cx.tcx, item.def_id.to_def_id()).self_ty().skip_binder();
3382 wrong_self_convention::check(
3384 item.ident.name.as_str(),
3395 if item.ident.name == sym::new;
3396 if let TraitItemKind::Fn(_, _) = item.kind;
3397 let ret_ty = return_ty(cx, item.hir_id());
3398 let self_ty = TraitRef::identity(cx.tcx, item.def_id.to_def_id()).self_ty().skip_binder();
3399 if !ret_ty.contains(self_ty);
3406 "methods called `new` usually return `Self`",
3412 extract_msrv_attr!(LateContext);
3416 #[allow(clippy::too_many_lines)]
3417 fn check_methods<'tcx>(&self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
3418 if let Some((name, recv, args, span)) = method_call(expr) {
3419 match (name, args) {
3420 ("add" | "offset" | "sub" | "wrapping_offset" | "wrapping_add" | "wrapping_sub", [_arg]) => {
3421 zst_offset::check(cx, expr, recv);
3423 ("and_then", [arg]) => {
3424 let biom_option_linted = bind_instead_of_map::OptionAndThenSome::check(cx, expr, recv, arg);
3425 let biom_result_linted = bind_instead_of_map::ResultAndThenOk::check(cx, expr, recv, arg);
3426 if !biom_option_linted && !biom_result_linted {
3427 unnecessary_lazy_eval::check(cx, expr, recv, arg, "and");
3430 ("as_deref" | "as_deref_mut", []) => {
3431 needless_option_as_deref::check(cx, expr, recv, name);
3433 ("as_mut", []) => useless_asref::check(cx, expr, "as_mut", recv),
3434 ("as_ref", []) => useless_asref::check(cx, expr, "as_ref", recv),
3435 ("assume_init", []) => uninit_assumed_init::check(cx, expr, recv),
3436 ("cloned", []) => cloned_instead_of_copied::check(cx, expr, recv, span, self.msrv),
3437 ("collect", []) => match method_call(recv) {
3438 Some((name @ ("cloned" | "copied"), recv2, [], _)) => {
3439 iter_cloned_collect::check(cx, name, expr, recv2);
3441 Some(("map", m_recv, [m_arg], _)) => {
3442 map_collect_result_unit::check(cx, expr, m_recv, m_arg, recv);
3444 Some(("take", take_self_arg, [take_arg], _)) => {
3445 if meets_msrv(self.msrv, msrvs::STR_REPEAT) {
3446 manual_str_repeat::check(cx, expr, recv, take_self_arg, take_arg);
3451 ("count", []) if is_trait_method(cx, expr, sym::Iterator) => match method_call(recv) {
3452 Some(("cloned", recv2, [], _)) => iter_overeager_cloned::check(cx, expr, recv, recv2, true, false),
3453 Some((name2 @ ("into_iter" | "iter" | "iter_mut"), recv2, [], _)) => {
3454 iter_count::check(cx, expr, recv2, name2);
3456 Some(("map", _, [arg], _)) => suspicious_map::check(cx, expr, recv, arg),
3457 Some(("filter", recv2, [arg], _)) => bytecount::check(cx, expr, recv2, arg),
3458 Some(("bytes", recv2, [], _)) => bytes_count_to_len::check(cx, expr, recv, recv2),
3461 ("drain", [arg]) => {
3462 iter_with_drain::check(cx, expr, recv, span, arg);
3464 ("ends_with", [arg]) => {
3465 if let ExprKind::MethodCall(.., span) = expr.kind {
3466 case_sensitive_file_extension_comparisons::check(cx, expr, span, recv, arg);
3469 ("expect", [_]) => match method_call(recv) {
3470 Some(("ok", recv, [], _)) => ok_expect::check(cx, expr, recv),
3471 Some(("err", recv, [], err_span)) => err_expect::check(cx, expr, recv, self.msrv, span, err_span),
3472 _ => expect_used::check(cx, expr, recv, false, self.allow_expect_in_tests),
3474 ("expect_err", [_]) => expect_used::check(cx, expr, recv, true, self.allow_expect_in_tests),
3475 ("extend", [arg]) => {
3476 string_extend_chars::check(cx, expr, recv, arg);
3477 extend_with_drain::check(cx, expr, recv, arg);
3479 ("filter_map", [arg]) => {
3480 unnecessary_filter_map::check(cx, expr, arg, name);
3481 filter_map_identity::check(cx, expr, arg, span);
3483 ("find_map", [arg]) => {
3484 unnecessary_filter_map::check(cx, expr, arg, name);
3486 ("flat_map", [arg]) => {
3487 flat_map_identity::check(cx, expr, arg, span);
3488 flat_map_option::check(cx, expr, arg, span);
3490 ("flatten", []) => match method_call(recv) {
3491 Some(("map", recv, [map_arg], map_span)) => map_flatten::check(cx, expr, recv, map_arg, map_span),
3492 Some(("cloned", recv2, [], _)) => iter_overeager_cloned::check(cx, expr, recv, recv2, false, true),
3495 ("fold", [init, acc]) => unnecessary_fold::check(cx, expr, init, acc, span),
3496 ("for_each", [_]) => {
3497 if let Some(("inspect", _, [_], span2)) = method_call(recv) {
3498 inspect_for_each::check(cx, expr, span2);
3502 get_first::check(cx, expr, recv, arg);
3503 get_last_with_len::check(cx, expr, recv, arg);
3505 ("get_or_insert_with", [arg]) => unnecessary_lazy_eval::check(cx, expr, recv, arg, "get_or_insert"),
3506 ("hash", [arg]) => {
3507 unit_hash::check(cx, expr, recv, arg);
3509 ("is_file", []) => filetype_is_file::check(cx, expr, recv),
3510 ("is_digit", [radix]) => is_digit_ascii_radix::check(cx, expr, recv, radix, self.msrv),
3511 ("is_none", []) => check_is_some_is_none(cx, expr, recv, false),
3512 ("is_some", []) => check_is_some_is_none(cx, expr, recv, true),
3513 ("iter" | "iter_mut" | "into_iter", []) => {
3514 iter_on_single_or_empty_collections::check(cx, expr, name, recv);
3516 ("join", [join_arg]) => {
3517 if let Some(("collect", _, _, span)) = method_call(recv) {
3518 unnecessary_join::check(cx, expr, recv, join_arg, span);
3521 ("last", []) | ("skip", [_]) => {
3522 if let Some((name2, recv2, args2, _span2)) = method_call(recv) {
3523 if let ("cloned", []) = (name2, args2) {
3524 iter_overeager_cloned::check(cx, expr, recv, recv2, false, false);
3529 mut_mutex_lock::check(cx, expr, recv, span);
3531 (name @ ("map" | "map_err"), [m_arg]) => {
3533 map_clone::check(cx, expr, recv, m_arg, self.msrv);
3534 if let Some((map_name @ ("iter" | "into_iter"), recv2, _, _)) = method_call(recv) {
3535 iter_kv_map::check(cx, map_name, expr, recv2, m_arg);
3538 map_err_ignore::check(cx, expr, m_arg);
3540 if let Some((name, recv2, args, span2)) = method_call(recv) {
3541 match (name, args) {
3542 ("as_mut", []) => option_as_ref_deref::check(cx, expr, recv2, m_arg, true, self.msrv),
3543 ("as_ref", []) => option_as_ref_deref::check(cx, expr, recv2, m_arg, false, self.msrv),
3544 ("filter", [f_arg]) => {
3545 filter_map::check(cx, expr, recv2, f_arg, span2, recv, m_arg, span, false);
3547 ("find", [f_arg]) => {
3548 filter_map::check(cx, expr, recv2, f_arg, span2, recv, m_arg, span, true);
3553 map_identity::check(cx, expr, recv, m_arg, name, span);
3555 ("map_or", [def, map]) => {
3556 option_map_or_none::check(cx, expr, recv, def, map);
3557 manual_ok_or::check(cx, expr, recv, def, map);
3560 if let Some((name2, recv2, args2, _)) = method_call(recv) {
3561 match (name2, args2) {
3562 ("cloned", []) => iter_overeager_cloned::check(cx, expr, recv, recv2, false, false),
3563 ("filter", [arg]) => filter_next::check(cx, expr, recv2, arg),
3564 ("filter_map", [arg]) => filter_map_next::check(cx, expr, recv2, arg, self.msrv),
3565 ("iter", []) => iter_next_slice::check(cx, expr, recv2),
3566 ("skip", [arg]) => iter_skip_next::check(cx, expr, recv2, arg),
3567 ("skip_while", [_]) => skip_while_next::check(cx, expr),
3572 ("nth", [n_arg]) => match method_call(recv) {
3573 Some(("bytes", recv2, [], _)) => bytes_nth::check(cx, expr, recv2, n_arg),
3574 Some(("cloned", recv2, [], _)) => iter_overeager_cloned::check(cx, expr, recv, recv2, false, false),
3575 Some(("iter", recv2, [], _)) => iter_nth::check(cx, expr, recv2, recv, n_arg, false),
3576 Some(("iter_mut", recv2, [], _)) => iter_nth::check(cx, expr, recv2, recv, n_arg, true),
3577 _ => iter_nth_zero::check(cx, expr, recv, n_arg),
3579 ("ok_or_else", [arg]) => unnecessary_lazy_eval::check(cx, expr, recv, arg, "ok_or"),
3581 open_options::check(cx, expr, recv);
3583 ("or_else", [arg]) => {
3584 if !bind_instead_of_map::ResultOrElseErrInfo::check(cx, expr, recv, arg) {
3585 unnecessary_lazy_eval::check(cx, expr, recv, arg, "or");
3588 ("push", [arg]) => {
3589 path_buf_push_overwrite::check(cx, expr, arg);
3591 ("read_to_end", [_]) => {
3592 verbose_file_reads::check(cx, expr, recv, verbose_file_reads::READ_TO_END_MSG);
3594 ("read_to_string", [_]) => {
3595 verbose_file_reads::check(cx, expr, recv, verbose_file_reads::READ_TO_STRING_MSG);
3597 ("repeat", [arg]) => {
3598 repeat_once::check(cx, expr, recv, arg);
3600 (name @ ("replace" | "replacen"), [arg1, arg2] | [arg1, arg2, _]) => {
3601 no_effect_replace::check(cx, expr, arg1, arg2);
3603 // Check for repeated `str::replace` calls to perform `collapsible_str_replace` lint
3604 if name == "replace" && let Some(("replace", ..)) = method_call(recv) {
3605 collapsible_str_replace::check(cx, expr, arg1, arg2);
3608 ("resize", [count_arg, default_arg]) => {
3609 vec_resize_to_zero::check(cx, expr, count_arg, default_arg, span);
3612 stable_sort_primitive::check(cx, expr, recv);
3614 ("sort_by", [arg]) => {
3615 unnecessary_sort_by::check(cx, expr, recv, arg, false);
3617 ("sort_unstable_by", [arg]) => {
3618 unnecessary_sort_by::check(cx, expr, recv, arg, true);
3620 ("splitn" | "rsplitn", [count_arg, pat_arg]) => {
3621 if let Some((Constant::Int(count), _)) = constant(cx, cx.typeck_results(), count_arg) {
3622 suspicious_splitn::check(cx, name, expr, recv, count);
3623 str_splitn::check(cx, name, expr, recv, pat_arg, count, self.msrv);
3626 ("splitn_mut" | "rsplitn_mut", [count_arg, _]) => {
3627 if let Some((Constant::Int(count), _)) = constant(cx, cx.typeck_results(), count_arg) {
3628 suspicious_splitn::check(cx, name, expr, recv, count);
3631 ("step_by", [arg]) => iterator_step_by_zero::check(cx, expr, arg),
3632 ("take", [_arg]) => {
3633 if let Some((name2, recv2, args2, _span2)) = method_call(recv) {
3634 if let ("cloned", []) = (name2, args2) {
3635 iter_overeager_cloned::check(cx, expr, recv, recv2, false, false);
3639 ("take", []) => needless_option_take::check(cx, expr, recv),
3640 ("then", [arg]) => {
3641 if !meets_msrv(self.msrv, msrvs::BOOL_THEN_SOME) {
3644 unnecessary_lazy_eval::check(cx, expr, recv, arg, "then_some");
3646 ("to_owned", []) => {
3647 if !suspicious_to_owned::check(cx, expr, recv) {
3648 implicit_clone::check(cx, name, expr, recv);
3651 ("to_os_string" | "to_path_buf" | "to_vec", []) => {
3652 implicit_clone::check(cx, name, expr, recv);
3655 match method_call(recv) {
3656 Some(("get", recv, [get_arg], _)) => {
3657 get_unwrap::check(cx, expr, recv, get_arg, false);
3659 Some(("get_mut", recv, [get_arg], _)) => {
3660 get_unwrap::check(cx, expr, recv, get_arg, true);
3662 Some(("or", recv, [or_arg], or_span)) => {
3663 or_then_unwrap::check(cx, expr, recv, or_arg, or_span);
3667 unwrap_used::check(cx, expr, recv, false, self.allow_unwrap_in_tests);
3669 ("unwrap_err", []) => unwrap_used::check(cx, expr, recv, true, self.allow_unwrap_in_tests),
3670 ("unwrap_or", [u_arg]) => match method_call(recv) {
3671 Some((arith @ ("checked_add" | "checked_sub" | "checked_mul"), lhs, [rhs], _)) => {
3672 manual_saturating_arithmetic::check(cx, expr, lhs, rhs, u_arg, &arith["checked_".len()..]);
3674 Some(("map", m_recv, [m_arg], span)) => {
3675 option_map_unwrap_or::check(cx, expr, m_recv, m_arg, recv, u_arg, span);
3677 Some(("then_some", t_recv, [t_arg], _)) => {
3678 obfuscated_if_else::check(cx, expr, t_recv, t_arg, u_arg);
3682 ("unwrap_or_else", [u_arg]) => match method_call(recv) {
3683 Some(("map", recv, [map_arg], _))
3684 if map_unwrap_or::check(cx, expr, recv, map_arg, u_arg, self.msrv) => {},
3686 unwrap_or_else_default::check(cx, expr, recv, u_arg);
3687 unnecessary_lazy_eval::check(cx, expr, recv, u_arg, "unwrap_or");
3691 if let ExprKind::MethodCall(name, iter_recv, [], _) = recv.kind
3692 && name.ident.name == sym::iter
3694 range_zip_with_len::check(cx, expr, iter_recv, arg);
3703 fn check_is_some_is_none(cx: &LateContext<'_>, expr: &Expr<'_>, recv: &Expr<'_>, is_some: bool) {
3704 if let Some((name @ ("find" | "position" | "rposition"), f_recv, [arg], span)) = method_call(recv) {
3705 search_is_some::check(cx, expr, name, is_some, f_recv, arg, recv, span);
3709 /// Used for `lint_binary_expr_with_method_call`.
3710 #[derive(Copy, Clone)]
3711 struct BinaryExprInfo<'a> {
3712 expr: &'a hir::Expr<'a>,
3713 chain: &'a hir::Expr<'a>,
3714 other: &'a hir::Expr<'a>,
3718 /// Checks for the `CHARS_NEXT_CMP` and `CHARS_LAST_CMP` lints.
3719 fn lint_binary_expr_with_method_call(cx: &LateContext<'_>, info: &mut BinaryExprInfo<'_>) {
3720 macro_rules! lint_with_both_lhs_and_rhs {
3721 ($func:expr, $cx:expr, $info:ident) => {
3722 if !$func($cx, $info) {
3723 ::std::mem::swap(&mut $info.chain, &mut $info.other);
3724 if $func($cx, $info) {
3731 lint_with_both_lhs_and_rhs!(chars_next_cmp::check, cx, info);
3732 lint_with_both_lhs_and_rhs!(chars_last_cmp::check, cx, info);
3733 lint_with_both_lhs_and_rhs!(chars_next_cmp_with_unwrap::check, cx, info);
3734 lint_with_both_lhs_and_rhs!(chars_last_cmp_with_unwrap::check, cx, info);
3737 const FN_HEADER: hir::FnHeader = hir::FnHeader {
3738 unsafety: hir::Unsafety::Normal,
3739 constness: hir::Constness::NotConst,
3740 asyncness: hir::IsAsync::NotAsync,
3741 abi: rustc_target::spec::abi::Abi::Rust,
3744 struct ShouldImplTraitCase {
3745 trait_name: &'static str,
3746 method_name: &'static str,
3748 fn_header: hir::FnHeader,
3749 // implicit self kind expected (none, self, &self, ...)
3750 self_kind: SelfKind,
3751 // checks against the output type
3752 output_type: OutType,
3753 // certain methods with explicit lifetimes can't implement the equivalent trait method
3754 lint_explicit_lifetime: bool,
3756 impl ShouldImplTraitCase {
3758 trait_name: &'static str,
3759 method_name: &'static str,
3761 fn_header: hir::FnHeader,
3762 self_kind: SelfKind,
3763 output_type: OutType,
3764 lint_explicit_lifetime: bool,
3765 ) -> ShouldImplTraitCase {
3766 ShouldImplTraitCase {
3773 lint_explicit_lifetime,
3777 fn lifetime_param_cond(&self, impl_item: &hir::ImplItem<'_>) -> bool {
3778 self.lint_explicit_lifetime
3779 || !impl_item.generics.params.iter().any(|p| {
3782 hir::GenericParamKind::Lifetime {
3783 kind: hir::LifetimeParamKind::Explicit
3791 const TRAIT_METHODS: [ShouldImplTraitCase; 30] = [
3792 ShouldImplTraitCase::new("std::ops::Add", "add", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3793 ShouldImplTraitCase::new("std::convert::AsMut", "as_mut", 1, FN_HEADER, SelfKind::RefMut, OutType::Ref, true),
3794 ShouldImplTraitCase::new("std::convert::AsRef", "as_ref", 1, FN_HEADER, SelfKind::Ref, OutType::Ref, true),
3795 ShouldImplTraitCase::new("std::ops::BitAnd", "bitand", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3796 ShouldImplTraitCase::new("std::ops::BitOr", "bitor", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3797 ShouldImplTraitCase::new("std::ops::BitXor", "bitxor", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3798 ShouldImplTraitCase::new("std::borrow::Borrow", "borrow", 1, FN_HEADER, SelfKind::Ref, OutType::Ref, true),
3799 ShouldImplTraitCase::new("std::borrow::BorrowMut", "borrow_mut", 1, FN_HEADER, SelfKind::RefMut, OutType::Ref, true),
3800 ShouldImplTraitCase::new("std::clone::Clone", "clone", 1, FN_HEADER, SelfKind::Ref, OutType::Any, true),
3801 ShouldImplTraitCase::new("std::cmp::Ord", "cmp", 2, FN_HEADER, SelfKind::Ref, OutType::Any, true),
3802 // FIXME: default doesn't work
3803 ShouldImplTraitCase::new("std::default::Default", "default", 0, FN_HEADER, SelfKind::No, OutType::Any, true),
3804 ShouldImplTraitCase::new("std::ops::Deref", "deref", 1, FN_HEADER, SelfKind::Ref, OutType::Ref, true),
3805 ShouldImplTraitCase::new("std::ops::DerefMut", "deref_mut", 1, FN_HEADER, SelfKind::RefMut, OutType::Ref, true),
3806 ShouldImplTraitCase::new("std::ops::Div", "div", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3807 ShouldImplTraitCase::new("std::ops::Drop", "drop", 1, FN_HEADER, SelfKind::RefMut, OutType::Unit, true),
3808 ShouldImplTraitCase::new("std::cmp::PartialEq", "eq", 2, FN_HEADER, SelfKind::Ref, OutType::Bool, true),
3809 ShouldImplTraitCase::new("std::iter::FromIterator", "from_iter", 1, FN_HEADER, SelfKind::No, OutType::Any, true),
3810 ShouldImplTraitCase::new("std::str::FromStr", "from_str", 1, FN_HEADER, SelfKind::No, OutType::Any, true),
3811 ShouldImplTraitCase::new("std::hash::Hash", "hash", 2, FN_HEADER, SelfKind::Ref, OutType::Unit, true),
3812 ShouldImplTraitCase::new("std::ops::Index", "index", 2, FN_HEADER, SelfKind::Ref, OutType::Ref, true),
3813 ShouldImplTraitCase::new("std::ops::IndexMut", "index_mut", 2, FN_HEADER, SelfKind::RefMut, OutType::Ref, true),
3814 ShouldImplTraitCase::new("std::iter::IntoIterator", "into_iter", 1, FN_HEADER, SelfKind::Value, OutType::Any, true),
3815 ShouldImplTraitCase::new("std::ops::Mul", "mul", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3816 ShouldImplTraitCase::new("std::ops::Neg", "neg", 1, FN_HEADER, SelfKind::Value, OutType::Any, true),
3817 ShouldImplTraitCase::new("std::iter::Iterator", "next", 1, FN_HEADER, SelfKind::RefMut, OutType::Any, false),
3818 ShouldImplTraitCase::new("std::ops::Not", "not", 1, FN_HEADER, SelfKind::Value, OutType::Any, true),
3819 ShouldImplTraitCase::new("std::ops::Rem", "rem", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3820 ShouldImplTraitCase::new("std::ops::Shl", "shl", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3821 ShouldImplTraitCase::new("std::ops::Shr", "shr", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3822 ShouldImplTraitCase::new("std::ops::Sub", "sub", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3825 #[derive(Clone, Copy, PartialEq, Eq, Debug)]
3834 fn matches<'a>(self, cx: &LateContext<'a>, parent_ty: Ty<'a>, ty: Ty<'a>) -> bool {
3835 fn matches_value<'a>(cx: &LateContext<'a>, parent_ty: Ty<'a>, ty: Ty<'a>) -> bool {
3836 if ty == parent_ty {
3838 } else if ty.is_box() {
3839 ty.boxed_ty() == parent_ty
3840 } else if is_type_diagnostic_item(cx, ty, sym::Rc) || is_type_diagnostic_item(cx, ty, sym::Arc) {
3841 if let ty::Adt(_, substs) = ty.kind() {
3842 substs.types().next().map_or(false, |t| t == parent_ty)
3851 fn matches_ref<'a>(cx: &LateContext<'a>, mutability: hir::Mutability, parent_ty: Ty<'a>, ty: Ty<'a>) -> bool {
3852 if let ty::Ref(_, t, m) = *ty.kind() {
3853 return m == mutability && t == parent_ty;
3856 let trait_path = match mutability {
3857 hir::Mutability::Not => &paths::ASREF_TRAIT,
3858 hir::Mutability::Mut => &paths::ASMUT_TRAIT,
3861 let trait_def_id = match get_trait_def_id(cx, trait_path) {
3863 None => return false,
3865 implements_trait(cx, ty, trait_def_id, &[parent_ty.into()])
3868 fn matches_none<'a>(cx: &LateContext<'a>, parent_ty: Ty<'a>, ty: Ty<'a>) -> bool {
3869 !matches_value(cx, parent_ty, ty)
3870 && !matches_ref(cx, hir::Mutability::Not, parent_ty, ty)
3871 && !matches_ref(cx, hir::Mutability::Mut, parent_ty, ty)
3875 Self::Value => matches_value(cx, parent_ty, ty),
3876 Self::Ref => matches_ref(cx, hir::Mutability::Not, parent_ty, ty) || ty == parent_ty && is_copy(cx, ty),
3877 Self::RefMut => matches_ref(cx, hir::Mutability::Mut, parent_ty, ty),
3878 Self::No => matches_none(cx, parent_ty, ty),
3883 fn description(self) -> &'static str {
3885 Self::Value => "`self` by value",
3886 Self::Ref => "`self` by reference",
3887 Self::RefMut => "`self` by mutable reference",
3888 Self::No => "no `self`",
3893 #[derive(Clone, Copy)]
3902 fn matches(self, ty: &hir::FnRetTy<'_>) -> bool {
3903 let is_unit = |ty: &hir::Ty<'_>| matches!(ty.kind, hir::TyKind::Tup(&[]));
3905 (Self::Unit, &hir::FnRetTy::DefaultReturn(_)) => true,
3906 (Self::Unit, &hir::FnRetTy::Return(ty)) if is_unit(ty) => true,
3907 (Self::Bool, &hir::FnRetTy::Return(ty)) if is_bool(ty) => true,
3908 (Self::Any, &hir::FnRetTy::Return(ty)) if !is_unit(ty) => true,
3909 (Self::Ref, &hir::FnRetTy::Return(ty)) => matches!(ty.kind, hir::TyKind::Rptr(_, _)),
3915 fn is_bool(ty: &hir::Ty<'_>) -> bool {
3916 if let hir::TyKind::Path(QPath::Resolved(_, path)) = ty.kind {
3917 matches!(path.res, Res::PrimTy(PrimTy::Bool))
3923 fn fn_header_equals(expected: hir::FnHeader, actual: hir::FnHeader) -> bool {
3924 expected.constness == actual.constness
3925 && expected.unsafety == actual.unsafety
3926 && expected.asyncness == actual.asyncness