1 mod bind_instead_of_map;
3 mod bytes_count_to_len;
5 mod case_sensitive_file_extension_comparisons;
7 mod chars_cmp_with_unwrap;
9 mod chars_last_cmp_with_unwrap;
11 mod chars_next_cmp_with_unwrap;
14 mod cloned_instead_of_copied;
15 mod collapsible_str_replace;
19 mod extend_with_drain;
22 mod filter_map_identity;
25 mod flat_map_identity;
27 mod from_iter_instead_of_collect;
29 mod get_last_with_len;
32 mod inefficient_to_string;
35 mod is_digit_ascii_radix;
36 mod iter_cloned_collect;
42 mod iter_on_single_or_empty_collections;
43 mod iter_overeager_cloned;
46 mod iterator_step_by_zero;
48 mod manual_saturating_arithmetic;
49 mod manual_str_repeat;
51 mod map_collect_result_unit;
58 mod needless_option_as_deref;
59 mod needless_option_take;
60 mod no_effect_replace;
61 mod obfuscated_if_else;
64 mod option_as_ref_deref;
65 mod option_map_or_none;
66 mod option_map_unwrap_or;
69 mod path_buf_push_overwrite;
70 mod range_zip_with_len;
73 mod seek_from_current;
74 mod seek_to_start_instead_of_rewind;
75 mod single_char_add_str;
76 mod single_char_insert_string;
77 mod single_char_pattern;
78 mod single_char_push_string;
80 mod stable_sort_primitive;
82 mod string_extend_chars;
84 mod suspicious_splitn;
85 mod suspicious_to_owned;
86 mod uninit_assumed_init;
88 mod unnecessary_filter_map;
90 mod unnecessary_iter_cloned;
92 mod unnecessary_lazy_eval;
93 mod unnecessary_sort_by;
94 mod unnecessary_to_owned;
95 mod unwrap_or_else_default;
99 mod vec_resize_to_zero;
100 mod verbose_file_reads;
101 mod wrong_self_convention;
104 use bind_instead_of_map::BindInsteadOfMap;
105 use clippy_utils::consts::{constant, Constant};
106 use clippy_utils::diagnostics::{span_lint, span_lint_and_help};
107 use clippy_utils::msrvs::{self, Msrv};
108 use clippy_utils::ty::{contains_ty_adt_constructor_opaque, implements_trait, is_copy, is_type_diagnostic_item};
109 use clippy_utils::{contains_return, is_bool, is_trait_method, iter_input_pats, return_ty};
110 use if_chain::if_chain;
111 use rustc_hir as hir;
112 use rustc_hir::{Expr, ExprKind, TraitItem, TraitItemKind};
113 use rustc_hir_analysis::hir_ty_to_ty;
114 use rustc_lint::{LateContext, LateLintPass, LintContext};
115 use rustc_middle::lint::in_external_macro;
116 use rustc_middle::ty::{self, TraitRef, Ty};
117 use rustc_session::{declare_tool_lint, impl_lint_pass};
118 use rustc_span::{sym, Span};
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.65.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. This is only bad if it allocates or
835 /// does some non-trivial amount of work.
837 /// ### Known problems
838 /// If the function has side-effects, not calling it will change the
839 /// semantic of the program, but you shouldn't rely on that.
841 /// The lint also cannot figure out whether the function you call is
842 /// actually expensive to call or not.
846 /// # let foo = Some(String::new());
847 /// foo.unwrap_or(String::from("empty"));
852 /// # let foo = Some(String::new());
853 /// foo.unwrap_or_else(|| String::from("empty"));
855 #[clippy::version = "pre 1.29.0"]
858 "using any `*or` method with a function call, which suggests `*or_else`"
861 declare_clippy_lint! {
863 /// Checks for `.or(…).unwrap()` calls to Options and Results.
865 /// ### Why is this bad?
866 /// You should use `.unwrap_or(…)` instead for clarity.
870 /// # let fallback = "fallback";
872 /// # type Error = &'static str;
873 /// # let result: Result<&str, Error> = Err("error");
874 /// let value = result.or::<Error>(Ok(fallback)).unwrap();
877 /// # let option: Option<&str> = None;
878 /// let value = option.or(Some(fallback)).unwrap();
882 /// # let fallback = "fallback";
884 /// # let result: Result<&str, &str> = Err("error");
885 /// let value = result.unwrap_or(fallback);
888 /// # let option: Option<&str> = None;
889 /// let value = option.unwrap_or(fallback);
891 #[clippy::version = "1.61.0"]
894 "checks for `.or(…).unwrap()` calls to Options and Results."
897 declare_clippy_lint! {
899 /// Checks for calls to `.expect(&format!(...))`, `.expect(foo(..))`,
900 /// etc., and suggests to use `unwrap_or_else` instead
902 /// ### Why is this bad?
903 /// The function will always be called.
905 /// ### Known problems
906 /// If the function has side-effects, not calling it will
907 /// change the semantics of the program, but you shouldn't rely on that anyway.
911 /// # let foo = Some(String::new());
912 /// # let err_code = "418";
913 /// # let err_msg = "I'm a teapot";
914 /// foo.expect(&format!("Err {}: {}", err_code, err_msg));
918 /// # let foo = Some(String::new());
919 /// foo.expect(format!("Err {}: {}", err_code, err_msg).as_str());
924 /// # let foo = Some(String::new());
925 /// # let err_code = "418";
926 /// # let err_msg = "I'm a teapot";
927 /// foo.unwrap_or_else(|| panic!("Err {}: {}", err_code, err_msg));
929 #[clippy::version = "pre 1.29.0"]
932 "using any `expect` method with a function call"
935 declare_clippy_lint! {
937 /// Checks for usage of `.clone()` on a `Copy` type.
939 /// ### Why is this bad?
940 /// The only reason `Copy` types implement `Clone` is for
941 /// generics, not for using the `clone` method on a concrete type.
947 #[clippy::version = "pre 1.29.0"]
950 "using `clone` on a `Copy` type"
953 declare_clippy_lint! {
955 /// Checks for usage of `.clone()` on a ref-counted pointer,
956 /// (`Rc`, `Arc`, `rc::Weak`, or `sync::Weak`), and suggests calling Clone via unified
957 /// function syntax instead (e.g., `Rc::clone(foo)`).
959 /// ### Why is this bad?
960 /// Calling '.clone()' on an Rc, Arc, or Weak
961 /// can obscure the fact that only the pointer is being cloned, not the underlying
966 /// # use std::rc::Rc;
967 /// let x = Rc::new(1);
974 /// # use std::rc::Rc;
975 /// # let x = Rc::new(1);
978 #[clippy::version = "pre 1.29.0"]
979 pub CLONE_ON_REF_PTR,
981 "using 'clone' on a ref-counted pointer"
984 declare_clippy_lint! {
986 /// Checks for usage of `.clone()` on an `&&T`.
988 /// ### Why is this bad?
989 /// Cloning an `&&T` copies the inner `&T`, instead of
990 /// cloning the underlying `T`.
997 /// let z = y.clone();
998 /// println!("{:p} {:p}", *y, z); // prints out the same pointer
1001 #[clippy::version = "pre 1.29.0"]
1002 pub CLONE_DOUBLE_REF,
1004 "using `clone` on `&&T`"
1007 declare_clippy_lint! {
1008 /// ### What it does
1009 /// Checks for usage of `.to_string()` on an `&&T` where
1010 /// `T` implements `ToString` directly (like `&&str` or `&&String`).
1012 /// ### Why is this bad?
1013 /// This bypasses the specialized implementation of
1014 /// `ToString` and instead goes through the more expensive string formatting
1019 /// // Generic implementation for `T: Display` is used (slow)
1020 /// ["foo", "bar"].iter().map(|s| s.to_string());
1022 /// // OK, the specialized impl is used
1023 /// ["foo", "bar"].iter().map(|&s| s.to_string());
1025 #[clippy::version = "1.40.0"]
1026 pub INEFFICIENT_TO_STRING,
1028 "using `to_string` on `&&T` where `T: ToString`"
1031 declare_clippy_lint! {
1032 /// ### What it does
1033 /// Checks for `new` not returning a type that contains `Self`.
1035 /// ### Why is this bad?
1036 /// As a convention, `new` methods are used to make a new
1037 /// instance of a type.
1040 /// In an impl block:
1043 /// # struct NotAFoo;
1045 /// fn new() -> NotAFoo {
1053 /// struct Bar(Foo);
1055 /// // Bad. The type name must contain `Self`
1056 /// fn new() -> Bar {
1064 /// # struct FooError;
1066 /// // Good. Return type contains `Self`
1067 /// fn new() -> Result<Foo, FooError> {
1073 /// Or in a trait definition:
1075 /// pub trait Trait {
1076 /// // Bad. The type name must contain `Self`
1082 /// pub trait Trait {
1083 /// // Good. Return type contains `Self`
1084 /// fn new() -> Self;
1087 #[clippy::version = "pre 1.29.0"]
1088 pub NEW_RET_NO_SELF,
1090 "not returning type containing `Self` in a `new` method"
1093 declare_clippy_lint! {
1094 /// ### What it does
1095 /// Checks for string methods that receive a single-character
1096 /// `str` as an argument, e.g., `_.split("x")`.
1098 /// ### Why is this bad?
1099 /// Performing these methods using a `char` is faster than
1102 /// ### Known problems
1103 /// Does not catch multi-byte unicode characters.
1114 #[clippy::version = "pre 1.29.0"]
1115 pub SINGLE_CHAR_PATTERN,
1117 "using a single-character str where a char could be used, e.g., `_.split(\"x\")`"
1120 declare_clippy_lint! {
1121 /// ### What it does
1122 /// Checks for calling `.step_by(0)` on iterators which panics.
1124 /// ### Why is this bad?
1125 /// This very much looks like an oversight. Use `panic!()` instead if you
1126 /// actually intend to panic.
1129 /// ```rust,should_panic
1130 /// for x in (0..100).step_by(0) {
1134 #[clippy::version = "pre 1.29.0"]
1135 pub ITERATOR_STEP_BY_ZERO,
1137 "using `Iterator::step_by(0)`, which will panic at runtime"
1140 declare_clippy_lint! {
1141 /// ### What it does
1142 /// Checks for indirect collection of populated `Option`
1144 /// ### Why is this bad?
1145 /// `Option` is like a collection of 0-1 things, so `flatten`
1146 /// automatically does this without suspicious-looking `unwrap` calls.
1150 /// let _ = std::iter::empty::<Option<i32>>().filter(Option::is_some).map(Option::unwrap);
1154 /// let _ = std::iter::empty::<Option<i32>>().flatten();
1156 #[clippy::version = "1.53.0"]
1157 pub OPTION_FILTER_MAP,
1159 "filtering `Option` for `Some` then force-unwrapping, which can be one type-safe operation"
1162 declare_clippy_lint! {
1163 /// ### What it does
1164 /// Checks for the use of `iter.nth(0)`.
1166 /// ### Why is this bad?
1167 /// `iter.next()` is equivalent to
1168 /// `iter.nth(0)`, as they both consume the next element,
1169 /// but is more readable.
1173 /// # use std::collections::HashSet;
1174 /// # let mut s = HashSet::new();
1176 /// let x = s.iter().nth(0);
1181 /// # use std::collections::HashSet;
1182 /// # let mut s = HashSet::new();
1184 /// let x = s.iter().next();
1186 #[clippy::version = "1.42.0"]
1189 "replace `iter.nth(0)` with `iter.next()`"
1192 declare_clippy_lint! {
1193 /// ### What it does
1194 /// Checks for use of `.iter().nth()` (and the related
1195 /// `.iter_mut().nth()`) on standard library types with *O*(1) element access.
1197 /// ### Why is this bad?
1198 /// `.get()` and `.get_mut()` are more efficient and more
1203 /// let some_vec = vec![0, 1, 2, 3];
1204 /// let bad_vec = some_vec.iter().nth(3);
1205 /// let bad_slice = &some_vec[..].iter().nth(3);
1207 /// The correct use would be:
1209 /// let some_vec = vec![0, 1, 2, 3];
1210 /// let bad_vec = some_vec.get(3);
1211 /// let bad_slice = &some_vec[..].get(3);
1213 #[clippy::version = "pre 1.29.0"]
1216 "using `.iter().nth()` on a standard library type with O(1) element access"
1219 declare_clippy_lint! {
1220 /// ### What it does
1221 /// Checks for use of `.skip(x).next()` on iterators.
1223 /// ### Why is this bad?
1224 /// `.nth(x)` is cleaner
1228 /// let some_vec = vec![0, 1, 2, 3];
1229 /// let bad_vec = some_vec.iter().skip(3).next();
1230 /// let bad_slice = &some_vec[..].iter().skip(3).next();
1232 /// The correct use would be:
1234 /// let some_vec = vec![0, 1, 2, 3];
1235 /// let bad_vec = some_vec.iter().nth(3);
1236 /// let bad_slice = &some_vec[..].iter().nth(3);
1238 #[clippy::version = "pre 1.29.0"]
1241 "using `.skip(x).next()` on an iterator"
1244 declare_clippy_lint! {
1245 /// ### What it does
1246 /// Checks for use of `.drain(..)` on `Vec` and `VecDeque` for iteration.
1248 /// ### Why is this bad?
1249 /// `.into_iter()` is simpler with better performance.
1253 /// # use std::collections::HashSet;
1254 /// let mut foo = vec![0, 1, 2, 3];
1255 /// let bar: HashSet<usize> = foo.drain(..).collect();
1259 /// # use std::collections::HashSet;
1260 /// let foo = vec![0, 1, 2, 3];
1261 /// let bar: HashSet<usize> = foo.into_iter().collect();
1263 #[clippy::version = "1.61.0"]
1264 pub ITER_WITH_DRAIN,
1266 "replace `.drain(..)` with `.into_iter()`"
1269 declare_clippy_lint! {
1270 /// ### What it does
1271 /// Checks for using `x.get(x.len() - 1)` instead of
1274 /// ### Why is this bad?
1275 /// Using `x.last()` is easier to read and has the same
1278 /// Note that using `x[x.len() - 1]` is semantically different from
1279 /// `x.last()`. Indexing into the array will panic on out-of-bounds
1280 /// accesses, while `x.get()` and `x.last()` will return `None`.
1282 /// There is another lint (get_unwrap) that covers the case of using
1283 /// `x.get(index).unwrap()` instead of `x[index]`.
1287 /// let x = vec![2, 3, 5];
1288 /// let last_element = x.get(x.len() - 1);
1293 /// let x = vec![2, 3, 5];
1294 /// let last_element = x.last();
1296 #[clippy::version = "1.37.0"]
1297 pub GET_LAST_WITH_LEN,
1299 "Using `x.get(x.len() - 1)` when `x.last()` is correct and simpler"
1302 declare_clippy_lint! {
1303 /// ### What it does
1304 /// Checks for use of `.get().unwrap()` (or
1305 /// `.get_mut().unwrap`) on a standard library type which implements `Index`
1307 /// ### Why is this bad?
1308 /// Using the Index trait (`[]`) is more clear and more
1311 /// ### Known problems
1312 /// Not a replacement for error handling: Using either
1313 /// `.unwrap()` or the Index trait (`[]`) carries the risk of causing a `panic`
1314 /// if the value being accessed is `None`. If the use of `.get().unwrap()` is a
1315 /// temporary placeholder for dealing with the `Option` type, then this does
1316 /// not mitigate the need for error handling. If there is a chance that `.get()`
1317 /// will be `None` in your program, then it is advisable that the `None` case
1318 /// is handled in a future refactor instead of using `.unwrap()` or the Index
1323 /// let mut some_vec = vec![0, 1, 2, 3];
1324 /// let last = some_vec.get(3).unwrap();
1325 /// *some_vec.get_mut(0).unwrap() = 1;
1327 /// The correct use would be:
1329 /// let mut some_vec = vec![0, 1, 2, 3];
1330 /// let last = some_vec[3];
1331 /// some_vec[0] = 1;
1333 #[clippy::version = "pre 1.29.0"]
1336 "using `.get().unwrap()` or `.get_mut().unwrap()` when using `[]` would work instead"
1339 declare_clippy_lint! {
1340 /// ### What it does
1341 /// Checks for occurrences where one vector gets extended instead of append
1343 /// ### Why is this bad?
1344 /// Using `append` instead of `extend` is more concise and faster
1348 /// let mut a = vec![1, 2, 3];
1349 /// let mut b = vec![4, 5, 6];
1351 /// a.extend(b.drain(..));
1356 /// let mut a = vec![1, 2, 3];
1357 /// let mut b = vec![4, 5, 6];
1359 /// a.append(&mut b);
1361 #[clippy::version = "1.55.0"]
1362 pub EXTEND_WITH_DRAIN,
1364 "using vec.append(&mut vec) to move the full range of a vector to another"
1367 declare_clippy_lint! {
1368 /// ### What it does
1369 /// Checks for the use of `.extend(s.chars())` where s is a
1370 /// `&str` or `String`.
1372 /// ### Why is this bad?
1373 /// `.push_str(s)` is clearer
1377 /// let abc = "abc";
1378 /// let def = String::from("def");
1379 /// let mut s = String::new();
1380 /// s.extend(abc.chars());
1381 /// s.extend(def.chars());
1383 /// The correct use would be:
1385 /// let abc = "abc";
1386 /// let def = String::from("def");
1387 /// let mut s = String::new();
1388 /// s.push_str(abc);
1389 /// s.push_str(&def);
1391 #[clippy::version = "pre 1.29.0"]
1392 pub STRING_EXTEND_CHARS,
1394 "using `x.extend(s.chars())` where s is a `&str` or `String`"
1397 declare_clippy_lint! {
1398 /// ### What it does
1399 /// Checks for the use of `.cloned().collect()` on slice to
1402 /// ### Why is this bad?
1403 /// `.to_vec()` is clearer
1407 /// let s = [1, 2, 3, 4, 5];
1408 /// let s2: Vec<isize> = s[..].iter().cloned().collect();
1410 /// The better use would be:
1412 /// let s = [1, 2, 3, 4, 5];
1413 /// let s2: Vec<isize> = s.to_vec();
1415 #[clippy::version = "pre 1.29.0"]
1416 pub ITER_CLONED_COLLECT,
1418 "using `.cloned().collect()` on slice to create a `Vec`"
1421 declare_clippy_lint! {
1422 /// ### What it does
1423 /// Checks for usage of `_.chars().last()` or
1424 /// `_.chars().next_back()` on a `str` to check if it ends with a given char.
1426 /// ### Why is this bad?
1427 /// Readability, this can be written more concisely as
1428 /// `_.ends_with(_)`.
1432 /// # let name = "_";
1433 /// name.chars().last() == Some('_') || name.chars().next_back() == Some('-');
1438 /// # let name = "_";
1439 /// name.ends_with('_') || name.ends_with('-');
1441 #[clippy::version = "pre 1.29.0"]
1444 "using `.chars().last()` or `.chars().next_back()` to check if a string ends with a char"
1447 declare_clippy_lint! {
1448 /// ### What it does
1449 /// Checks for usage of `.as_ref()` or `.as_mut()` where the
1450 /// types before and after the call are the same.
1452 /// ### Why is this bad?
1453 /// The call is unnecessary.
1457 /// # fn do_stuff(x: &[i32]) {}
1458 /// let x: &[i32] = &[1, 2, 3, 4, 5];
1459 /// do_stuff(x.as_ref());
1461 /// The correct use would be:
1463 /// # fn do_stuff(x: &[i32]) {}
1464 /// let x: &[i32] = &[1, 2, 3, 4, 5];
1467 #[clippy::version = "pre 1.29.0"]
1470 "using `as_ref` where the types before and after the call are the same"
1473 declare_clippy_lint! {
1474 /// ### What it does
1475 /// Checks for using `fold` when a more succinct alternative exists.
1476 /// Specifically, this checks for `fold`s which could be replaced by `any`, `all`,
1477 /// `sum` or `product`.
1479 /// ### Why is this bad?
1484 /// # #[allow(unused)]
1485 /// (0..3).fold(false, |acc, x| acc || x > 2);
1490 /// (0..3).any(|x| x > 2);
1492 #[clippy::version = "pre 1.29.0"]
1493 pub UNNECESSARY_FOLD,
1495 "using `fold` when a more succinct alternative exists"
1498 declare_clippy_lint! {
1499 /// ### What it does
1500 /// Checks for `filter_map` calls that could be replaced by `filter` or `map`.
1501 /// More specifically it checks if the closure provided is only performing one of the
1502 /// filter or map operations and suggests the appropriate option.
1504 /// ### Why is this bad?
1505 /// Complexity. The intent is also clearer if only a single
1506 /// operation is being performed.
1510 /// let _ = (0..3).filter_map(|x| if x > 2 { Some(x) } else { None });
1512 /// // As there is no transformation of the argument this could be written as:
1513 /// let _ = (0..3).filter(|&x| x > 2);
1517 /// let _ = (0..4).filter_map(|x| Some(x + 1));
1519 /// // As there is no conditional check on the argument this could be written as:
1520 /// let _ = (0..4).map(|x| x + 1);
1522 #[clippy::version = "1.31.0"]
1523 pub UNNECESSARY_FILTER_MAP,
1525 "using `filter_map` when a more succinct alternative exists"
1528 declare_clippy_lint! {
1529 /// ### What it does
1530 /// Checks for `find_map` calls that could be replaced by `find` or `map`. More
1531 /// specifically it checks if the closure provided is only performing one of the
1532 /// find or map operations and suggests the appropriate option.
1534 /// ### Why is this bad?
1535 /// Complexity. The intent is also clearer if only a single
1536 /// operation is being performed.
1540 /// let _ = (0..3).find_map(|x| if x > 2 { Some(x) } else { None });
1542 /// // As there is no transformation of the argument this could be written as:
1543 /// let _ = (0..3).find(|&x| x > 2);
1547 /// let _ = (0..4).find_map(|x| Some(x + 1));
1549 /// // As there is no conditional check on the argument this could be written as:
1550 /// let _ = (0..4).map(|x| x + 1).next();
1552 #[clippy::version = "1.61.0"]
1553 pub UNNECESSARY_FIND_MAP,
1555 "using `find_map` when a more succinct alternative exists"
1558 declare_clippy_lint! {
1559 /// ### What it does
1560 /// Checks for `into_iter` calls on references which should be replaced by `iter`
1563 /// ### Why is this bad?
1564 /// Readability. Calling `into_iter` on a reference will not move out its
1565 /// content into the resulting iterator, which is confusing. It is better just call `iter` or
1566 /// `iter_mut` directly.
1570 /// # let vec = vec![3, 4, 5];
1571 /// (&vec).into_iter();
1576 /// # let vec = vec![3, 4, 5];
1579 #[clippy::version = "1.32.0"]
1580 pub INTO_ITER_ON_REF,
1582 "using `.into_iter()` on a reference"
1585 declare_clippy_lint! {
1586 /// ### What it does
1587 /// Checks for calls to `map` followed by a `count`.
1589 /// ### Why is this bad?
1590 /// It looks suspicious. Maybe `map` was confused with `filter`.
1591 /// If the `map` call is intentional, this should be rewritten
1592 /// using `inspect`. Or, if you intend to drive the iterator to
1593 /// completion, you can just use `for_each` instead.
1597 /// let _ = (0..3).map(|x| x + 2).count();
1599 #[clippy::version = "1.39.0"]
1602 "suspicious usage of map"
1605 declare_clippy_lint! {
1606 /// ### What it does
1607 /// Checks for `MaybeUninit::uninit().assume_init()`.
1609 /// ### Why is this bad?
1610 /// For most types, this is undefined behavior.
1612 /// ### Known problems
1613 /// For now, we accept empty tuples and tuples / arrays
1614 /// of `MaybeUninit`. There may be other types that allow uninitialized
1615 /// data, but those are not yet rigorously defined.
1619 /// // Beware the UB
1620 /// use std::mem::MaybeUninit;
1622 /// let _: usize = unsafe { MaybeUninit::uninit().assume_init() };
1625 /// Note that the following is OK:
1628 /// use std::mem::MaybeUninit;
1630 /// let _: [MaybeUninit<bool>; 5] = unsafe {
1631 /// MaybeUninit::uninit().assume_init()
1634 #[clippy::version = "1.39.0"]
1635 pub UNINIT_ASSUMED_INIT,
1637 "`MaybeUninit::uninit().assume_init()`"
1640 declare_clippy_lint! {
1641 /// ### What it does
1642 /// Checks for `.checked_add/sub(x).unwrap_or(MAX/MIN)`.
1644 /// ### Why is this bad?
1645 /// These can be written simply with `saturating_add/sub` methods.
1649 /// # let y: u32 = 0;
1650 /// # let x: u32 = 100;
1651 /// let add = x.checked_add(y).unwrap_or(u32::MAX);
1652 /// let sub = x.checked_sub(y).unwrap_or(u32::MIN);
1655 /// can be written using dedicated methods for saturating addition/subtraction as:
1658 /// # let y: u32 = 0;
1659 /// # let x: u32 = 100;
1660 /// let add = x.saturating_add(y);
1661 /// let sub = x.saturating_sub(y);
1663 #[clippy::version = "1.39.0"]
1664 pub MANUAL_SATURATING_ARITHMETIC,
1666 "`.checked_add/sub(x).unwrap_or(MAX/MIN)`"
1669 declare_clippy_lint! {
1670 /// ### What it does
1671 /// Checks for `offset(_)`, `wrapping_`{`add`, `sub`}, etc. on raw pointers to
1672 /// zero-sized types
1674 /// ### Why is this bad?
1675 /// This is a no-op, and likely unintended
1679 /// unsafe { (&() as *const ()).offset(1) };
1681 #[clippy::version = "1.41.0"]
1684 "Check for offset calculations on raw pointers to zero-sized types"
1687 declare_clippy_lint! {
1688 /// ### What it does
1689 /// Checks for `FileType::is_file()`.
1691 /// ### Why is this bad?
1692 /// When people testing a file type with `FileType::is_file`
1693 /// they are testing whether a path is something they can get bytes from. But
1694 /// `is_file` doesn't cover special file types in unix-like systems, and doesn't cover
1695 /// symlink in windows. Using `!FileType::is_dir()` is a better way to that intention.
1700 /// let metadata = std::fs::metadata("foo.txt")?;
1701 /// let filetype = metadata.file_type();
1703 /// if filetype.is_file() {
1706 /// # Ok::<_, std::io::Error>(())
1710 /// should be written as:
1714 /// let metadata = std::fs::metadata("foo.txt")?;
1715 /// let filetype = metadata.file_type();
1717 /// if !filetype.is_dir() {
1720 /// # Ok::<_, std::io::Error>(())
1723 #[clippy::version = "1.42.0"]
1724 pub FILETYPE_IS_FILE,
1726 "`FileType::is_file` is not recommended to test for readable file type"
1729 declare_clippy_lint! {
1730 /// ### What it does
1731 /// Checks for usage of `_.as_ref().map(Deref::deref)` or its aliases (such as String::as_str).
1733 /// ### Why is this bad?
1734 /// Readability, this can be written more concisely as
1739 /// # let opt = Some("".to_string());
1740 /// opt.as_ref().map(String::as_str)
1743 /// Can be written as
1745 /// # let opt = Some("".to_string());
1749 #[clippy::version = "1.42.0"]
1750 pub OPTION_AS_REF_DEREF,
1752 "using `as_ref().map(Deref::deref)`, which is more succinctly expressed as `as_deref()`"
1755 declare_clippy_lint! {
1756 /// ### What it does
1757 /// Checks for usage of `iter().next()` on a Slice or an Array
1759 /// ### Why is this bad?
1760 /// These can be shortened into `.get()`
1764 /// # let a = [1, 2, 3];
1765 /// # let b = vec![1, 2, 3];
1766 /// a[2..].iter().next();
1767 /// b.iter().next();
1769 /// should be written as:
1771 /// # let a = [1, 2, 3];
1772 /// # let b = vec![1, 2, 3];
1776 #[clippy::version = "1.46.0"]
1777 pub ITER_NEXT_SLICE,
1779 "using `.iter().next()` on a sliced array, which can be shortened to just `.get()`"
1782 declare_clippy_lint! {
1783 /// ### What it does
1784 /// Warns when using `push_str`/`insert_str` with a single-character string literal
1785 /// where `push`/`insert` with a `char` would work fine.
1787 /// ### Why is this bad?
1788 /// It's less clear that we are pushing a single character.
1792 /// # let mut string = String::new();
1793 /// string.insert_str(0, "R");
1794 /// string.push_str("R");
1799 /// # let mut string = String::new();
1800 /// string.insert(0, 'R');
1801 /// string.push('R');
1803 #[clippy::version = "1.49.0"]
1804 pub SINGLE_CHAR_ADD_STR,
1806 "`push_str()` or `insert_str()` used with a single-character string literal as parameter"
1809 declare_clippy_lint! {
1810 /// ### What it does
1811 /// As the counterpart to `or_fun_call`, this lint looks for unnecessary
1812 /// lazily evaluated closures on `Option` and `Result`.
1814 /// This lint suggests changing the following functions, when eager evaluation results in
1816 /// - `unwrap_or_else` to `unwrap_or`
1817 /// - `and_then` to `and`
1818 /// - `or_else` to `or`
1819 /// - `get_or_insert_with` to `get_or_insert`
1820 /// - `ok_or_else` to `ok_or`
1822 /// ### Why is this bad?
1823 /// Using eager evaluation is shorter and simpler in some cases.
1825 /// ### Known problems
1826 /// It is possible, but not recommended for `Deref` and `Index` to have
1827 /// side effects. Eagerly evaluating them can change the semantics of the program.
1831 /// // example code where clippy issues a warning
1832 /// let opt: Option<u32> = None;
1834 /// opt.unwrap_or_else(|| 42);
1838 /// let opt: Option<u32> = None;
1840 /// opt.unwrap_or(42);
1842 #[clippy::version = "1.48.0"]
1843 pub UNNECESSARY_LAZY_EVALUATIONS,
1845 "using unnecessary lazy evaluation, which can be replaced with simpler eager evaluation"
1848 declare_clippy_lint! {
1849 /// ### What it does
1850 /// Checks for usage of `_.map(_).collect::<Result<(), _>()`.
1852 /// ### Why is this bad?
1853 /// Using `try_for_each` instead is more readable and idiomatic.
1857 /// (0..3).map(|t| Err(t)).collect::<Result<(), _>>();
1861 /// (0..3).try_for_each(|t| Err(t));
1863 #[clippy::version = "1.49.0"]
1864 pub MAP_COLLECT_RESULT_UNIT,
1866 "using `.map(_).collect::<Result<(),_>()`, which can be replaced with `try_for_each`"
1869 declare_clippy_lint! {
1870 /// ### What it does
1871 /// Checks for `from_iter()` function calls on types that implement the `FromIterator`
1874 /// ### Why is this bad?
1875 /// It is recommended style to use collect. See
1876 /// [FromIterator documentation](https://doc.rust-lang.org/std/iter/trait.FromIterator.html)
1880 /// let five_fives = std::iter::repeat(5).take(5);
1882 /// let v = Vec::from_iter(five_fives);
1884 /// assert_eq!(v, vec![5, 5, 5, 5, 5]);
1888 /// let five_fives = std::iter::repeat(5).take(5);
1890 /// let v: Vec<i32> = five_fives.collect();
1892 /// assert_eq!(v, vec![5, 5, 5, 5, 5]);
1894 #[clippy::version = "1.49.0"]
1895 pub FROM_ITER_INSTEAD_OF_COLLECT,
1897 "use `.collect()` instead of `::from_iter()`"
1900 declare_clippy_lint! {
1901 /// ### What it does
1902 /// Checks for usage of `inspect().for_each()`.
1904 /// ### Why is this bad?
1905 /// It is the same as performing the computation
1906 /// inside `inspect` at the beginning of the closure in `for_each`.
1910 /// [1,2,3,4,5].iter()
1911 /// .inspect(|&x| println!("inspect the number: {}", x))
1912 /// .for_each(|&x| {
1913 /// assert!(x >= 0);
1916 /// Can be written as
1918 /// [1,2,3,4,5].iter()
1919 /// .for_each(|&x| {
1920 /// println!("inspect the number: {}", x);
1921 /// assert!(x >= 0);
1924 #[clippy::version = "1.51.0"]
1925 pub INSPECT_FOR_EACH,
1927 "using `.inspect().for_each()`, which can be replaced with `.for_each()`"
1930 declare_clippy_lint! {
1931 /// ### What it does
1932 /// Checks for usage of `filter_map(|x| x)`.
1934 /// ### Why is this bad?
1935 /// Readability, this can be written more concisely by using `flatten`.
1939 /// # let iter = vec![Some(1)].into_iter();
1940 /// iter.filter_map(|x| x);
1944 /// # let iter = vec![Some(1)].into_iter();
1947 #[clippy::version = "1.52.0"]
1948 pub FILTER_MAP_IDENTITY,
1950 "call to `filter_map` where `flatten` is sufficient"
1953 declare_clippy_lint! {
1954 /// ### What it does
1955 /// Checks for instances of `map(f)` where `f` is the identity function.
1957 /// ### Why is this bad?
1958 /// It can be written more concisely without the call to `map`.
1962 /// let x = [1, 2, 3];
1963 /// let y: Vec<_> = x.iter().map(|x| x).map(|x| 2*x).collect();
1967 /// let x = [1, 2, 3];
1968 /// let y: Vec<_> = x.iter().map(|x| 2*x).collect();
1970 #[clippy::version = "1.47.0"]
1973 "using iterator.map(|x| x)"
1976 declare_clippy_lint! {
1977 /// ### What it does
1978 /// Checks for the use of `.bytes().nth()`.
1980 /// ### Why is this bad?
1981 /// `.as_bytes().get()` is more efficient and more
1986 /// # #[allow(unused)]
1987 /// "Hello".bytes().nth(3);
1992 /// # #[allow(unused)]
1993 /// "Hello".as_bytes().get(3);
1995 #[clippy::version = "1.52.0"]
1998 "replace `.bytes().nth()` with `.as_bytes().get()`"
2001 declare_clippy_lint! {
2002 /// ### What it does
2003 /// Checks for the usage of `_.to_owned()`, `vec.to_vec()`, or similar when calling `_.clone()` would be clearer.
2005 /// ### Why is this bad?
2006 /// These methods do the same thing as `_.clone()` but may be confusing as
2007 /// to why we are calling `to_vec` on something that is already a `Vec` or calling `to_owned` on something that is already owned.
2011 /// let a = vec![1, 2, 3];
2012 /// let b = a.to_vec();
2013 /// let c = a.to_owned();
2017 /// let a = vec![1, 2, 3];
2018 /// let b = a.clone();
2019 /// let c = a.clone();
2021 #[clippy::version = "1.52.0"]
2024 "implicitly cloning a value by invoking a function on its dereferenced type"
2027 declare_clippy_lint! {
2028 /// ### What it does
2029 /// Checks for the use of `.iter().count()`.
2031 /// ### Why is this bad?
2032 /// `.len()` is more efficient and more
2037 /// # #![allow(unused)]
2038 /// let some_vec = vec![0, 1, 2, 3];
2040 /// some_vec.iter().count();
2041 /// &some_vec[..].iter().count();
2046 /// let some_vec = vec![0, 1, 2, 3];
2049 /// &some_vec[..].len();
2051 #[clippy::version = "1.52.0"]
2054 "replace `.iter().count()` with `.len()`"
2057 declare_clippy_lint! {
2058 /// ### What it does
2059 /// Checks for the usage of `_.to_owned()`, on a `Cow<'_, _>`.
2061 /// ### Why is this bad?
2062 /// Calling `to_owned()` on a `Cow` creates a clone of the `Cow`
2063 /// itself, without taking ownership of the `Cow` contents (i.e.
2064 /// it's equivalent to calling `Cow::clone`).
2065 /// The similarly named `into_owned` method, on the other hand,
2066 /// clones the `Cow` contents, effectively turning any `Cow::Borrowed`
2067 /// into a `Cow::Owned`.
2069 /// Given the potential ambiguity, consider replacing `to_owned`
2070 /// with `clone` for better readability or, if getting a `Cow::Owned`
2071 /// was the original intent, using `into_owned` instead.
2075 /// # use std::borrow::Cow;
2076 /// let s = "Hello world!";
2077 /// let cow = Cow::Borrowed(s);
2079 /// let data = cow.to_owned();
2080 /// assert!(matches!(data, Cow::Borrowed(_)))
2084 /// # use std::borrow::Cow;
2085 /// let s = "Hello world!";
2086 /// let cow = Cow::Borrowed(s);
2088 /// let data = cow.clone();
2089 /// assert!(matches!(data, Cow::Borrowed(_)))
2093 /// # use std::borrow::Cow;
2094 /// let s = "Hello world!";
2095 /// let cow = Cow::Borrowed(s);
2097 /// let _data: String = cow.into_owned();
2099 #[clippy::version = "1.65.0"]
2100 pub SUSPICIOUS_TO_OWNED,
2102 "calls to `to_owned` on a `Cow<'_, _>` might not do what they are expected"
2105 declare_clippy_lint! {
2106 /// ### What it does
2107 /// Checks for calls to [`splitn`]
2108 /// (https://doc.rust-lang.org/std/primitive.str.html#method.splitn) and
2109 /// related functions with either zero or one splits.
2111 /// ### Why is this bad?
2112 /// These calls don't actually split the value and are
2113 /// likely to be intended as a different number.
2118 /// for x in s.splitn(1, ":") {
2126 /// for x in s.splitn(2, ":") {
2130 #[clippy::version = "1.54.0"]
2131 pub SUSPICIOUS_SPLITN,
2133 "checks for `.splitn(0, ..)` and `.splitn(1, ..)`"
2136 declare_clippy_lint! {
2137 /// ### What it does
2138 /// Checks for manual implementations of `str::repeat`
2140 /// ### Why is this bad?
2141 /// These are both harder to read, as well as less performant.
2145 /// let x: String = std::iter::repeat('x').take(10).collect();
2150 /// let x: String = "x".repeat(10);
2152 #[clippy::version = "1.54.0"]
2153 pub MANUAL_STR_REPEAT,
2155 "manual implementation of `str::repeat`"
2158 declare_clippy_lint! {
2159 /// ### What it does
2160 /// Checks for usages of `str::splitn(2, _)`
2162 /// ### Why is this bad?
2163 /// `split_once` is both clearer in intent and slightly more efficient.
2167 /// let s = "key=value=add";
2168 /// let (key, value) = s.splitn(2, '=').next_tuple()?;
2169 /// let value = s.splitn(2, '=').nth(1)?;
2171 /// let mut parts = s.splitn(2, '=');
2172 /// let key = parts.next()?;
2173 /// let value = parts.next()?;
2178 /// let s = "key=value=add";
2179 /// let (key, value) = s.split_once('=')?;
2180 /// let value = s.split_once('=')?.1;
2182 /// let (key, value) = s.split_once('=')?;
2186 /// The multiple statement variant currently only detects `iter.next()?`/`iter.next().unwrap()`
2187 /// in two separate `let` statements that immediately follow the `splitn()`
2188 #[clippy::version = "1.57.0"]
2189 pub MANUAL_SPLIT_ONCE,
2191 "replace `.splitn(2, pat)` with `.split_once(pat)`"
2194 declare_clippy_lint! {
2195 /// ### What it does
2196 /// Checks for usages of `str::splitn` (or `str::rsplitn`) where using `str::split` would be the same.
2197 /// ### Why is this bad?
2198 /// The function `split` is simpler and there is no performance difference in these cases, considering
2199 /// that both functions return a lazy iterator.
2202 /// let str = "key=value=add";
2203 /// let _ = str.splitn(3, '=').next().unwrap();
2208 /// let str = "key=value=add";
2209 /// let _ = str.split('=').next().unwrap();
2211 #[clippy::version = "1.59.0"]
2212 pub NEEDLESS_SPLITN,
2214 "usages of `str::splitn` that can be replaced with `str::split`"
2217 declare_clippy_lint! {
2218 /// ### What it does
2219 /// Checks for unnecessary calls to [`ToOwned::to_owned`](https://doc.rust-lang.org/std/borrow/trait.ToOwned.html#tymethod.to_owned)
2220 /// and other `to_owned`-like functions.
2222 /// ### Why is this bad?
2223 /// The unnecessary calls result in useless allocations.
2225 /// ### Known problems
2226 /// `unnecessary_to_owned` can falsely trigger if `IntoIterator::into_iter` is applied to an
2227 /// owned copy of a resource and the resource is later used mutably. See
2228 /// [#8148](https://github.com/rust-lang/rust-clippy/issues/8148).
2232 /// let path = std::path::Path::new("x");
2233 /// foo(&path.to_string_lossy().to_string());
2234 /// fn foo(s: &str) {}
2238 /// let path = std::path::Path::new("x");
2239 /// foo(&path.to_string_lossy());
2240 /// fn foo(s: &str) {}
2242 #[clippy::version = "1.59.0"]
2243 pub UNNECESSARY_TO_OWNED,
2245 "unnecessary calls to `to_owned`-like functions"
2248 declare_clippy_lint! {
2249 /// ### What it does
2250 /// Checks for use of `.collect::<Vec<String>>().join("")` on iterators.
2252 /// ### Why is this bad?
2253 /// `.collect::<String>()` is more concise and might be more performant
2257 /// let vector = vec!["hello", "world"];
2258 /// let output = vector.iter().map(|item| item.to_uppercase()).collect::<Vec<String>>().join("");
2259 /// println!("{}", output);
2261 /// The correct use would be:
2263 /// let vector = vec!["hello", "world"];
2264 /// let output = vector.iter().map(|item| item.to_uppercase()).collect::<String>();
2265 /// println!("{}", output);
2267 /// ### Known problems
2268 /// While `.collect::<String>()` is sometimes more performant, there are cases where
2269 /// using `.collect::<String>()` over `.collect::<Vec<String>>().join("")`
2270 /// will prevent loop unrolling and will result in a negative performance impact.
2272 /// Additionally, differences have been observed between aarch64 and x86_64 assembly output,
2273 /// with aarch64 tending to producing faster assembly in more cases when using `.collect::<String>()`
2274 #[clippy::version = "1.61.0"]
2275 pub UNNECESSARY_JOIN,
2277 "using `.collect::<Vec<String>>().join(\"\")` on an iterator"
2280 declare_clippy_lint! {
2281 /// ### What it does
2282 /// Checks for no-op uses of `Option::{as_deref, as_deref_mut}`,
2283 /// for example, `Option<&T>::as_deref()` returns the same type.
2285 /// ### Why is this bad?
2286 /// Redundant code and improving readability.
2290 /// let a = Some(&1);
2291 /// let b = a.as_deref(); // goes from Option<&i32> to Option<&i32>
2296 /// let a = Some(&1);
2299 #[clippy::version = "1.57.0"]
2300 pub NEEDLESS_OPTION_AS_DEREF,
2302 "no-op use of `deref` or `deref_mut` method to `Option`."
2305 declare_clippy_lint! {
2306 /// ### What it does
2307 /// Finds usages of [`char::is_digit`](https://doc.rust-lang.org/stable/std/primitive.char.html#method.is_digit) that
2308 /// can be replaced with [`is_ascii_digit`](https://doc.rust-lang.org/stable/std/primitive.char.html#method.is_ascii_digit) or
2309 /// [`is_ascii_hexdigit`](https://doc.rust-lang.org/stable/std/primitive.char.html#method.is_ascii_hexdigit).
2311 /// ### Why is this bad?
2312 /// `is_digit(..)` is slower and requires specifying the radix.
2316 /// let c: char = '6';
2322 /// let c: char = '6';
2323 /// c.is_ascii_digit();
2324 /// c.is_ascii_hexdigit();
2326 #[clippy::version = "1.62.0"]
2327 pub IS_DIGIT_ASCII_RADIX,
2329 "use of `char::is_digit(..)` with literal radix of 10 or 16"
2332 declare_clippy_lint! {
2333 /// ### What it does
2334 /// Checks for calling `take` function after `as_ref`.
2336 /// ### Why is this bad?
2337 /// Redundant code. `take` writes `None` to its argument.
2338 /// In this case the modification is useless as it's a temporary that cannot be read from afterwards.
2342 /// let x = Some(3);
2343 /// x.as_ref().take();
2347 /// let x = Some(3);
2350 #[clippy::version = "1.62.0"]
2351 pub NEEDLESS_OPTION_TAKE,
2353 "using `.as_ref().take()` on a temporary value"
2356 declare_clippy_lint! {
2357 /// ### What it does
2358 /// Checks for `replace` statements which have no effect.
2360 /// ### Why is this bad?
2361 /// It's either a mistake or confusing.
2365 /// "1234".replace("12", "12");
2366 /// "1234".replacen("12", "12", 1);
2368 #[clippy::version = "1.63.0"]
2369 pub NO_EFFECT_REPLACE,
2371 "replace with no effect"
2374 declare_clippy_lint! {
2375 /// ### What it does
2376 /// Checks for usages of `.then_some(..).unwrap_or(..)`
2378 /// ### Why is this bad?
2379 /// This can be written more clearly with `if .. else ..`
2382 /// This lint currently only looks for usages of
2383 /// `.then_some(..).unwrap_or(..)`, but will be expanded
2384 /// to account for similar patterns.
2389 /// x.then_some("a").unwrap_or("b");
2394 /// if x { "a" } else { "b" };
2396 #[clippy::version = "1.64.0"]
2397 pub OBFUSCATED_IF_ELSE,
2399 "use of `.then_some(..).unwrap_or(..)` can be written \
2400 more clearly with `if .. else ..`"
2403 declare_clippy_lint! {
2404 /// ### What it does
2406 /// Checks for calls to `iter`, `iter_mut` or `into_iter` on collections containing a single item
2408 /// ### Why is this bad?
2410 /// It is simpler to use the once function from the standard library:
2415 /// let a = [123].iter();
2416 /// let b = Some(123).into_iter();
2421 /// let a = iter::once(&123);
2422 /// let b = iter::once(123);
2425 /// ### Known problems
2427 /// The type of the resulting iterator might become incompatible with its usage
2428 #[clippy::version = "1.65.0"]
2429 pub ITER_ON_SINGLE_ITEMS,
2431 "Iterator for array of length 1"
2434 declare_clippy_lint! {
2435 /// ### What it does
2437 /// Checks for calls to `iter`, `iter_mut` or `into_iter` on empty collections
2439 /// ### Why is this bad?
2441 /// It is simpler to use the empty function from the standard library:
2446 /// use std::{slice, option};
2447 /// let a: slice::Iter<i32> = [].iter();
2448 /// let f: option::IntoIter<i32> = None.into_iter();
2453 /// let a: iter::Empty<i32> = iter::empty();
2454 /// let b: iter::Empty<i32> = iter::empty();
2457 /// ### Known problems
2459 /// The type of the resulting iterator might become incompatible with its usage
2460 #[clippy::version = "1.65.0"]
2461 pub ITER_ON_EMPTY_COLLECTIONS,
2463 "Iterator for empty array"
2466 declare_clippy_lint! {
2467 /// ### What it does
2468 /// Checks for naive byte counts
2470 /// ### Why is this bad?
2471 /// The [`bytecount`](https://crates.io/crates/bytecount)
2472 /// crate has methods to count your bytes faster, especially for large slices.
2474 /// ### Known problems
2475 /// If you have predominantly small slices, the
2476 /// `bytecount::count(..)` method may actually be slower. However, if you can
2477 /// ensure that less than 2³²-1 matches arise, the `naive_count_32(..)` can be
2478 /// faster in those cases.
2482 /// # let vec = vec![1_u8];
2483 /// let count = vec.iter().filter(|x| **x == 0u8).count();
2488 /// # let vec = vec![1_u8];
2489 /// let count = bytecount::count(&vec, 0u8);
2491 #[clippy::version = "pre 1.29.0"]
2492 pub NAIVE_BYTECOUNT,
2494 "use of naive `<slice>.filter(|&x| x == y).count()` to count byte values"
2497 declare_clippy_lint! {
2498 /// ### What it does
2499 /// It checks for `str::bytes().count()` and suggests replacing it with
2502 /// ### Why is this bad?
2503 /// `str::bytes().count()` is longer and may not be as performant as using
2508 /// "hello".bytes().count();
2509 /// String::from("hello").bytes().count();
2514 /// String::from("hello").len();
2516 #[clippy::version = "1.62.0"]
2517 pub BYTES_COUNT_TO_LEN,
2519 "Using `bytes().count()` when `len()` performs the same functionality"
2522 declare_clippy_lint! {
2523 /// ### What it does
2524 /// Checks for calls to `ends_with` with possible file extensions
2525 /// and suggests to use a case-insensitive approach instead.
2527 /// ### Why is this bad?
2528 /// `ends_with` is case-sensitive and may not detect files with a valid extension.
2532 /// fn is_rust_file(filename: &str) -> bool {
2533 /// filename.ends_with(".rs")
2538 /// fn is_rust_file(filename: &str) -> bool {
2539 /// let filename = std::path::Path::new(filename);
2540 /// filename.extension()
2541 /// .map_or(false, |ext| ext.eq_ignore_ascii_case("rs"))
2544 #[clippy::version = "1.51.0"]
2545 pub CASE_SENSITIVE_FILE_EXTENSION_COMPARISONS,
2547 "Checks for calls to ends_with with case-sensitive file extensions"
2550 declare_clippy_lint! {
2551 /// ### What it does
2552 /// Checks for using `x.get(0)` instead of
2555 /// ### Why is this bad?
2556 /// Using `x.first()` is easier to read and has the same
2561 /// let x = vec![2, 3, 5];
2562 /// let first_element = x.get(0);
2567 /// let x = vec![2, 3, 5];
2568 /// let first_element = x.first();
2570 #[clippy::version = "1.63.0"]
2573 "Using `x.get(0)` when `x.first()` is simpler"
2576 declare_clippy_lint! {
2577 /// ### What it does
2579 /// Finds patterns that reimplement `Option::ok_or`.
2581 /// ### Why is this bad?
2583 /// Concise code helps focusing on behavior instead of boilerplate.
2587 /// let foo: Option<i32> = None;
2588 /// foo.map_or(Err("error"), |v| Ok(v));
2593 /// let foo: Option<i32> = None;
2594 /// foo.ok_or("error");
2596 #[clippy::version = "1.49.0"]
2599 "finds patterns that can be encoded more concisely with `Option::ok_or`"
2602 declare_clippy_lint! {
2603 /// ### What it does
2604 /// Checks for usage of `map(|x| x.clone())` or
2605 /// dereferencing closures for `Copy` types, on `Iterator` or `Option`,
2606 /// and suggests `cloned()` or `copied()` instead
2608 /// ### Why is this bad?
2609 /// Readability, this can be written more concisely
2613 /// let x = vec![42, 43];
2614 /// let y = x.iter();
2615 /// let z = y.map(|i| *i);
2618 /// The correct use would be:
2621 /// let x = vec![42, 43];
2622 /// let y = x.iter();
2623 /// let z = y.cloned();
2625 #[clippy::version = "pre 1.29.0"]
2628 "using `iterator.map(|x| x.clone())`, or dereferencing closures for `Copy` types"
2631 declare_clippy_lint! {
2632 /// ### What it does
2633 /// Checks for instances of `map_err(|_| Some::Enum)`
2635 /// ### Why is this bad?
2636 /// This `map_err` throws away the original error rather than allowing the enum to contain and report the cause of the error
2643 /// #[derive(Debug)]
2649 /// impl fmt::Display for Error {
2650 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2652 /// Error::Indivisible => write!(f, "could not divide input by three"),
2653 /// Error::Remainder(remainder) => write!(
2655 /// "input is not divisible by three, remainder = {}",
2662 /// impl std::error::Error for Error {}
2664 /// fn divisible_by_3(input: &str) -> Result<(), Error> {
2667 /// .map_err(|_| Error::Indivisible)
2669 /// .and_then(|remainder| {
2670 /// if remainder == 0 {
2673 /// Err(Error::Remainder(remainder as u8))
2681 /// use std::{fmt, num::ParseIntError};
2683 /// #[derive(Debug)]
2685 /// Indivisible(ParseIntError),
2689 /// impl fmt::Display for Error {
2690 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2692 /// Error::Indivisible(_) => write!(f, "could not divide input by three"),
2693 /// Error::Remainder(remainder) => write!(
2695 /// "input is not divisible by three, remainder = {}",
2702 /// impl std::error::Error for Error {
2703 /// fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
2705 /// Error::Indivisible(source) => Some(source),
2711 /// fn divisible_by_3(input: &str) -> Result<(), Error> {
2714 /// .map_err(Error::Indivisible)
2716 /// .and_then(|remainder| {
2717 /// if remainder == 0 {
2720 /// Err(Error::Remainder(remainder as u8))
2725 #[clippy::version = "1.48.0"]
2728 "`map_err` should not ignore the original error"
2731 declare_clippy_lint! {
2732 /// ### What it does
2733 /// Checks for `&mut Mutex::lock` calls
2735 /// ### Why is this bad?
2736 /// `Mutex::lock` is less efficient than
2737 /// calling `Mutex::get_mut`. In addition you also have a statically
2738 /// guarantee that the mutex isn't locked, instead of just a runtime
2743 /// use std::sync::{Arc, Mutex};
2745 /// let mut value_rc = Arc::new(Mutex::new(42_u8));
2746 /// let value_mutex = Arc::get_mut(&mut value_rc).unwrap();
2748 /// let mut value = value_mutex.lock().unwrap();
2753 /// use std::sync::{Arc, Mutex};
2755 /// let mut value_rc = Arc::new(Mutex::new(42_u8));
2756 /// let value_mutex = Arc::get_mut(&mut value_rc).unwrap();
2758 /// let value = value_mutex.get_mut().unwrap();
2761 #[clippy::version = "1.49.0"]
2764 "`&mut Mutex::lock` does unnecessary locking"
2767 declare_clippy_lint! {
2768 /// ### What it does
2769 /// Checks for duplicate open options as well as combinations
2770 /// that make no sense.
2772 /// ### Why is this bad?
2773 /// In the best case, the code will be harder to read than
2774 /// necessary. I don't know the worst case.
2778 /// use std::fs::OpenOptions;
2780 /// OpenOptions::new().read(true).truncate(true);
2782 #[clippy::version = "pre 1.29.0"]
2783 pub NONSENSICAL_OPEN_OPTIONS,
2785 "nonsensical combination of options for opening a file"
2788 declare_clippy_lint! {
2789 /// ### What it does
2790 ///* Checks for [push](https://doc.rust-lang.org/std/path/struct.PathBuf.html#method.push)
2791 /// calls on `PathBuf` that can cause overwrites.
2793 /// ### Why is this bad?
2794 /// Calling `push` with a root path at the start can overwrite the
2795 /// previous defined path.
2799 /// use std::path::PathBuf;
2801 /// let mut x = PathBuf::from("/foo");
2803 /// assert_eq!(x, PathBuf::from("/bar"));
2805 /// Could be written:
2808 /// use std::path::PathBuf;
2810 /// let mut x = PathBuf::from("/foo");
2812 /// assert_eq!(x, PathBuf::from("/foo/bar"));
2814 #[clippy::version = "1.36.0"]
2815 pub PATH_BUF_PUSH_OVERWRITE,
2817 "calling `push` with file system root on `PathBuf` can overwrite it"
2820 declare_clippy_lint! {
2821 /// ### What it does
2822 /// Checks for zipping a collection with the range of
2825 /// ### Why is this bad?
2826 /// The code is better expressed with `.enumerate()`.
2830 /// # let x = vec![1];
2831 /// let _ = x.iter().zip(0..x.len());
2836 /// # let x = vec![1];
2837 /// let _ = x.iter().enumerate();
2839 #[clippy::version = "pre 1.29.0"]
2840 pub RANGE_ZIP_WITH_LEN,
2842 "zipping iterator with a range when `enumerate()` would do"
2845 declare_clippy_lint! {
2846 /// ### What it does
2847 /// Checks for usage of `.repeat(1)` and suggest the following method for each types.
2848 /// - `.to_string()` for `str`
2849 /// - `.clone()` for `String`
2850 /// - `.to_vec()` for `slice`
2852 /// The lint will evaluate constant expressions and values as arguments of `.repeat(..)` and emit a message if
2853 /// they are equivalent to `1`. (Related discussion in [rust-clippy#7306](https://github.com/rust-lang/rust-clippy/issues/7306))
2855 /// ### Why is this bad?
2856 /// For example, `String.repeat(1)` is equivalent to `.clone()`. If cloning
2857 /// the string is the intention behind this, `clone()` should be used.
2862 /// let x = String::from("hello world").repeat(1);
2868 /// let x = String::from("hello world").clone();
2871 #[clippy::version = "1.47.0"]
2874 "using `.repeat(1)` instead of `String.clone()`, `str.to_string()` or `slice.to_vec()` "
2877 declare_clippy_lint! {
2878 /// ### What it does
2879 /// When sorting primitive values (integers, bools, chars, as well
2880 /// as arrays, slices, and tuples of such items), it is typically better to
2881 /// use an unstable sort than a stable sort.
2883 /// ### Why is this bad?
2884 /// Typically, using a stable sort consumes more memory and cpu cycles.
2885 /// Because values which compare equal are identical, preserving their
2886 /// relative order (the guarantee that a stable sort provides) means
2887 /// nothing, while the extra costs still apply.
2889 /// ### Known problems
2891 /// As pointed out in
2892 /// [issue #8241](https://github.com/rust-lang/rust-clippy/issues/8241),
2893 /// a stable sort can instead be significantly faster for certain scenarios
2894 /// (eg. when a sorted vector is extended with new data and resorted).
2896 /// For more information and benchmarking results, please refer to the
2897 /// issue linked above.
2901 /// let mut vec = vec![2, 1, 3];
2906 /// let mut vec = vec![2, 1, 3];
2907 /// vec.sort_unstable();
2909 #[clippy::version = "1.47.0"]
2910 pub STABLE_SORT_PRIMITIVE,
2912 "use of sort() when sort_unstable() is equivalent"
2915 declare_clippy_lint! {
2916 /// ### What it does
2917 /// Detects `().hash(_)`.
2919 /// ### Why is this bad?
2920 /// Hashing a unit value doesn't do anything as the implementation of `Hash` for `()` is a no-op.
2924 /// # use std::hash::Hash;
2925 /// # use std::collections::hash_map::DefaultHasher;
2926 /// # enum Foo { Empty, WithValue(u8) }
2928 /// # let mut state = DefaultHasher::new();
2929 /// # let my_enum = Foo::Empty;
2931 /// Empty => ().hash(&mut state),
2932 /// WithValue(x) => x.hash(&mut state),
2937 /// # use std::hash::Hash;
2938 /// # use std::collections::hash_map::DefaultHasher;
2939 /// # enum Foo { Empty, WithValue(u8) }
2941 /// # let mut state = DefaultHasher::new();
2942 /// # let my_enum = Foo::Empty;
2944 /// Empty => 0_u8.hash(&mut state),
2945 /// WithValue(x) => x.hash(&mut state),
2948 #[clippy::version = "1.58.0"]
2951 "hashing a unit value, which does nothing"
2954 declare_clippy_lint! {
2955 /// ### What it does
2956 /// Detects uses of `Vec::sort_by` passing in a closure
2957 /// which compares the two arguments, either directly or indirectly.
2959 /// ### Why is this bad?
2960 /// It is more clear to use `Vec::sort_by_key` (or `Vec::sort` if
2961 /// possible) than to use `Vec::sort_by` and a more complicated
2964 /// ### Known problems
2965 /// If the suggested `Vec::sort_by_key` uses Reverse and it isn't already
2966 /// imported by a use statement, then it will need to be added manually.
2971 /// # impl A { fn foo(&self) {} }
2972 /// # let mut vec: Vec<A> = Vec::new();
2973 /// vec.sort_by(|a, b| a.foo().cmp(&b.foo()));
2978 /// # impl A { fn foo(&self) {} }
2979 /// # let mut vec: Vec<A> = Vec::new();
2980 /// vec.sort_by_key(|a| a.foo());
2982 #[clippy::version = "1.46.0"]
2983 pub UNNECESSARY_SORT_BY,
2985 "Use of `Vec::sort_by` when `Vec::sort_by_key` or `Vec::sort` would be clearer"
2988 declare_clippy_lint! {
2989 /// ### What it does
2990 /// Finds occurrences of `Vec::resize(0, an_int)`
2992 /// ### Why is this bad?
2993 /// This is probably an argument inversion mistake.
2997 /// vec!(1, 2, 3, 4, 5).resize(0, 5)
3002 /// vec!(1, 2, 3, 4, 5).clear()
3004 #[clippy::version = "1.46.0"]
3005 pub VEC_RESIZE_TO_ZERO,
3007 "emptying a vector with `resize(0, an_int)` instead of `clear()` is probably an argument inversion mistake"
3010 declare_clippy_lint! {
3011 /// ### What it does
3012 /// Checks for use of File::read_to_end and File::read_to_string.
3014 /// ### Why is this bad?
3015 /// `fs::{read, read_to_string}` provide the same functionality when `buf` is empty with fewer imports and no intermediate values.
3016 /// 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)
3020 /// # use std::io::Read;
3021 /// # use std::fs::File;
3022 /// let mut f = File::open("foo.txt").unwrap();
3023 /// let mut bytes = Vec::new();
3024 /// f.read_to_end(&mut bytes).unwrap();
3026 /// Can be written more concisely as
3029 /// let mut bytes = fs::read("foo.txt").unwrap();
3031 #[clippy::version = "1.44.0"]
3032 pub VERBOSE_FILE_READS,
3034 "use of `File::read_to_end` or `File::read_to_string`"
3037 declare_clippy_lint! {
3038 /// ### What it does
3040 /// Checks for iterating a map (`HashMap` or `BTreeMap`) and
3041 /// ignoring either the keys or values.
3043 /// ### Why is this bad?
3045 /// Readability. There are `keys` and `values` methods that
3046 /// can be used to express that we only need the keys or the values.
3051 /// # use std::collections::HashMap;
3052 /// let map: HashMap<u32, u32> = HashMap::new();
3053 /// let values = map.iter().map(|(_, value)| value).collect::<Vec<_>>();
3058 /// # use std::collections::HashMap;
3059 /// let map: HashMap<u32, u32> = HashMap::new();
3060 /// let values = map.values().collect::<Vec<_>>();
3062 #[clippy::version = "1.66.0"]
3065 "iterating on map using `iter` when `keys` or `values` would do"
3068 declare_clippy_lint! {
3069 /// ### What it does
3071 /// Checks an argument of `seek` method of `Seek` trait
3072 /// and if it start seek from `SeekFrom::Current(0)`, suggests `stream_position` instead.
3074 /// ### Why is this bad?
3076 /// Readability. Use dedicated method.
3081 /// use std::fs::File;
3082 /// use std::io::{self, Write, Seek, SeekFrom};
3084 /// fn main() -> io::Result<()> {
3085 /// let mut f = File::create("foo.txt")?;
3086 /// f.write_all(b"Hello")?;
3087 /// eprintln!("Written {} bytes", f.seek(SeekFrom::Current(0))?);
3094 /// use std::fs::File;
3095 /// use std::io::{self, Write, Seek, SeekFrom};
3097 /// fn main() -> io::Result<()> {
3098 /// let mut f = File::create("foo.txt")?;
3099 /// f.write_all(b"Hello")?;
3100 /// eprintln!("Written {} bytes", f.stream_position()?);
3105 #[clippy::version = "1.66.0"]
3106 pub SEEK_FROM_CURRENT,
3108 "use dedicated method for seek from current position"
3111 declare_clippy_lint! {
3112 /// ### What it does
3114 /// Checks for jumps to the start of a stream that implements `Seek`
3115 /// and uses the `seek` method providing `Start` as parameter.
3117 /// ### Why is this bad?
3119 /// Readability. There is a specific method that was implemented for
3120 /// this exact scenario.
3125 /// fn foo<T: io::Seek>(t: &mut T) {
3126 /// t.seek(io::SeekFrom::Start(0));
3132 /// fn foo<T: io::Seek>(t: &mut T) {
3136 #[clippy::version = "1.66.0"]
3137 pub SEEK_TO_START_INSTEAD_OF_REWIND,
3139 "jumping to the start of stream using `seek` method"
3142 declare_clippy_lint! {
3143 /// ### What it does
3144 /// Checks for functions collecting an iterator when collect
3147 /// ### Why is this bad?
3148 /// `collect` causes the allocation of a new data structure,
3149 /// when this allocation may not be needed.
3153 /// # let iterator = vec![1].into_iter();
3154 /// let len = iterator.clone().collect::<Vec<_>>().len();
3156 /// let len = iterator.count();
3158 #[clippy::version = "1.30.0"]
3159 pub NEEDLESS_COLLECT,
3161 "collecting an iterator when collect is not needed"
3164 pub struct Methods {
3165 avoid_breaking_exported_api: bool,
3167 allow_expect_in_tests: bool,
3168 allow_unwrap_in_tests: bool,
3174 avoid_breaking_exported_api: bool,
3176 allow_expect_in_tests: bool,
3177 allow_unwrap_in_tests: bool,
3180 avoid_breaking_exported_api,
3182 allow_expect_in_tests,
3183 allow_unwrap_in_tests,
3188 impl_lint_pass!(Methods => [
3191 SHOULD_IMPLEMENT_TRAIT,
3192 WRONG_SELF_CONVENTION,
3194 UNWRAP_OR_ELSE_DEFAULT,
3196 RESULT_MAP_OR_INTO_OPTION,
3198 BIND_INSTEAD_OF_MAP,
3207 COLLAPSIBLE_STR_REPLACE,
3208 ITER_OVEREAGER_CLONED,
3209 CLONED_INSTEAD_OF_COPIED,
3211 INEFFICIENT_TO_STRING,
3213 SINGLE_CHAR_PATTERN,
3214 SINGLE_CHAR_ADD_STR,
3218 FILTER_MAP_IDENTITY,
3226 ITERATOR_STEP_BY_ZERO,
3235 STRING_EXTEND_CHARS,
3236 ITER_CLONED_COLLECT,
3240 UNNECESSARY_FILTER_MAP,
3241 UNNECESSARY_FIND_MAP,
3244 UNINIT_ASSUMED_INIT,
3245 MANUAL_SATURATING_ARITHMETIC,
3248 OPTION_AS_REF_DEREF,
3249 UNNECESSARY_LAZY_EVALUATIONS,
3250 MAP_COLLECT_RESULT_UNIT,
3251 FROM_ITER_INSTEAD_OF_COLLECT,
3254 SUSPICIOUS_TO_OWNED,
3260 UNNECESSARY_TO_OWNED,
3263 NEEDLESS_OPTION_AS_DEREF,
3264 IS_DIGIT_ASCII_RADIX,
3265 NEEDLESS_OPTION_TAKE,
3268 ITER_ON_SINGLE_ITEMS,
3269 ITER_ON_EMPTY_COLLECTIONS,
3272 CASE_SENSITIVE_FILE_EXTENSION_COMPARISONS,
3278 NONSENSICAL_OPEN_OPTIONS,
3279 PATH_BUF_PUSH_OVERWRITE,
3282 STABLE_SORT_PRIMITIVE,
3284 UNNECESSARY_SORT_BY,
3289 SEEK_TO_START_INSTEAD_OF_REWIND,
3293 /// Extracts a method call name, args, and `Span` of the method name.
3294 fn method_call<'tcx>(
3295 recv: &'tcx hir::Expr<'tcx>,
3296 ) -> Option<(&'tcx str, &'tcx hir::Expr<'tcx>, &'tcx [hir::Expr<'tcx>], Span, Span)> {
3297 if let ExprKind::MethodCall(path, receiver, args, call_span) = recv.kind {
3298 if !args.iter().any(|e| e.span.from_expansion()) && !receiver.span.from_expansion() {
3299 let name = path.ident.name.as_str();
3300 return Some((name, receiver, args, path.ident.span, call_span));
3306 impl<'tcx> LateLintPass<'tcx> for Methods {
3307 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) {
3308 if expr.span.from_expansion() {
3312 self.check_methods(cx, expr);
3315 hir::ExprKind::Call(func, args) => {
3316 from_iter_instead_of_collect::check(cx, expr, args, func);
3318 hir::ExprKind::MethodCall(method_call, receiver, args, _) => {
3319 let method_span = method_call.ident.span;
3320 or_fun_call::check(cx, expr, method_span, method_call.ident.as_str(), receiver, args);
3321 expect_fun_call::check(cx, expr, method_span, method_call.ident.as_str(), receiver, args);
3322 clone_on_copy::check(cx, expr, method_call.ident.name, receiver, args);
3323 clone_on_ref_ptr::check(cx, expr, method_call.ident.name, receiver, args);
3324 inefficient_to_string::check(cx, expr, method_call.ident.name, receiver, args);
3325 single_char_add_str::check(cx, expr, receiver, args);
3326 into_iter_on_ref::check(cx, expr, method_span, method_call.ident.name, receiver);
3327 single_char_pattern::check(cx, expr, method_call.ident.name, receiver, args);
3328 unnecessary_to_owned::check(cx, expr, method_call.ident.name, receiver, args, &self.msrv);
3330 hir::ExprKind::Binary(op, lhs, rhs) if op.node == hir::BinOpKind::Eq || op.node == hir::BinOpKind::Ne => {
3331 let mut info = BinaryExprInfo {
3335 eq: op.node == hir::BinOpKind::Eq,
3337 lint_binary_expr_with_method_call(cx, &mut info);
3343 #[allow(clippy::too_many_lines)]
3344 fn check_impl_item(&mut self, cx: &LateContext<'tcx>, impl_item: &'tcx hir::ImplItem<'_>) {
3345 if in_external_macro(cx.sess(), impl_item.span) {
3348 let name = impl_item.ident.name.as_str();
3349 let parent = cx.tcx.hir().get_parent_item(impl_item.hir_id()).def_id;
3350 let item = cx.tcx.hir().expect_item(parent);
3351 let self_ty = cx.tcx.type_of(item.owner_id);
3353 let implements_trait = matches!(item.kind, hir::ItemKind::Impl(hir::Impl { of_trait: Some(_), .. }));
3354 if let hir::ImplItemKind::Fn(ref sig, id) = impl_item.kind {
3355 let method_sig = cx.tcx.fn_sig(impl_item.owner_id);
3356 let method_sig = cx.tcx.erase_late_bound_regions(method_sig);
3357 let first_arg_ty_opt = method_sig.inputs().iter().next().copied();
3358 // if this impl block implements a trait, lint in trait definition instead
3359 if !implements_trait && cx.effective_visibilities.is_exported(impl_item.owner_id.def_id) {
3360 // check missing trait implementations
3361 for method_config in &TRAIT_METHODS {
3362 if name == method_config.method_name
3363 && sig.decl.inputs.len() == method_config.param_count
3364 && method_config.output_type.matches(&sig.decl.output)
3365 // in case there is no first arg, since we already have checked the number of arguments
3366 // it's should be always true
3367 && first_arg_ty_opt.map_or(true, |first_arg_ty| method_config
3368 .self_kind.matches(cx, self_ty, first_arg_ty)
3370 && fn_header_equals(method_config.fn_header, sig.header)
3371 && method_config.lifetime_param_cond(impl_item)
3375 SHOULD_IMPLEMENT_TRAIT,
3378 "method `{}` can be confused for the standard trait method `{}::{}`",
3379 method_config.method_name, method_config.trait_name, method_config.method_name
3383 "consider implementing the trait `{}` or choosing a less ambiguous method name",
3384 method_config.trait_name
3391 if sig.decl.implicit_self.has_implicit_self()
3392 && !(self.avoid_breaking_exported_api
3393 && cx.effective_visibilities.is_exported(impl_item.owner_id.def_id))
3394 && let Some(first_arg) = iter_input_pats(sig.decl, cx.tcx.hir().body(id)).next()
3395 && let Some(first_arg_ty) = first_arg_ty_opt
3397 wrong_self_convention::check(
3409 // if this impl block implements a trait, lint in trait definition instead
3410 if implements_trait {
3414 if let hir::ImplItemKind::Fn(_, _) = impl_item.kind {
3415 let ret_ty = return_ty(cx, impl_item.hir_id());
3417 if contains_ty_adt_constructor_opaque(cx, ret_ty, self_ty) {
3421 if name == "new" && ret_ty != self_ty {
3426 "methods called `new` usually return `Self`",
3432 fn check_trait_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx TraitItem<'_>) {
3433 if in_external_macro(cx.tcx.sess, item.span) {
3438 if let TraitItemKind::Fn(ref sig, _) = item.kind;
3439 if sig.decl.implicit_self.has_implicit_self();
3440 if let Some(first_arg_ty) = sig.decl.inputs.iter().next();
3443 let first_arg_span = first_arg_ty.span;
3444 let first_arg_ty = hir_ty_to_ty(cx.tcx, first_arg_ty);
3445 let self_ty = TraitRef::identity(cx.tcx, item.owner_id.to_def_id())
3448 wrong_self_convention::check(
3450 item.ident.name.as_str(),
3461 if item.ident.name == sym::new;
3462 if let TraitItemKind::Fn(_, _) = item.kind;
3463 let ret_ty = return_ty(cx, item.hir_id());
3464 let self_ty = TraitRef::identity(cx.tcx, item.owner_id.to_def_id())
3467 if !ret_ty.contains(self_ty);
3474 "methods called `new` usually return `Self`",
3480 extract_msrv_attr!(LateContext);
3484 #[allow(clippy::too_many_lines)]
3485 fn check_methods<'tcx>(&self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
3486 if let Some((name, recv, args, span, call_span)) = method_call(expr) {
3487 match (name, args) {
3488 ("add" | "offset" | "sub" | "wrapping_offset" | "wrapping_add" | "wrapping_sub", [_arg]) => {
3489 zst_offset::check(cx, expr, recv);
3491 ("and_then", [arg]) => {
3492 let biom_option_linted = bind_instead_of_map::OptionAndThenSome::check(cx, expr, recv, arg);
3493 let biom_result_linted = bind_instead_of_map::ResultAndThenOk::check(cx, expr, recv, arg);
3494 if !biom_option_linted && !biom_result_linted {
3495 unnecessary_lazy_eval::check(cx, expr, recv, arg, "and");
3498 ("as_deref" | "as_deref_mut", []) => {
3499 needless_option_as_deref::check(cx, expr, recv, name);
3501 ("as_mut", []) => useless_asref::check(cx, expr, "as_mut", recv),
3502 ("as_ref", []) => useless_asref::check(cx, expr, "as_ref", recv),
3503 ("assume_init", []) => uninit_assumed_init::check(cx, expr, recv),
3504 ("cloned", []) => cloned_instead_of_copied::check(cx, expr, recv, span, &self.msrv),
3505 ("collect", []) if is_trait_method(cx, expr, sym::Iterator) => {
3506 needless_collect::check(cx, span, expr, recv, call_span);
3507 match method_call(recv) {
3508 Some((name @ ("cloned" | "copied"), recv2, [], _, _)) => {
3509 iter_cloned_collect::check(cx, name, expr, recv2);
3511 Some(("map", m_recv, [m_arg], _, _)) => {
3512 map_collect_result_unit::check(cx, expr, m_recv, m_arg);
3514 Some(("take", take_self_arg, [take_arg], _, _)) => {
3515 if self.msrv.meets(msrvs::STR_REPEAT) {
3516 manual_str_repeat::check(cx, expr, recv, take_self_arg, take_arg);
3522 ("count", []) if is_trait_method(cx, expr, sym::Iterator) => match method_call(recv) {
3523 Some(("cloned", recv2, [], _, _)) => iter_overeager_cloned::check(cx, expr, recv, recv2, true, false),
3524 Some((name2 @ ("into_iter" | "iter" | "iter_mut"), recv2, [], _, _)) => {
3525 iter_count::check(cx, expr, recv2, name2);
3527 Some(("map", _, [arg], _, _)) => suspicious_map::check(cx, expr, recv, arg),
3528 Some(("filter", recv2, [arg], _, _)) => bytecount::check(cx, expr, recv2, arg),
3529 Some(("bytes", recv2, [], _, _)) => bytes_count_to_len::check(cx, expr, recv, recv2),
3532 ("drain", [arg]) => {
3533 iter_with_drain::check(cx, expr, recv, span, arg);
3535 ("ends_with", [arg]) => {
3536 if let ExprKind::MethodCall(.., span) = expr.kind {
3537 case_sensitive_file_extension_comparisons::check(cx, expr, span, recv, arg);
3540 ("expect", [_]) => match method_call(recv) {
3541 Some(("ok", recv, [], _, _)) => ok_expect::check(cx, expr, recv),
3542 Some(("err", recv, [], err_span, _)) => err_expect::check(cx, expr, recv, span, err_span, &self.msrv),
3543 _ => expect_used::check(cx, expr, recv, false, self.allow_expect_in_tests),
3545 ("expect_err", [_]) => expect_used::check(cx, expr, recv, true, self.allow_expect_in_tests),
3546 ("extend", [arg]) => {
3547 string_extend_chars::check(cx, expr, recv, arg);
3548 extend_with_drain::check(cx, expr, recv, arg);
3550 ("filter_map", [arg]) => {
3551 unnecessary_filter_map::check(cx, expr, arg, name);
3552 filter_map_identity::check(cx, expr, arg, span);
3554 ("find_map", [arg]) => {
3555 unnecessary_filter_map::check(cx, expr, arg, name);
3557 ("flat_map", [arg]) => {
3558 flat_map_identity::check(cx, expr, arg, span);
3559 flat_map_option::check(cx, expr, arg, span);
3561 ("flatten", []) => match method_call(recv) {
3562 Some(("map", recv, [map_arg], map_span, _)) => map_flatten::check(cx, expr, recv, map_arg, map_span),
3563 Some(("cloned", recv2, [], _, _)) => iter_overeager_cloned::check(cx, expr, recv, recv2, false, true),
3566 ("fold", [init, acc]) => unnecessary_fold::check(cx, expr, init, acc, span),
3567 ("for_each", [_]) => {
3568 if let Some(("inspect", _, [_], span2, _)) = method_call(recv) {
3569 inspect_for_each::check(cx, expr, span2);
3573 get_first::check(cx, expr, recv, arg);
3574 get_last_with_len::check(cx, expr, recv, arg);
3576 ("get_or_insert_with", [arg]) => unnecessary_lazy_eval::check(cx, expr, recv, arg, "get_or_insert"),
3577 ("hash", [arg]) => {
3578 unit_hash::check(cx, expr, recv, arg);
3580 ("is_file", []) => filetype_is_file::check(cx, expr, recv),
3581 ("is_digit", [radix]) => is_digit_ascii_radix::check(cx, expr, recv, radix, &self.msrv),
3582 ("is_none", []) => check_is_some_is_none(cx, expr, recv, false),
3583 ("is_some", []) => check_is_some_is_none(cx, expr, recv, true),
3584 ("iter" | "iter_mut" | "into_iter", []) => {
3585 iter_on_single_or_empty_collections::check(cx, expr, name, recv);
3587 ("join", [join_arg]) => {
3588 if let Some(("collect", _, _, span, _)) = method_call(recv) {
3589 unnecessary_join::check(cx, expr, recv, join_arg, span);
3592 ("last", []) | ("skip", [_]) => {
3593 if let Some((name2, recv2, args2, _span2, _)) = method_call(recv) {
3594 if let ("cloned", []) = (name2, args2) {
3595 iter_overeager_cloned::check(cx, expr, recv, recv2, false, false);
3600 mut_mutex_lock::check(cx, expr, recv, span);
3602 (name @ ("map" | "map_err"), [m_arg]) => {
3604 map_clone::check(cx, expr, recv, m_arg, &self.msrv);
3605 if let Some((map_name @ ("iter" | "into_iter"), recv2, _, _, _)) = method_call(recv) {
3606 iter_kv_map::check(cx, map_name, expr, recv2, m_arg);
3609 map_err_ignore::check(cx, expr, m_arg);
3611 if let Some((name, recv2, args, span2,_)) = method_call(recv) {
3612 match (name, args) {
3613 ("as_mut", []) => option_as_ref_deref::check(cx, expr, recv2, m_arg, true, &self.msrv),
3614 ("as_ref", []) => option_as_ref_deref::check(cx, expr, recv2, m_arg, false, &self.msrv),
3615 ("filter", [f_arg]) => {
3616 filter_map::check(cx, expr, recv2, f_arg, span2, recv, m_arg, span, false);
3618 ("find", [f_arg]) => {
3619 filter_map::check(cx, expr, recv2, f_arg, span2, recv, m_arg, span, true);
3624 map_identity::check(cx, expr, recv, m_arg, name, span);
3626 ("map_or", [def, map]) => {
3627 option_map_or_none::check(cx, expr, recv, def, map);
3628 manual_ok_or::check(cx, expr, recv, def, map);
3631 if let Some((name2, recv2, args2, _, _)) = method_call(recv) {
3632 match (name2, args2) {
3633 ("cloned", []) => iter_overeager_cloned::check(cx, expr, recv, recv2, false, false),
3634 ("filter", [arg]) => filter_next::check(cx, expr, recv2, arg),
3635 ("filter_map", [arg]) => filter_map_next::check(cx, expr, recv2, arg, &self.msrv),
3636 ("iter", []) => iter_next_slice::check(cx, expr, recv2),
3637 ("skip", [arg]) => iter_skip_next::check(cx, expr, recv2, arg),
3638 ("skip_while", [_]) => skip_while_next::check(cx, expr),
3643 ("nth", [n_arg]) => match method_call(recv) {
3644 Some(("bytes", recv2, [], _, _)) => bytes_nth::check(cx, expr, recv2, n_arg),
3645 Some(("cloned", recv2, [], _, _)) => iter_overeager_cloned::check(cx, expr, recv, recv2, false, false),
3646 Some(("iter", recv2, [], _, _)) => iter_nth::check(cx, expr, recv2, recv, n_arg, false),
3647 Some(("iter_mut", recv2, [], _, _)) => iter_nth::check(cx, expr, recv2, recv, n_arg, true),
3648 _ => iter_nth_zero::check(cx, expr, recv, n_arg),
3650 ("ok_or_else", [arg]) => unnecessary_lazy_eval::check(cx, expr, recv, arg, "ok_or"),
3652 open_options::check(cx, expr, recv);
3654 ("or_else", [arg]) => {
3655 if !bind_instead_of_map::ResultOrElseErrInfo::check(cx, expr, recv, arg) {
3656 unnecessary_lazy_eval::check(cx, expr, recv, arg, "or");
3659 ("push", [arg]) => {
3660 path_buf_push_overwrite::check(cx, expr, arg);
3662 ("read_to_end", [_]) => {
3663 verbose_file_reads::check(cx, expr, recv, verbose_file_reads::READ_TO_END_MSG);
3665 ("read_to_string", [_]) => {
3666 verbose_file_reads::check(cx, expr, recv, verbose_file_reads::READ_TO_STRING_MSG);
3668 ("repeat", [arg]) => {
3669 repeat_once::check(cx, expr, recv, arg);
3671 (name @ ("replace" | "replacen"), [arg1, arg2] | [arg1, arg2, _]) => {
3672 no_effect_replace::check(cx, expr, arg1, arg2);
3674 // Check for repeated `str::replace` calls to perform `collapsible_str_replace` lint
3675 if self.msrv.meets(msrvs::PATTERN_TRAIT_CHAR_ARRAY)
3676 && name == "replace"
3677 && let Some(("replace", ..)) = method_call(recv)
3679 collapsible_str_replace::check(cx, expr, arg1, arg2);
3682 ("resize", [count_arg, default_arg]) => {
3683 vec_resize_to_zero::check(cx, expr, count_arg, default_arg, span);
3685 ("seek", [arg]) => {
3686 if self.msrv.meets(msrvs::SEEK_FROM_CURRENT) {
3687 seek_from_current::check(cx, expr, recv, arg);
3689 if self.msrv.meets(msrvs::SEEK_REWIND) {
3690 seek_to_start_instead_of_rewind::check(cx, expr, recv, arg, span);
3694 stable_sort_primitive::check(cx, expr, recv);
3696 ("sort_by", [arg]) => {
3697 unnecessary_sort_by::check(cx, expr, recv, arg, false);
3699 ("sort_unstable_by", [arg]) => {
3700 unnecessary_sort_by::check(cx, expr, recv, arg, true);
3702 ("splitn" | "rsplitn", [count_arg, pat_arg]) => {
3703 if let Some((Constant::Int(count), _)) = constant(cx, cx.typeck_results(), count_arg) {
3704 suspicious_splitn::check(cx, name, expr, recv, count);
3705 str_splitn::check(cx, name, expr, recv, pat_arg, count, &self.msrv);
3708 ("splitn_mut" | "rsplitn_mut", [count_arg, _]) => {
3709 if let Some((Constant::Int(count), _)) = constant(cx, cx.typeck_results(), count_arg) {
3710 suspicious_splitn::check(cx, name, expr, recv, count);
3713 ("step_by", [arg]) => iterator_step_by_zero::check(cx, expr, arg),
3714 ("take", [_arg]) => {
3715 if let Some((name2, recv2, args2, _span2, _)) = method_call(recv) {
3716 if let ("cloned", []) = (name2, args2) {
3717 iter_overeager_cloned::check(cx, expr, recv, recv2, false, false);
3721 ("take", []) => needless_option_take::check(cx, expr, recv),
3722 ("then", [arg]) => {
3723 if !self.msrv.meets(msrvs::BOOL_THEN_SOME) {
3726 unnecessary_lazy_eval::check(cx, expr, recv, arg, "then_some");
3728 ("to_owned", []) => {
3729 if !suspicious_to_owned::check(cx, expr, recv) {
3730 implicit_clone::check(cx, name, expr, recv);
3733 ("to_os_string" | "to_path_buf" | "to_vec", []) => {
3734 implicit_clone::check(cx, name, expr, recv);
3737 match method_call(recv) {
3738 Some(("get", recv, [get_arg], _, _)) => {
3739 get_unwrap::check(cx, expr, recv, get_arg, false);
3741 Some(("get_mut", recv, [get_arg], _, _)) => {
3742 get_unwrap::check(cx, expr, recv, get_arg, true);
3744 Some(("or", recv, [or_arg], or_span, _)) => {
3745 or_then_unwrap::check(cx, expr, recv, or_arg, or_span);
3749 unwrap_used::check(cx, expr, recv, false, self.allow_unwrap_in_tests);
3751 ("unwrap_err", []) => unwrap_used::check(cx, expr, recv, true, self.allow_unwrap_in_tests),
3752 ("unwrap_or", [u_arg]) => match method_call(recv) {
3753 Some((arith @ ("checked_add" | "checked_sub" | "checked_mul"), lhs, [rhs], _, _)) => {
3754 manual_saturating_arithmetic::check(cx, expr, lhs, rhs, u_arg, &arith["checked_".len()..]);
3756 Some(("map", m_recv, [m_arg], span, _)) => {
3757 option_map_unwrap_or::check(cx, expr, m_recv, m_arg, recv, u_arg, span);
3759 Some(("then_some", t_recv, [t_arg], _, _)) => {
3760 obfuscated_if_else::check(cx, expr, t_recv, t_arg, u_arg);
3764 ("unwrap_or_else", [u_arg]) => match method_call(recv) {
3765 Some(("map", recv, [map_arg], _, _))
3766 if map_unwrap_or::check(cx, expr, recv, map_arg, u_arg, &self.msrv) => {},
3768 unwrap_or_else_default::check(cx, expr, recv, u_arg);
3769 unnecessary_lazy_eval::check(cx, expr, recv, u_arg, "unwrap_or");
3773 if let ExprKind::MethodCall(name, iter_recv, [], _) = recv.kind
3774 && name.ident.name == sym::iter
3776 range_zip_with_len::check(cx, expr, iter_recv, arg);
3785 fn check_is_some_is_none(cx: &LateContext<'_>, expr: &Expr<'_>, recv: &Expr<'_>, is_some: bool) {
3786 if let Some((name @ ("find" | "position" | "rposition"), f_recv, [arg], span, _)) = method_call(recv) {
3787 search_is_some::check(cx, expr, name, is_some, f_recv, arg, recv, span);
3791 /// Used for `lint_binary_expr_with_method_call`.
3792 #[derive(Copy, Clone)]
3793 struct BinaryExprInfo<'a> {
3794 expr: &'a hir::Expr<'a>,
3795 chain: &'a hir::Expr<'a>,
3796 other: &'a hir::Expr<'a>,
3800 /// Checks for the `CHARS_NEXT_CMP` and `CHARS_LAST_CMP` lints.
3801 fn lint_binary_expr_with_method_call(cx: &LateContext<'_>, info: &mut BinaryExprInfo<'_>) {
3802 macro_rules! lint_with_both_lhs_and_rhs {
3803 ($func:expr, $cx:expr, $info:ident) => {
3804 if !$func($cx, $info) {
3805 ::std::mem::swap(&mut $info.chain, &mut $info.other);
3806 if $func($cx, $info) {
3813 lint_with_both_lhs_and_rhs!(chars_next_cmp::check, cx, info);
3814 lint_with_both_lhs_and_rhs!(chars_last_cmp::check, cx, info);
3815 lint_with_both_lhs_and_rhs!(chars_next_cmp_with_unwrap::check, cx, info);
3816 lint_with_both_lhs_and_rhs!(chars_last_cmp_with_unwrap::check, cx, info);
3819 const FN_HEADER: hir::FnHeader = hir::FnHeader {
3820 unsafety: hir::Unsafety::Normal,
3821 constness: hir::Constness::NotConst,
3822 asyncness: hir::IsAsync::NotAsync,
3823 abi: rustc_target::spec::abi::Abi::Rust,
3826 struct ShouldImplTraitCase {
3827 trait_name: &'static str,
3828 method_name: &'static str,
3830 fn_header: hir::FnHeader,
3831 // implicit self kind expected (none, self, &self, ...)
3832 self_kind: SelfKind,
3833 // checks against the output type
3834 output_type: OutType,
3835 // certain methods with explicit lifetimes can't implement the equivalent trait method
3836 lint_explicit_lifetime: bool,
3838 impl ShouldImplTraitCase {
3840 trait_name: &'static str,
3841 method_name: &'static str,
3843 fn_header: hir::FnHeader,
3844 self_kind: SelfKind,
3845 output_type: OutType,
3846 lint_explicit_lifetime: bool,
3847 ) -> ShouldImplTraitCase {
3848 ShouldImplTraitCase {
3855 lint_explicit_lifetime,
3859 fn lifetime_param_cond(&self, impl_item: &hir::ImplItem<'_>) -> bool {
3860 self.lint_explicit_lifetime
3861 || !impl_item.generics.params.iter().any(|p| {
3864 hir::GenericParamKind::Lifetime {
3865 kind: hir::LifetimeParamKind::Explicit
3873 const TRAIT_METHODS: [ShouldImplTraitCase; 30] = [
3874 ShouldImplTraitCase::new("std::ops::Add", "add", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3875 ShouldImplTraitCase::new("std::convert::AsMut", "as_mut", 1, FN_HEADER, SelfKind::RefMut, OutType::Ref, true),
3876 ShouldImplTraitCase::new("std::convert::AsRef", "as_ref", 1, FN_HEADER, SelfKind::Ref, OutType::Ref, true),
3877 ShouldImplTraitCase::new("std::ops::BitAnd", "bitand", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3878 ShouldImplTraitCase::new("std::ops::BitOr", "bitor", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3879 ShouldImplTraitCase::new("std::ops::BitXor", "bitxor", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3880 ShouldImplTraitCase::new("std::borrow::Borrow", "borrow", 1, FN_HEADER, SelfKind::Ref, OutType::Ref, true),
3881 ShouldImplTraitCase::new("std::borrow::BorrowMut", "borrow_mut", 1, FN_HEADER, SelfKind::RefMut, OutType::Ref, true),
3882 ShouldImplTraitCase::new("std::clone::Clone", "clone", 1, FN_HEADER, SelfKind::Ref, OutType::Any, true),
3883 ShouldImplTraitCase::new("std::cmp::Ord", "cmp", 2, FN_HEADER, SelfKind::Ref, OutType::Any, true),
3884 ShouldImplTraitCase::new("std::default::Default", "default", 0, FN_HEADER, SelfKind::No, OutType::Any, true),
3885 ShouldImplTraitCase::new("std::ops::Deref", "deref", 1, FN_HEADER, SelfKind::Ref, OutType::Ref, true),
3886 ShouldImplTraitCase::new("std::ops::DerefMut", "deref_mut", 1, FN_HEADER, SelfKind::RefMut, OutType::Ref, true),
3887 ShouldImplTraitCase::new("std::ops::Div", "div", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3888 ShouldImplTraitCase::new("std::ops::Drop", "drop", 1, FN_HEADER, SelfKind::RefMut, OutType::Unit, true),
3889 ShouldImplTraitCase::new("std::cmp::PartialEq", "eq", 2, FN_HEADER, SelfKind::Ref, OutType::Bool, true),
3890 ShouldImplTraitCase::new("std::iter::FromIterator", "from_iter", 1, FN_HEADER, SelfKind::No, OutType::Any, true),
3891 ShouldImplTraitCase::new("std::str::FromStr", "from_str", 1, FN_HEADER, SelfKind::No, OutType::Any, true),
3892 ShouldImplTraitCase::new("std::hash::Hash", "hash", 2, FN_HEADER, SelfKind::Ref, OutType::Unit, true),
3893 ShouldImplTraitCase::new("std::ops::Index", "index", 2, FN_HEADER, SelfKind::Ref, OutType::Ref, true),
3894 ShouldImplTraitCase::new("std::ops::IndexMut", "index_mut", 2, FN_HEADER, SelfKind::RefMut, OutType::Ref, true),
3895 ShouldImplTraitCase::new("std::iter::IntoIterator", "into_iter", 1, FN_HEADER, SelfKind::Value, OutType::Any, true),
3896 ShouldImplTraitCase::new("std::ops::Mul", "mul", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3897 ShouldImplTraitCase::new("std::ops::Neg", "neg", 1, FN_HEADER, SelfKind::Value, OutType::Any, true),
3898 ShouldImplTraitCase::new("std::iter::Iterator", "next", 1, FN_HEADER, SelfKind::RefMut, OutType::Any, false),
3899 ShouldImplTraitCase::new("std::ops::Not", "not", 1, FN_HEADER, SelfKind::Value, OutType::Any, true),
3900 ShouldImplTraitCase::new("std::ops::Rem", "rem", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3901 ShouldImplTraitCase::new("std::ops::Shl", "shl", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3902 ShouldImplTraitCase::new("std::ops::Shr", "shr", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3903 ShouldImplTraitCase::new("std::ops::Sub", "sub", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3906 #[derive(Clone, Copy, PartialEq, Eq, Debug)]
3911 No, // When we want the first argument type to be different than `Self`
3915 fn matches<'a>(self, cx: &LateContext<'a>, parent_ty: Ty<'a>, ty: Ty<'a>) -> bool {
3916 fn matches_value<'a>(cx: &LateContext<'a>, parent_ty: Ty<'a>, ty: Ty<'a>) -> bool {
3917 if ty == parent_ty {
3919 } else if ty.is_box() {
3920 ty.boxed_ty() == parent_ty
3921 } else if is_type_diagnostic_item(cx, ty, sym::Rc) || is_type_diagnostic_item(cx, ty, sym::Arc) {
3922 if let ty::Adt(_, substs) = ty.kind() {
3923 substs.types().next().map_or(false, |t| t == parent_ty)
3932 fn matches_ref<'a>(cx: &LateContext<'a>, mutability: hir::Mutability, parent_ty: Ty<'a>, ty: Ty<'a>) -> bool {
3933 if let ty::Ref(_, t, m) = *ty.kind() {
3934 return m == mutability && t == parent_ty;
3937 let trait_sym = match mutability {
3938 hir::Mutability::Not => sym::AsRef,
3939 hir::Mutability::Mut => sym::AsMut,
3942 let Some(trait_def_id) = cx.tcx.get_diagnostic_item(trait_sym) else {
3945 implements_trait(cx, ty, trait_def_id, &[parent_ty.into()])
3948 fn matches_none<'a>(cx: &LateContext<'a>, parent_ty: Ty<'a>, ty: Ty<'a>) -> bool {
3949 !matches_value(cx, parent_ty, ty)
3950 && !matches_ref(cx, hir::Mutability::Not, parent_ty, ty)
3951 && !matches_ref(cx, hir::Mutability::Mut, parent_ty, ty)
3955 Self::Value => matches_value(cx, parent_ty, ty),
3956 Self::Ref => matches_ref(cx, hir::Mutability::Not, parent_ty, ty) || ty == parent_ty && is_copy(cx, ty),
3957 Self::RefMut => matches_ref(cx, hir::Mutability::Mut, parent_ty, ty),
3958 Self::No => matches_none(cx, parent_ty, ty),
3963 fn description(self) -> &'static str {
3965 Self::Value => "`self` by value",
3966 Self::Ref => "`self` by reference",
3967 Self::RefMut => "`self` by mutable reference",
3968 Self::No => "no `self`",
3973 #[derive(Clone, Copy)]
3982 fn matches(self, ty: &hir::FnRetTy<'_>) -> bool {
3983 let is_unit = |ty: &hir::Ty<'_>| matches!(ty.kind, hir::TyKind::Tup(&[]));
3985 (Self::Unit, &hir::FnRetTy::DefaultReturn(_)) => true,
3986 (Self::Unit, &hir::FnRetTy::Return(ty)) if is_unit(ty) => true,
3987 (Self::Bool, &hir::FnRetTy::Return(ty)) if is_bool(ty) => true,
3988 (Self::Any, &hir::FnRetTy::Return(ty)) if !is_unit(ty) => true,
3989 (Self::Ref, &hir::FnRetTy::Return(ty)) => matches!(ty.kind, hir::TyKind::Rptr(_, _)),
3995 fn fn_header_equals(expected: hir::FnHeader, actual: hir::FnHeader) -> bool {
3996 expected.constness == actual.constness
3997 && expected.unsafety == actual.unsafety
3998 && expected.asyncness == actual.asyncness