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;
18 mod extend_with_drain;
21 mod filter_map_identity;
24 mod flat_map_identity;
26 mod from_iter_instead_of_collect;
27 mod get_last_with_len;
30 mod inefficient_to_string;
33 mod is_digit_ascii_radix;
34 mod iter_cloned_collect;
39 mod iter_on_single_or_empty_collections;
40 mod iter_overeager_cloned;
43 mod iterator_step_by_zero;
44 mod manual_saturating_arithmetic;
45 mod manual_str_repeat;
46 mod map_collect_result_unit;
50 mod needless_option_as_deref;
51 mod needless_option_take;
52 mod no_effect_replace;
53 mod obfuscated_if_else;
55 mod option_as_ref_deref;
56 mod option_map_or_none;
57 mod option_map_unwrap_or;
61 mod single_char_add_str;
62 mod single_char_insert_string;
63 mod single_char_pattern;
64 mod single_char_push_string;
67 mod string_extend_chars;
69 mod suspicious_splitn;
70 mod uninit_assumed_init;
71 mod unnecessary_filter_map;
73 mod unnecessary_iter_cloned;
75 mod unnecessary_lazy_eval;
76 mod unnecessary_to_owned;
77 mod unwrap_or_else_default;
81 mod wrong_self_convention;
84 use bind_instead_of_map::BindInsteadOfMap;
85 use clippy_utils::consts::{constant, Constant};
86 use clippy_utils::diagnostics::{span_lint, span_lint_and_help};
87 use clippy_utils::ty::{contains_adt_constructor, contains_ty, implements_trait, is_copy, is_type_diagnostic_item};
89 contains_return, get_trait_def_id, is_trait_method, iter_input_pats, meets_msrv, msrvs, paths, return_ty,
91 use if_chain::if_chain;
93 use rustc_hir::def::Res;
94 use rustc_hir::{Expr, ExprKind, PrimTy, QPath, TraitItem, TraitItemKind};
95 use rustc_lint::{LateContext, LateLintPass, LintContext};
96 use rustc_middle::lint::in_external_macro;
97 use rustc_middle::ty::{self, TraitRef, Ty};
98 use rustc_semver::RustcVersion;
99 use rustc_session::{declare_tool_lint, impl_lint_pass};
100 use rustc_span::{sym, Span};
101 use rustc_typeck::hir_ty_to_ty;
103 declare_clippy_lint! {
105 /// Checks for usages of `cloned()` on an `Iterator` or `Option` where
106 /// `copied()` could be used instead.
108 /// ### Why is this bad?
109 /// `copied()` is better because it guarantees that the type being cloned
110 /// implements `Copy`.
114 /// [1, 2, 3].iter().cloned();
118 /// [1, 2, 3].iter().copied();
120 #[clippy::version = "1.53.0"]
121 pub CLONED_INSTEAD_OF_COPIED,
123 "used `cloned` where `copied` could be used instead"
126 declare_clippy_lint! {
128 /// Checks for usage of `_.cloned().<func>()` where call to `.cloned()` can be postponed.
130 /// ### Why is this bad?
131 /// It's often inefficient to clone all elements of an iterator, when eventually, only some
132 /// of them will be consumed.
134 /// ### Known Problems
135 /// This `lint` removes the side of effect of cloning items in the iterator.
136 /// A code that relies on that side-effect could fail.
140 /// # let vec = vec!["string".to_string()];
141 /// vec.iter().cloned().take(10);
142 /// vec.iter().cloned().last();
147 /// # let vec = vec!["string".to_string()];
148 /// vec.iter().take(10).cloned();
149 /// vec.iter().last().cloned();
151 #[clippy::version = "1.60.0"]
152 pub ITER_OVEREAGER_CLONED,
154 "using `cloned()` early with `Iterator::iter()` can lead to some performance inefficiencies"
157 declare_clippy_lint! {
159 /// Checks for usages of `Iterator::flat_map()` where `filter_map()` could be
162 /// ### Why is this bad?
163 /// When applicable, `filter_map()` is more clear since it shows that
164 /// `Option` is used to produce 0 or 1 items.
168 /// let nums: Vec<i32> = ["1", "2", "whee!"].iter().flat_map(|x| x.parse().ok()).collect();
172 /// let nums: Vec<i32> = ["1", "2", "whee!"].iter().filter_map(|x| x.parse().ok()).collect();
174 #[clippy::version = "1.53.0"]
177 "used `flat_map` where `filter_map` could be used instead"
180 declare_clippy_lint! {
182 /// Checks for `.unwrap()` or `.unwrap_err()` calls on `Result`s and `.unwrap()` call on `Option`s.
184 /// ### Why is this bad?
185 /// It is better to handle the `None` or `Err` case,
186 /// or at least call `.expect(_)` with a more helpful message. Still, for a lot of
187 /// quick-and-dirty code, `unwrap` is a good choice, which is why this lint is
188 /// `Allow` by default.
190 /// `result.unwrap()` will let the thread panic on `Err` values.
191 /// Normally, you want to implement more sophisticated error handling,
192 /// and propagate errors upwards with `?` operator.
194 /// Even if you want to panic on errors, not all `Error`s implement good
195 /// messages on display. Therefore, it may be beneficial to look at the places
196 /// where they may get displayed. Activate this lint to do just that.
200 /// # let option = Some(1);
201 /// # let result: Result<usize, ()> = Ok(1);
208 /// # let option = Some(1);
209 /// # let result: Result<usize, ()> = Ok(1);
210 /// option.expect("more helpful message");
211 /// result.expect("more helpful message");
214 /// If [expect_used](#expect_used) is enabled, instead:
216 /// # let option = Some(1);
217 /// # let result: Result<usize, ()> = Ok(1);
224 #[clippy::version = "1.45.0"]
227 "using `.unwrap()` on `Result` or `Option`, which should at least get a better message using `expect()`"
230 declare_clippy_lint! {
232 /// Checks for `.expect()` or `.expect_err()` calls on `Result`s and `.expect()` call on `Option`s.
234 /// ### Why is this bad?
235 /// Usually it is better to handle the `None` or `Err` case.
236 /// Still, for a lot of quick-and-dirty code, `expect` is a good choice, which is why
237 /// this lint is `Allow` by default.
239 /// `result.expect()` will let the thread panic on `Err`
240 /// values. Normally, you want to implement more sophisticated error handling,
241 /// and propagate errors upwards with `?` operator.
245 /// # let option = Some(1);
246 /// # let result: Result<usize, ()> = Ok(1);
247 /// option.expect("one");
248 /// result.expect("one");
253 /// # let option = Some(1);
254 /// # let result: Result<usize, ()> = Ok(1);
261 #[clippy::version = "1.45.0"]
264 "using `.expect()` on `Result` or `Option`, which might be better handled"
267 declare_clippy_lint! {
269 /// Checks for methods that should live in a trait
270 /// implementation of a `std` trait (see [llogiq's blog
271 /// post](http://llogiq.github.io/2015/07/30/traits.html) for further
272 /// information) instead of an inherent implementation.
274 /// ### Why is this bad?
275 /// Implementing the traits improve ergonomics for users of
276 /// the code, often with very little cost. Also people seeing a `mul(...)`
278 /// may expect `*` to work equally, so you should have good reason to disappoint
285 /// fn add(&self, other: &X) -> X {
291 #[clippy::version = "pre 1.29.0"]
292 pub SHOULD_IMPLEMENT_TRAIT,
294 "defining a method that should be implementing a std trait"
297 declare_clippy_lint! {
299 /// Checks for methods with certain name prefixes and which
300 /// doesn't match how self is taken. The actual rules are:
302 /// |Prefix |Postfix |`self` taken | `self` type |
303 /// |-------|------------|-------------------------------|--------------|
304 /// |`as_` | none |`&self` or `&mut self` | any |
305 /// |`from_`| none | none | any |
306 /// |`into_`| none |`self` | any |
307 /// |`is_` | none |`&mut self` or `&self` or none | any |
308 /// |`to_` | `_mut` |`&mut self` | any |
309 /// |`to_` | not `_mut` |`self` | `Copy` |
310 /// |`to_` | not `_mut` |`&self` | not `Copy` |
312 /// Note: Clippy doesn't trigger methods with `to_` prefix in:
313 /// - Traits definition.
314 /// Clippy can not tell if a type that implements a trait is `Copy` or not.
315 /// - Traits implementation, when `&self` is taken.
316 /// The method signature is controlled by the trait and often `&self` is required for all types that implement the trait
317 /// (see e.g. the `std::string::ToString` trait).
319 /// Clippy allows `Pin<&Self>` and `Pin<&mut Self>` if `&self` and `&mut self` is required.
321 /// Please find more info here:
322 /// https://rust-lang.github.io/api-guidelines/naming.html#ad-hoc-conversions-follow-as_-to_-into_-conventions-c-conv
324 /// ### Why is this bad?
325 /// Consistency breeds readability. If you follow the
326 /// conventions, your users won't be surprised that they, e.g., need to supply a
327 /// mutable reference to a `as_..` function.
333 /// fn as_str(self) -> &'static str {
339 #[clippy::version = "pre 1.29.0"]
340 pub WRONG_SELF_CONVENTION,
342 "defining a method named with an established prefix (like \"into_\") that takes `self` with the wrong convention"
345 declare_clippy_lint! {
347 /// Checks for usage of `ok().expect(..)`.
349 /// ### Why is this bad?
350 /// Because you usually call `expect()` on the `Result`
351 /// directly to get a better error message.
353 /// ### Known problems
354 /// The error type needs to implement `Debug`
358 /// # let x = Ok::<_, ()>(());
359 /// x.ok().expect("why did I do this again?");
364 /// # let x = Ok::<_, ()>(());
365 /// x.expect("why did I do this again?");
367 #[clippy::version = "pre 1.29.0"]
370 "using `ok().expect()`, which gives worse error messages than calling `expect` directly on the Result"
373 declare_clippy_lint! {
375 /// Checks for `.err().expect()` calls on the `Result` type.
377 /// ### Why is this bad?
378 /// `.expect_err()` can be called directly to avoid the extra type conversion from `err()`.
382 /// let x: Result<u32, &str> = Ok(10);
383 /// x.err().expect("Testing err().expect()");
387 /// let x: Result<u32, &str> = Ok(10);
388 /// x.expect_err("Testing expect_err");
390 #[clippy::version = "1.62.0"]
393 r#"using `.err().expect("")` when `.expect_err("")` can be used"#
396 declare_clippy_lint! {
398 /// Checks for usages of `_.unwrap_or_else(Default::default)` on `Option` and
401 /// ### Why is this bad?
402 /// Readability, these can be written as `_.unwrap_or_default`, which is
403 /// simpler and more concise.
407 /// # let x = Some(1);
408 /// x.unwrap_or_else(Default::default);
409 /// x.unwrap_or_else(u32::default);
414 /// # let x = Some(1);
415 /// x.unwrap_or_default();
417 #[clippy::version = "1.56.0"]
418 pub UNWRAP_OR_ELSE_DEFAULT,
420 "using `.unwrap_or_else(Default::default)`, which is more succinctly expressed as `.unwrap_or_default()`"
423 declare_clippy_lint! {
425 /// Checks for usage of `option.map(_).unwrap_or(_)` or `option.map(_).unwrap_or_else(_)` or
426 /// `result.map(_).unwrap_or_else(_)`.
428 /// ### Why is this bad?
429 /// Readability, these can be written more concisely (resp.) as
430 /// `option.map_or(_, _)`, `option.map_or_else(_, _)` and `result.map_or_else(_, _)`.
432 /// ### Known problems
433 /// The order of the arguments is not in execution order
437 /// # let option = Some(1);
438 /// # let result: Result<usize, ()> = Ok(1);
439 /// # fn some_function(foo: ()) -> usize { 1 }
440 /// option.map(|a| a + 1).unwrap_or(0);
441 /// result.map(|a| a + 1).unwrap_or_else(some_function);
446 /// # let option = Some(1);
447 /// # let result: Result<usize, ()> = Ok(1);
448 /// # fn some_function(foo: ()) -> usize { 1 }
449 /// option.map_or(0, |a| a + 1);
450 /// result.map_or_else(some_function, |a| a + 1);
452 #[clippy::version = "1.45.0"]
455 "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)`"
458 declare_clippy_lint! {
460 /// Checks for usage of `_.map_or(None, _)`.
462 /// ### Why is this bad?
463 /// Readability, this can be written more concisely as
466 /// ### Known problems
467 /// The order of the arguments is not in execution order.
471 /// # let opt = Some(1);
472 /// opt.map_or(None, |a| Some(a + 1));
477 /// # let opt = Some(1);
478 /// opt.and_then(|a| Some(a + 1));
480 #[clippy::version = "pre 1.29.0"]
481 pub OPTION_MAP_OR_NONE,
483 "using `Option.map_or(None, f)`, which is more succinctly expressed as `and_then(f)`"
486 declare_clippy_lint! {
488 /// Checks for usage of `_.map_or(None, Some)`.
490 /// ### Why is this bad?
491 /// Readability, this can be written more concisely as
496 /// # let r: Result<u32, &str> = Ok(1);
497 /// assert_eq!(Some(1), r.map_or(None, Some));
502 /// # let r: Result<u32, &str> = Ok(1);
503 /// assert_eq!(Some(1), r.ok());
505 #[clippy::version = "1.44.0"]
506 pub RESULT_MAP_OR_INTO_OPTION,
508 "using `Result.map_or(None, Some)`, which is more succinctly expressed as `ok()`"
511 declare_clippy_lint! {
513 /// Checks for usage of `_.and_then(|x| Some(y))`, `_.and_then(|x| Ok(y))` or
514 /// `_.or_else(|x| Err(y))`.
516 /// ### Why is this bad?
517 /// Readability, this can be written more concisely as
518 /// `_.map(|x| y)` or `_.map_err(|x| y)`.
522 /// # fn opt() -> Option<&'static str> { Some("42") }
523 /// # fn res() -> Result<&'static str, &'static str> { Ok("42") }
524 /// let _ = opt().and_then(|s| Some(s.len()));
525 /// let _ = res().and_then(|s| if s.len() == 42 { Ok(10) } else { Ok(20) });
526 /// let _ = res().or_else(|s| if s.len() == 42 { Err(10) } else { Err(20) });
529 /// The correct use would be:
532 /// # fn opt() -> Option<&'static str> { Some("42") }
533 /// # fn res() -> Result<&'static str, &'static str> { Ok("42") }
534 /// let _ = opt().map(|s| s.len());
535 /// let _ = res().map(|s| if s.len() == 42 { 10 } else { 20 });
536 /// let _ = res().map_err(|s| if s.len() == 42 { 10 } else { 20 });
538 #[clippy::version = "1.45.0"]
539 pub BIND_INSTEAD_OF_MAP,
541 "using `Option.and_then(|x| Some(y))`, which is more succinctly expressed as `map(|x| y)`"
544 declare_clippy_lint! {
546 /// Checks for usage of `_.filter(_).next()`.
548 /// ### Why is this bad?
549 /// Readability, this can be written more concisely as
554 /// # let vec = vec![1];
555 /// vec.iter().filter(|x| **x == 0).next();
560 /// # let vec = vec![1];
561 /// vec.iter().find(|x| **x == 0);
563 #[clippy::version = "pre 1.29.0"]
566 "using `filter(p).next()`, which is more succinctly expressed as `.find(p)`"
569 declare_clippy_lint! {
571 /// Checks for usage of `_.skip_while(condition).next()`.
573 /// ### Why is this bad?
574 /// Readability, this can be written more concisely as
575 /// `_.find(!condition)`.
579 /// # let vec = vec![1];
580 /// vec.iter().skip_while(|x| **x == 0).next();
585 /// # let vec = vec![1];
586 /// vec.iter().find(|x| **x != 0);
588 #[clippy::version = "1.42.0"]
591 "using `skip_while(p).next()`, which is more succinctly expressed as `.find(!p)`"
594 declare_clippy_lint! {
596 /// Checks for usage of `_.map(_).flatten(_)` on `Iterator` and `Option`
598 /// ### Why is this bad?
599 /// Readability, this can be written more concisely as
600 /// `_.flat_map(_)` for `Iterator` or `_.and_then(_)` for `Option`
604 /// let vec = vec![vec![1]];
605 /// let opt = Some(5);
607 /// vec.iter().map(|x| x.iter()).flatten();
608 /// opt.map(|x| Some(x * 2)).flatten();
613 /// # let vec = vec![vec![1]];
614 /// # let opt = Some(5);
615 /// vec.iter().flat_map(|x| x.iter());
616 /// opt.and_then(|x| Some(x * 2));
618 #[clippy::version = "1.31.0"]
621 "using combinations of `flatten` and `map` which can usually be written as a single method call"
624 declare_clippy_lint! {
626 /// Checks for usage of `_.filter(_).map(_)` that can be written more simply
627 /// as `filter_map(_)`.
629 /// ### Why is this bad?
630 /// Redundant code in the `filter` and `map` operations is poor style and
635 /// # #![allow(unused)]
637 /// .filter(|n| n.checked_add(1).is_some())
638 /// .map(|n| n.checked_add(1).unwrap());
643 /// # #[allow(unused)]
644 /// (0_i32..10).filter_map(|n| n.checked_add(1));
646 #[clippy::version = "1.51.0"]
647 pub MANUAL_FILTER_MAP,
649 "using `_.filter(_).map(_)` in a way that can be written more simply as `filter_map(_)`"
652 declare_clippy_lint! {
654 /// Checks for usage of `_.find(_).map(_)` that can be written more simply
655 /// as `find_map(_)`.
657 /// ### Why is this bad?
658 /// Redundant code in the `find` and `map` operations is poor style and
664 /// .find(|n| n.checked_add(1).is_some())
665 /// .map(|n| n.checked_add(1).unwrap());
670 /// (0_i32..10).find_map(|n| n.checked_add(1));
672 #[clippy::version = "1.51.0"]
675 "using `_.find(_).map(_)` in a way that can be written more simply as `find_map(_)`"
678 declare_clippy_lint! {
680 /// Checks for usage of `_.filter_map(_).next()`.
682 /// ### Why is this bad?
683 /// Readability, this can be written more concisely as
688 /// (0..3).filter_map(|x| if x == 2 { Some(x) } else { None }).next();
690 /// Can be written as
693 /// (0..3).find_map(|x| if x == 2 { Some(x) } else { None });
695 #[clippy::version = "1.36.0"]
698 "using combination of `filter_map` and `next` which can usually be written as a single method call"
701 declare_clippy_lint! {
703 /// Checks for usage of `flat_map(|x| x)`.
705 /// ### Why is this bad?
706 /// Readability, this can be written more concisely by using `flatten`.
710 /// # let iter = vec![vec![0]].into_iter();
711 /// iter.flat_map(|x| x);
713 /// Can be written as
715 /// # let iter = vec![vec![0]].into_iter();
718 #[clippy::version = "1.39.0"]
719 pub FLAT_MAP_IDENTITY,
721 "call to `flat_map` where `flatten` is sufficient"
724 declare_clippy_lint! {
726 /// Checks for an iterator or string search (such as `find()`,
727 /// `position()`, or `rposition()`) followed by a call to `is_some()` or `is_none()`.
729 /// ### Why is this bad?
730 /// Readability, this can be written more concisely as:
731 /// * `_.any(_)`, or `_.contains(_)` for `is_some()`,
732 /// * `!_.any(_)`, or `!_.contains(_)` for `is_none()`.
736 /// # #![allow(unused)]
737 /// let vec = vec![1];
738 /// vec.iter().find(|x| **x == 0).is_some();
740 /// "hello world".find("world").is_none();
745 /// let vec = vec![1];
746 /// vec.iter().any(|x| *x == 0);
748 /// # #[allow(unused)]
749 /// !"hello world".contains("world");
751 #[clippy::version = "pre 1.29.0"]
754 "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()`)"
757 declare_clippy_lint! {
759 /// Checks for usage of `.chars().next()` on a `str` to check
760 /// if it starts with a given char.
762 /// ### Why is this bad?
763 /// Readability, this can be written more concisely as
764 /// `_.starts_with(_)`.
768 /// let name = "foo";
769 /// if name.chars().next() == Some('_') {};
774 /// let name = "foo";
775 /// if name.starts_with('_') {};
777 #[clippy::version = "pre 1.29.0"]
780 "using `.chars().next()` to check if a string starts with a char"
783 declare_clippy_lint! {
785 /// Checks for calls to `.or(foo(..))`, `.unwrap_or(foo(..))`,
786 /// etc., and suggests to use `or_else`, `unwrap_or_else`, etc., or
787 /// `unwrap_or_default` instead.
789 /// ### Why is this bad?
790 /// The function will always be called and potentially
791 /// allocate an object acting as the default.
793 /// ### Known problems
794 /// If the function has side-effects, not calling it will
795 /// change the semantic of the program, but you shouldn't rely on that anyway.
799 /// # let foo = Some(String::new());
800 /// foo.unwrap_or(String::new());
805 /// # let foo = Some(String::new());
806 /// foo.unwrap_or_else(String::new);
810 /// # let foo = Some(String::new());
811 /// foo.unwrap_or_default();
813 #[clippy::version = "pre 1.29.0"]
816 "using any `*or` method with a function call, which suggests `*or_else`"
819 declare_clippy_lint! {
821 /// Checks for `.or(…).unwrap()` calls to Options and Results.
823 /// ### Why is this bad?
824 /// You should use `.unwrap_or(…)` instead for clarity.
828 /// # let fallback = "fallback";
830 /// # type Error = &'static str;
831 /// # let result: Result<&str, Error> = Err("error");
832 /// let value = result.or::<Error>(Ok(fallback)).unwrap();
835 /// # let option: Option<&str> = None;
836 /// let value = option.or(Some(fallback)).unwrap();
840 /// # let fallback = "fallback";
842 /// # let result: Result<&str, &str> = Err("error");
843 /// let value = result.unwrap_or(fallback);
846 /// # let option: Option<&str> = None;
847 /// let value = option.unwrap_or(fallback);
849 #[clippy::version = "1.61.0"]
852 "checks for `.or(…).unwrap()` calls to Options and Results."
855 declare_clippy_lint! {
857 /// Checks for calls to `.expect(&format!(...))`, `.expect(foo(..))`,
858 /// etc., and suggests to use `unwrap_or_else` instead
860 /// ### Why is this bad?
861 /// The function will always be called.
863 /// ### Known problems
864 /// If the function has side-effects, not calling it will
865 /// change the semantics of the program, but you shouldn't rely on that anyway.
869 /// # let foo = Some(String::new());
870 /// # let err_code = "418";
871 /// # let err_msg = "I'm a teapot";
872 /// foo.expect(&format!("Err {}: {}", err_code, err_msg));
876 /// # let foo = Some(String::new());
877 /// foo.expect(format!("Err {}: {}", err_code, err_msg).as_str());
882 /// # let foo = Some(String::new());
883 /// # let err_code = "418";
884 /// # let err_msg = "I'm a teapot";
885 /// foo.unwrap_or_else(|| panic!("Err {}: {}", err_code, err_msg));
887 #[clippy::version = "pre 1.29.0"]
890 "using any `expect` method with a function call"
893 declare_clippy_lint! {
895 /// Checks for usage of `.clone()` on a `Copy` type.
897 /// ### Why is this bad?
898 /// The only reason `Copy` types implement `Clone` is for
899 /// generics, not for using the `clone` method on a concrete type.
905 #[clippy::version = "pre 1.29.0"]
908 "using `clone` on a `Copy` type"
911 declare_clippy_lint! {
913 /// Checks for usage of `.clone()` on a ref-counted pointer,
914 /// (`Rc`, `Arc`, `rc::Weak`, or `sync::Weak`), and suggests calling Clone via unified
915 /// function syntax instead (e.g., `Rc::clone(foo)`).
917 /// ### Why is this bad?
918 /// Calling '.clone()' on an Rc, Arc, or Weak
919 /// can obscure the fact that only the pointer is being cloned, not the underlying
924 /// # use std::rc::Rc;
925 /// let x = Rc::new(1);
932 /// # use std::rc::Rc;
933 /// # let x = Rc::new(1);
936 #[clippy::version = "pre 1.29.0"]
937 pub CLONE_ON_REF_PTR,
939 "using 'clone' on a ref-counted pointer"
942 declare_clippy_lint! {
944 /// Checks for usage of `.clone()` on an `&&T`.
946 /// ### Why is this bad?
947 /// Cloning an `&&T` copies the inner `&T`, instead of
948 /// cloning the underlying `T`.
955 /// let z = y.clone();
956 /// println!("{:p} {:p}", *y, z); // prints out the same pointer
959 #[clippy::version = "pre 1.29.0"]
960 pub CLONE_DOUBLE_REF,
962 "using `clone` on `&&T`"
965 declare_clippy_lint! {
967 /// Checks for usage of `.to_string()` on an `&&T` where
968 /// `T` implements `ToString` directly (like `&&str` or `&&String`).
970 /// ### Why is this bad?
971 /// This bypasses the specialized implementation of
972 /// `ToString` and instead goes through the more expensive string formatting
977 /// // Generic implementation for `T: Display` is used (slow)
978 /// ["foo", "bar"].iter().map(|s| s.to_string());
980 /// // OK, the specialized impl is used
981 /// ["foo", "bar"].iter().map(|&s| s.to_string());
983 #[clippy::version = "1.40.0"]
984 pub INEFFICIENT_TO_STRING,
986 "using `to_string` on `&&T` where `T: ToString`"
989 declare_clippy_lint! {
991 /// Checks for `new` not returning a type that contains `Self`.
993 /// ### Why is this bad?
994 /// As a convention, `new` methods are used to make a new
995 /// instance of a type.
998 /// In an impl block:
1001 /// # struct NotAFoo;
1003 /// fn new() -> NotAFoo {
1011 /// struct Bar(Foo);
1013 /// // Bad. The type name must contain `Self`
1014 /// fn new() -> Bar {
1022 /// # struct FooError;
1024 /// // Good. Return type contains `Self`
1025 /// fn new() -> Result<Foo, FooError> {
1031 /// Or in a trait definition:
1033 /// pub trait Trait {
1034 /// // Bad. The type name must contain `Self`
1040 /// pub trait Trait {
1041 /// // Good. Return type contains `Self`
1042 /// fn new() -> Self;
1045 #[clippy::version = "pre 1.29.0"]
1046 pub NEW_RET_NO_SELF,
1048 "not returning type containing `Self` in a `new` method"
1051 declare_clippy_lint! {
1052 /// ### What it does
1053 /// Checks for string methods that receive a single-character
1054 /// `str` as an argument, e.g., `_.split("x")`.
1056 /// ### Why is this bad?
1057 /// Performing these methods using a `char` is faster than
1060 /// ### Known problems
1061 /// Does not catch multi-byte unicode characters.
1072 #[clippy::version = "pre 1.29.0"]
1073 pub SINGLE_CHAR_PATTERN,
1075 "using a single-character str where a char could be used, e.g., `_.split(\"x\")`"
1078 declare_clippy_lint! {
1079 /// ### What it does
1080 /// Checks for calling `.step_by(0)` on iterators which panics.
1082 /// ### Why is this bad?
1083 /// This very much looks like an oversight. Use `panic!()` instead if you
1084 /// actually intend to panic.
1087 /// ```rust,should_panic
1088 /// for x in (0..100).step_by(0) {
1092 #[clippy::version = "pre 1.29.0"]
1093 pub ITERATOR_STEP_BY_ZERO,
1095 "using `Iterator::step_by(0)`, which will panic at runtime"
1098 declare_clippy_lint! {
1099 /// ### What it does
1100 /// Checks for indirect collection of populated `Option`
1102 /// ### Why is this bad?
1103 /// `Option` is like a collection of 0-1 things, so `flatten`
1104 /// automatically does this without suspicious-looking `unwrap` calls.
1108 /// let _ = std::iter::empty::<Option<i32>>().filter(Option::is_some).map(Option::unwrap);
1112 /// let _ = std::iter::empty::<Option<i32>>().flatten();
1114 #[clippy::version = "1.53.0"]
1115 pub OPTION_FILTER_MAP,
1117 "filtering `Option` for `Some` then force-unwrapping, which can be one type-safe operation"
1120 declare_clippy_lint! {
1121 /// ### What it does
1122 /// Checks for the use of `iter.nth(0)`.
1124 /// ### Why is this bad?
1125 /// `iter.next()` is equivalent to
1126 /// `iter.nth(0)`, as they both consume the next element,
1127 /// but is more readable.
1131 /// # use std::collections::HashSet;
1132 /// # let mut s = HashSet::new();
1134 /// let x = s.iter().nth(0);
1139 /// # use std::collections::HashSet;
1140 /// # let mut s = HashSet::new();
1142 /// let x = s.iter().next();
1144 #[clippy::version = "1.42.0"]
1147 "replace `iter.nth(0)` with `iter.next()`"
1150 declare_clippy_lint! {
1151 /// ### What it does
1152 /// Checks for use of `.iter().nth()` (and the related
1153 /// `.iter_mut().nth()`) on standard library types with *O*(1) element access.
1155 /// ### Why is this bad?
1156 /// `.get()` and `.get_mut()` are more efficient and more
1161 /// let some_vec = vec![0, 1, 2, 3];
1162 /// let bad_vec = some_vec.iter().nth(3);
1163 /// let bad_slice = &some_vec[..].iter().nth(3);
1165 /// The correct use would be:
1167 /// let some_vec = vec![0, 1, 2, 3];
1168 /// let bad_vec = some_vec.get(3);
1169 /// let bad_slice = &some_vec[..].get(3);
1171 #[clippy::version = "pre 1.29.0"]
1174 "using `.iter().nth()` on a standard library type with O(1) element access"
1177 declare_clippy_lint! {
1178 /// ### What it does
1179 /// Checks for use of `.skip(x).next()` on iterators.
1181 /// ### Why is this bad?
1182 /// `.nth(x)` is cleaner
1186 /// let some_vec = vec![0, 1, 2, 3];
1187 /// let bad_vec = some_vec.iter().skip(3).next();
1188 /// let bad_slice = &some_vec[..].iter().skip(3).next();
1190 /// The correct use would be:
1192 /// let some_vec = vec![0, 1, 2, 3];
1193 /// let bad_vec = some_vec.iter().nth(3);
1194 /// let bad_slice = &some_vec[..].iter().nth(3);
1196 #[clippy::version = "pre 1.29.0"]
1199 "using `.skip(x).next()` on an iterator"
1202 declare_clippy_lint! {
1203 /// ### What it does
1204 /// Checks for use of `.drain(..)` on `Vec` and `VecDeque` for iteration.
1206 /// ### Why is this bad?
1207 /// `.into_iter()` is simpler with better performance.
1211 /// # use std::collections::HashSet;
1212 /// let mut foo = vec![0, 1, 2, 3];
1213 /// let bar: HashSet<usize> = foo.drain(..).collect();
1217 /// # use std::collections::HashSet;
1218 /// let foo = vec![0, 1, 2, 3];
1219 /// let bar: HashSet<usize> = foo.into_iter().collect();
1221 #[clippy::version = "1.61.0"]
1222 pub ITER_WITH_DRAIN,
1224 "replace `.drain(..)` with `.into_iter()`"
1227 declare_clippy_lint! {
1228 /// ### What it does
1229 /// Checks for using `x.get(x.len() - 1)` instead of
1232 /// ### Why is this bad?
1233 /// Using `x.last()` is easier to read and has the same
1236 /// Note that using `x[x.len() - 1]` is semantically different from
1237 /// `x.last()`. Indexing into the array will panic on out-of-bounds
1238 /// accesses, while `x.get()` and `x.last()` will return `None`.
1240 /// There is another lint (get_unwrap) that covers the case of using
1241 /// `x.get(index).unwrap()` instead of `x[index]`.
1245 /// let x = vec![2, 3, 5];
1246 /// let last_element = x.get(x.len() - 1);
1251 /// let x = vec![2, 3, 5];
1252 /// let last_element = x.last();
1254 #[clippy::version = "1.37.0"]
1255 pub GET_LAST_WITH_LEN,
1257 "Using `x.get(x.len() - 1)` when `x.last()` is correct and simpler"
1260 declare_clippy_lint! {
1261 /// ### What it does
1262 /// Checks for use of `.get().unwrap()` (or
1263 /// `.get_mut().unwrap`) on a standard library type which implements `Index`
1265 /// ### Why is this bad?
1266 /// Using the Index trait (`[]`) is more clear and more
1269 /// ### Known problems
1270 /// Not a replacement for error handling: Using either
1271 /// `.unwrap()` or the Index trait (`[]`) carries the risk of causing a `panic`
1272 /// if the value being accessed is `None`. If the use of `.get().unwrap()` is a
1273 /// temporary placeholder for dealing with the `Option` type, then this does
1274 /// not mitigate the need for error handling. If there is a chance that `.get()`
1275 /// will be `None` in your program, then it is advisable that the `None` case
1276 /// is handled in a future refactor instead of using `.unwrap()` or the Index
1281 /// let mut some_vec = vec![0, 1, 2, 3];
1282 /// let last = some_vec.get(3).unwrap();
1283 /// *some_vec.get_mut(0).unwrap() = 1;
1285 /// The correct use would be:
1287 /// let mut some_vec = vec![0, 1, 2, 3];
1288 /// let last = some_vec[3];
1289 /// some_vec[0] = 1;
1291 #[clippy::version = "pre 1.29.0"]
1294 "using `.get().unwrap()` or `.get_mut().unwrap()` when using `[]` would work instead"
1297 declare_clippy_lint! {
1298 /// ### What it does
1299 /// Checks for occurrences where one vector gets extended instead of append
1301 /// ### Why is this bad?
1302 /// Using `append` instead of `extend` is more concise and faster
1306 /// let mut a = vec![1, 2, 3];
1307 /// let mut b = vec![4, 5, 6];
1309 /// a.extend(b.drain(..));
1314 /// let mut a = vec![1, 2, 3];
1315 /// let mut b = vec![4, 5, 6];
1317 /// a.append(&mut b);
1319 #[clippy::version = "1.55.0"]
1320 pub EXTEND_WITH_DRAIN,
1322 "using vec.append(&mut vec) to move the full range of a vector to another"
1325 declare_clippy_lint! {
1326 /// ### What it does
1327 /// Checks for the use of `.extend(s.chars())` where s is a
1328 /// `&str` or `String`.
1330 /// ### Why is this bad?
1331 /// `.push_str(s)` is clearer
1335 /// let abc = "abc";
1336 /// let def = String::from("def");
1337 /// let mut s = String::new();
1338 /// s.extend(abc.chars());
1339 /// s.extend(def.chars());
1341 /// The correct use would be:
1343 /// let abc = "abc";
1344 /// let def = String::from("def");
1345 /// let mut s = String::new();
1346 /// s.push_str(abc);
1347 /// s.push_str(&def);
1349 #[clippy::version = "pre 1.29.0"]
1350 pub STRING_EXTEND_CHARS,
1352 "using `x.extend(s.chars())` where s is a `&str` or `String`"
1355 declare_clippy_lint! {
1356 /// ### What it does
1357 /// Checks for the use of `.cloned().collect()` on slice to
1360 /// ### Why is this bad?
1361 /// `.to_vec()` is clearer
1365 /// let s = [1, 2, 3, 4, 5];
1366 /// let s2: Vec<isize> = s[..].iter().cloned().collect();
1368 /// The better use would be:
1370 /// let s = [1, 2, 3, 4, 5];
1371 /// let s2: Vec<isize> = s.to_vec();
1373 #[clippy::version = "pre 1.29.0"]
1374 pub ITER_CLONED_COLLECT,
1376 "using `.cloned().collect()` on slice to create a `Vec`"
1379 declare_clippy_lint! {
1380 /// ### What it does
1381 /// Checks for usage of `_.chars().last()` or
1382 /// `_.chars().next_back()` on a `str` to check if it ends with a given char.
1384 /// ### Why is this bad?
1385 /// Readability, this can be written more concisely as
1386 /// `_.ends_with(_)`.
1390 /// # let name = "_";
1391 /// name.chars().last() == Some('_') || name.chars().next_back() == Some('-');
1396 /// # let name = "_";
1397 /// name.ends_with('_') || name.ends_with('-');
1399 #[clippy::version = "pre 1.29.0"]
1402 "using `.chars().last()` or `.chars().next_back()` to check if a string ends with a char"
1405 declare_clippy_lint! {
1406 /// ### What it does
1407 /// Checks for usage of `.as_ref()` or `.as_mut()` where the
1408 /// types before and after the call are the same.
1410 /// ### Why is this bad?
1411 /// The call is unnecessary.
1415 /// # fn do_stuff(x: &[i32]) {}
1416 /// let x: &[i32] = &[1, 2, 3, 4, 5];
1417 /// do_stuff(x.as_ref());
1419 /// The correct use would be:
1421 /// # fn do_stuff(x: &[i32]) {}
1422 /// let x: &[i32] = &[1, 2, 3, 4, 5];
1425 #[clippy::version = "pre 1.29.0"]
1428 "using `as_ref` where the types before and after the call are the same"
1431 declare_clippy_lint! {
1432 /// ### What it does
1433 /// Checks for using `fold` when a more succinct alternative exists.
1434 /// Specifically, this checks for `fold`s which could be replaced by `any`, `all`,
1435 /// `sum` or `product`.
1437 /// ### Why is this bad?
1442 /// # #[allow(unused)]
1443 /// (0..3).fold(false, |acc, x| acc || x > 2);
1448 /// (0..3).any(|x| x > 2);
1450 #[clippy::version = "pre 1.29.0"]
1451 pub UNNECESSARY_FOLD,
1453 "using `fold` when a more succinct alternative exists"
1456 declare_clippy_lint! {
1457 /// ### What it does
1458 /// Checks for `filter_map` calls that could be replaced by `filter` or `map`.
1459 /// More specifically it checks if the closure provided is only performing one of the
1460 /// filter or map operations and suggests the appropriate option.
1462 /// ### Why is this bad?
1463 /// Complexity. The intent is also clearer if only a single
1464 /// operation is being performed.
1468 /// let _ = (0..3).filter_map(|x| if x > 2 { Some(x) } else { None });
1470 /// // As there is no transformation of the argument this could be written as:
1471 /// let _ = (0..3).filter(|&x| x > 2);
1475 /// let _ = (0..4).filter_map(|x| Some(x + 1));
1477 /// // As there is no conditional check on the argument this could be written as:
1478 /// let _ = (0..4).map(|x| x + 1);
1480 #[clippy::version = "1.31.0"]
1481 pub UNNECESSARY_FILTER_MAP,
1483 "using `filter_map` when a more succinct alternative exists"
1486 declare_clippy_lint! {
1487 /// ### What it does
1488 /// Checks for `find_map` calls that could be replaced by `find` or `map`. More
1489 /// specifically it checks if the closure provided is only performing one of the
1490 /// find or map operations and suggests the appropriate option.
1492 /// ### Why is this bad?
1493 /// Complexity. The intent is also clearer if only a single
1494 /// operation is being performed.
1498 /// let _ = (0..3).find_map(|x| if x > 2 { Some(x) } else { None });
1500 /// // As there is no transformation of the argument this could be written as:
1501 /// let _ = (0..3).find(|&x| x > 2);
1505 /// let _ = (0..4).find_map(|x| Some(x + 1));
1507 /// // As there is no conditional check on the argument this could be written as:
1508 /// let _ = (0..4).map(|x| x + 1).next();
1510 #[clippy::version = "1.61.0"]
1511 pub UNNECESSARY_FIND_MAP,
1513 "using `find_map` when a more succinct alternative exists"
1516 declare_clippy_lint! {
1517 /// ### What it does
1518 /// Checks for `into_iter` calls on references which should be replaced by `iter`
1521 /// ### Why is this bad?
1522 /// Readability. Calling `into_iter` on a reference will not move out its
1523 /// content into the resulting iterator, which is confusing. It is better just call `iter` or
1524 /// `iter_mut` directly.
1528 /// # let vec = vec![3, 4, 5];
1529 /// (&vec).into_iter();
1534 /// # let vec = vec![3, 4, 5];
1537 #[clippy::version = "1.32.0"]
1538 pub INTO_ITER_ON_REF,
1540 "using `.into_iter()` on a reference"
1543 declare_clippy_lint! {
1544 /// ### What it does
1545 /// Checks for calls to `map` followed by a `count`.
1547 /// ### Why is this bad?
1548 /// It looks suspicious. Maybe `map` was confused with `filter`.
1549 /// If the `map` call is intentional, this should be rewritten
1550 /// using `inspect`. Or, if you intend to drive the iterator to
1551 /// completion, you can just use `for_each` instead.
1555 /// let _ = (0..3).map(|x| x + 2).count();
1557 #[clippy::version = "1.39.0"]
1560 "suspicious usage of map"
1563 declare_clippy_lint! {
1564 /// ### What it does
1565 /// Checks for `MaybeUninit::uninit().assume_init()`.
1567 /// ### Why is this bad?
1568 /// For most types, this is undefined behavior.
1570 /// ### Known problems
1571 /// For now, we accept empty tuples and tuples / arrays
1572 /// of `MaybeUninit`. There may be other types that allow uninitialized
1573 /// data, but those are not yet rigorously defined.
1577 /// // Beware the UB
1578 /// use std::mem::MaybeUninit;
1580 /// let _: usize = unsafe { MaybeUninit::uninit().assume_init() };
1583 /// Note that the following is OK:
1586 /// use std::mem::MaybeUninit;
1588 /// let _: [MaybeUninit<bool>; 5] = unsafe {
1589 /// MaybeUninit::uninit().assume_init()
1592 #[clippy::version = "1.39.0"]
1593 pub UNINIT_ASSUMED_INIT,
1595 "`MaybeUninit::uninit().assume_init()`"
1598 declare_clippy_lint! {
1599 /// ### What it does
1600 /// Checks for `.checked_add/sub(x).unwrap_or(MAX/MIN)`.
1602 /// ### Why is this bad?
1603 /// These can be written simply with `saturating_add/sub` methods.
1607 /// # let y: u32 = 0;
1608 /// # let x: u32 = 100;
1609 /// let add = x.checked_add(y).unwrap_or(u32::MAX);
1610 /// let sub = x.checked_sub(y).unwrap_or(u32::MIN);
1613 /// can be written using dedicated methods for saturating addition/subtraction as:
1616 /// # let y: u32 = 0;
1617 /// # let x: u32 = 100;
1618 /// let add = x.saturating_add(y);
1619 /// let sub = x.saturating_sub(y);
1621 #[clippy::version = "1.39.0"]
1622 pub MANUAL_SATURATING_ARITHMETIC,
1624 "`.checked_add/sub(x).unwrap_or(MAX/MIN)`"
1627 declare_clippy_lint! {
1628 /// ### What it does
1629 /// Checks for `offset(_)`, `wrapping_`{`add`, `sub`}, etc. on raw pointers to
1630 /// zero-sized types
1632 /// ### Why is this bad?
1633 /// This is a no-op, and likely unintended
1637 /// unsafe { (&() as *const ()).offset(1) };
1639 #[clippy::version = "1.41.0"]
1642 "Check for offset calculations on raw pointers to zero-sized types"
1645 declare_clippy_lint! {
1646 /// ### What it does
1647 /// Checks for `FileType::is_file()`.
1649 /// ### Why is this bad?
1650 /// When people testing a file type with `FileType::is_file`
1651 /// they are testing whether a path is something they can get bytes from. But
1652 /// `is_file` doesn't cover special file types in unix-like systems, and doesn't cover
1653 /// symlink in windows. Using `!FileType::is_dir()` is a better way to that intention.
1658 /// let metadata = std::fs::metadata("foo.txt")?;
1659 /// let filetype = metadata.file_type();
1661 /// if filetype.is_file() {
1664 /// # Ok::<_, std::io::Error>(())
1668 /// should be written as:
1672 /// let metadata = std::fs::metadata("foo.txt")?;
1673 /// let filetype = metadata.file_type();
1675 /// if !filetype.is_dir() {
1678 /// # Ok::<_, std::io::Error>(())
1681 #[clippy::version = "1.42.0"]
1682 pub FILETYPE_IS_FILE,
1684 "`FileType::is_file` is not recommended to test for readable file type"
1687 declare_clippy_lint! {
1688 /// ### What it does
1689 /// Checks for usage of `_.as_ref().map(Deref::deref)` or it's aliases (such as String::as_str).
1691 /// ### Why is this bad?
1692 /// Readability, this can be written more concisely as
1697 /// # let opt = Some("".to_string());
1698 /// opt.as_ref().map(String::as_str)
1701 /// Can be written as
1703 /// # let opt = Some("".to_string());
1707 #[clippy::version = "1.42.0"]
1708 pub OPTION_AS_REF_DEREF,
1710 "using `as_ref().map(Deref::deref)`, which is more succinctly expressed as `as_deref()`"
1713 declare_clippy_lint! {
1714 /// ### What it does
1715 /// Checks for usage of `iter().next()` on a Slice or an Array
1717 /// ### Why is this bad?
1718 /// These can be shortened into `.get()`
1722 /// # let a = [1, 2, 3];
1723 /// # let b = vec![1, 2, 3];
1724 /// a[2..].iter().next();
1725 /// b.iter().next();
1727 /// should be written as:
1729 /// # let a = [1, 2, 3];
1730 /// # let b = vec![1, 2, 3];
1734 #[clippy::version = "1.46.0"]
1735 pub ITER_NEXT_SLICE,
1737 "using `.iter().next()` on a sliced array, which can be shortened to just `.get()`"
1740 declare_clippy_lint! {
1741 /// ### What it does
1742 /// Warns when using `push_str`/`insert_str` with a single-character string literal
1743 /// where `push`/`insert` with a `char` would work fine.
1745 /// ### Why is this bad?
1746 /// It's less clear that we are pushing a single character.
1750 /// # let mut string = String::new();
1751 /// string.insert_str(0, "R");
1752 /// string.push_str("R");
1757 /// # let mut string = String::new();
1758 /// string.insert(0, 'R');
1759 /// string.push('R');
1761 #[clippy::version = "1.49.0"]
1762 pub SINGLE_CHAR_ADD_STR,
1764 "`push_str()` or `insert_str()` used with a single-character string literal as parameter"
1767 declare_clippy_lint! {
1768 /// ### What it does
1769 /// As the counterpart to `or_fun_call`, this lint looks for unnecessary
1770 /// lazily evaluated closures on `Option` and `Result`.
1772 /// This lint suggests changing the following functions, when eager evaluation results in
1774 /// - `unwrap_or_else` to `unwrap_or`
1775 /// - `and_then` to `and`
1776 /// - `or_else` to `or`
1777 /// - `get_or_insert_with` to `get_or_insert`
1778 /// - `ok_or_else` to `ok_or`
1780 /// ### Why is this bad?
1781 /// Using eager evaluation is shorter and simpler in some cases.
1783 /// ### Known problems
1784 /// It is possible, but not recommended for `Deref` and `Index` to have
1785 /// side effects. Eagerly evaluating them can change the semantics of the program.
1789 /// // example code where clippy issues a warning
1790 /// let opt: Option<u32> = None;
1792 /// opt.unwrap_or_else(|| 42);
1796 /// let opt: Option<u32> = None;
1798 /// opt.unwrap_or(42);
1800 #[clippy::version = "1.48.0"]
1801 pub UNNECESSARY_LAZY_EVALUATIONS,
1803 "using unnecessary lazy evaluation, which can be replaced with simpler eager evaluation"
1806 declare_clippy_lint! {
1807 /// ### What it does
1808 /// Checks for usage of `_.map(_).collect::<Result<(), _>()`.
1810 /// ### Why is this bad?
1811 /// Using `try_for_each` instead is more readable and idiomatic.
1815 /// (0..3).map(|t| Err(t)).collect::<Result<(), _>>();
1819 /// (0..3).try_for_each(|t| Err(t));
1821 #[clippy::version = "1.49.0"]
1822 pub MAP_COLLECT_RESULT_UNIT,
1824 "using `.map(_).collect::<Result<(),_>()`, which can be replaced with `try_for_each`"
1827 declare_clippy_lint! {
1828 /// ### What it does
1829 /// Checks for `from_iter()` function calls on types that implement the `FromIterator`
1832 /// ### Why is this bad?
1833 /// It is recommended style to use collect. See
1834 /// [FromIterator documentation](https://doc.rust-lang.org/std/iter/trait.FromIterator.html)
1838 /// let five_fives = std::iter::repeat(5).take(5);
1840 /// let v = Vec::from_iter(five_fives);
1842 /// assert_eq!(v, vec![5, 5, 5, 5, 5]);
1846 /// let five_fives = std::iter::repeat(5).take(5);
1848 /// let v: Vec<i32> = five_fives.collect();
1850 /// assert_eq!(v, vec![5, 5, 5, 5, 5]);
1852 #[clippy::version = "1.49.0"]
1853 pub FROM_ITER_INSTEAD_OF_COLLECT,
1855 "use `.collect()` instead of `::from_iter()`"
1858 declare_clippy_lint! {
1859 /// ### What it does
1860 /// Checks for usage of `inspect().for_each()`.
1862 /// ### Why is this bad?
1863 /// It is the same as performing the computation
1864 /// inside `inspect` at the beginning of the closure in `for_each`.
1868 /// [1,2,3,4,5].iter()
1869 /// .inspect(|&x| println!("inspect the number: {}", x))
1870 /// .for_each(|&x| {
1871 /// assert!(x >= 0);
1874 /// Can be written as
1876 /// [1,2,3,4,5].iter()
1877 /// .for_each(|&x| {
1878 /// println!("inspect the number: {}", x);
1879 /// assert!(x >= 0);
1882 #[clippy::version = "1.51.0"]
1883 pub INSPECT_FOR_EACH,
1885 "using `.inspect().for_each()`, which can be replaced with `.for_each()`"
1888 declare_clippy_lint! {
1889 /// ### What it does
1890 /// Checks for usage of `filter_map(|x| x)`.
1892 /// ### Why is this bad?
1893 /// Readability, this can be written more concisely by using `flatten`.
1897 /// # let iter = vec![Some(1)].into_iter();
1898 /// iter.filter_map(|x| x);
1902 /// # let iter = vec![Some(1)].into_iter();
1905 #[clippy::version = "1.52.0"]
1906 pub FILTER_MAP_IDENTITY,
1908 "call to `filter_map` where `flatten` is sufficient"
1911 declare_clippy_lint! {
1912 /// ### What it does
1913 /// Checks for instances of `map(f)` where `f` is the identity function.
1915 /// ### Why is this bad?
1916 /// It can be written more concisely without the call to `map`.
1920 /// let x = [1, 2, 3];
1921 /// let y: Vec<_> = x.iter().map(|x| x).map(|x| 2*x).collect();
1925 /// let x = [1, 2, 3];
1926 /// let y: Vec<_> = x.iter().map(|x| 2*x).collect();
1928 #[clippy::version = "1.47.0"]
1931 "using iterator.map(|x| x)"
1934 declare_clippy_lint! {
1935 /// ### What it does
1936 /// Checks for the use of `.bytes().nth()`.
1938 /// ### Why is this bad?
1939 /// `.as_bytes().get()` is more efficient and more
1944 /// # #[allow(unused)]
1945 /// "Hello".bytes().nth(3);
1950 /// # #[allow(unused)]
1951 /// "Hello".as_bytes().get(3);
1953 #[clippy::version = "1.52.0"]
1956 "replace `.bytes().nth()` with `.as_bytes().get()`"
1959 declare_clippy_lint! {
1960 /// ### What it does
1961 /// Checks for the usage of `_.to_owned()`, `vec.to_vec()`, or similar when calling `_.clone()` would be clearer.
1963 /// ### Why is this bad?
1964 /// These methods do the same thing as `_.clone()` but may be confusing as
1965 /// to why we are calling `to_vec` on something that is already a `Vec` or calling `to_owned` on something that is already owned.
1969 /// let a = vec![1, 2, 3];
1970 /// let b = a.to_vec();
1971 /// let c = a.to_owned();
1975 /// let a = vec![1, 2, 3];
1976 /// let b = a.clone();
1977 /// let c = a.clone();
1979 #[clippy::version = "1.52.0"]
1982 "implicitly cloning a value by invoking a function on its dereferenced type"
1985 declare_clippy_lint! {
1986 /// ### What it does
1987 /// Checks for the use of `.iter().count()`.
1989 /// ### Why is this bad?
1990 /// `.len()` is more efficient and more
1995 /// # #![allow(unused)]
1996 /// let some_vec = vec![0, 1, 2, 3];
1998 /// some_vec.iter().count();
1999 /// &some_vec[..].iter().count();
2004 /// let some_vec = vec![0, 1, 2, 3];
2007 /// &some_vec[..].len();
2009 #[clippy::version = "1.52.0"]
2012 "replace `.iter().count()` with `.len()`"
2015 declare_clippy_lint! {
2016 /// ### What it does
2017 /// Checks for calls to [`splitn`]
2018 /// (https://doc.rust-lang.org/std/primitive.str.html#method.splitn) and
2019 /// related functions with either zero or one splits.
2021 /// ### Why is this bad?
2022 /// These calls don't actually split the value and are
2023 /// likely to be intended as a different number.
2028 /// for x in s.splitn(1, ":") {
2036 /// for x in s.splitn(2, ":") {
2040 #[clippy::version = "1.54.0"]
2041 pub SUSPICIOUS_SPLITN,
2043 "checks for `.splitn(0, ..)` and `.splitn(1, ..)`"
2046 declare_clippy_lint! {
2047 /// ### What it does
2048 /// Checks for manual implementations of `str::repeat`
2050 /// ### Why is this bad?
2051 /// These are both harder to read, as well as less performant.
2055 /// let x: String = std::iter::repeat('x').take(10).collect();
2060 /// let x: String = "x".repeat(10);
2062 #[clippy::version = "1.54.0"]
2063 pub MANUAL_STR_REPEAT,
2065 "manual implementation of `str::repeat`"
2068 declare_clippy_lint! {
2069 /// ### What it does
2070 /// Checks for usages of `str::splitn(2, _)`
2072 /// ### Why is this bad?
2073 /// `split_once` is both clearer in intent and slightly more efficient.
2077 /// let s = "key=value=add";
2078 /// let (key, value) = s.splitn(2, '=').next_tuple()?;
2079 /// let value = s.splitn(2, '=').nth(1)?;
2081 /// let mut parts = s.splitn(2, '=');
2082 /// let key = parts.next()?;
2083 /// let value = parts.next()?;
2088 /// let s = "key=value=add";
2089 /// let (key, value) = s.split_once('=')?;
2090 /// let value = s.split_once('=')?.1;
2092 /// let (key, value) = s.split_once('=')?;
2096 /// The multiple statement variant currently only detects `iter.next()?`/`iter.next().unwrap()`
2097 /// in two separate `let` statements that immediately follow the `splitn()`
2098 #[clippy::version = "1.57.0"]
2099 pub MANUAL_SPLIT_ONCE,
2101 "replace `.splitn(2, pat)` with `.split_once(pat)`"
2104 declare_clippy_lint! {
2105 /// ### What it does
2106 /// Checks for usages of `str::splitn` (or `str::rsplitn`) where using `str::split` would be the same.
2107 /// ### Why is this bad?
2108 /// The function `split` is simpler and there is no performance difference in these cases, considering
2109 /// that both functions return a lazy iterator.
2112 /// let str = "key=value=add";
2113 /// let _ = str.splitn(3, '=').next().unwrap();
2118 /// let str = "key=value=add";
2119 /// let _ = str.split('=').next().unwrap();
2121 #[clippy::version = "1.59.0"]
2122 pub NEEDLESS_SPLITN,
2124 "usages of `str::splitn` that can be replaced with `str::split`"
2127 declare_clippy_lint! {
2128 /// ### What it does
2129 /// Checks for unnecessary calls to [`ToOwned::to_owned`](https://doc.rust-lang.org/std/borrow/trait.ToOwned.html#tymethod.to_owned)
2130 /// and other `to_owned`-like functions.
2132 /// ### Why is this bad?
2133 /// The unnecessary calls result in useless allocations.
2135 /// ### Known problems
2136 /// `unnecessary_to_owned` can falsely trigger if `IntoIterator::into_iter` is applied to an
2137 /// owned copy of a resource and the resource is later used mutably. See
2138 /// [#8148](https://github.com/rust-lang/rust-clippy/issues/8148).
2142 /// let path = std::path::Path::new("x");
2143 /// foo(&path.to_string_lossy().to_string());
2144 /// fn foo(s: &str) {}
2148 /// let path = std::path::Path::new("x");
2149 /// foo(&path.to_string_lossy());
2150 /// fn foo(s: &str) {}
2152 #[clippy::version = "1.59.0"]
2153 pub UNNECESSARY_TO_OWNED,
2155 "unnecessary calls to `to_owned`-like functions"
2158 declare_clippy_lint! {
2159 /// ### What it does
2160 /// Checks for use of `.collect::<Vec<String>>().join("")` on iterators.
2162 /// ### Why is this bad?
2163 /// `.collect::<String>()` is more concise and might be more performant
2167 /// let vector = vec!["hello", "world"];
2168 /// let output = vector.iter().map(|item| item.to_uppercase()).collect::<Vec<String>>().join("");
2169 /// println!("{}", output);
2171 /// The correct use would be:
2173 /// let vector = vec!["hello", "world"];
2174 /// let output = vector.iter().map(|item| item.to_uppercase()).collect::<String>();
2175 /// println!("{}", output);
2177 /// ### Known problems
2178 /// While `.collect::<String>()` is sometimes more performant, there are cases where
2179 /// using `.collect::<String>()` over `.collect::<Vec<String>>().join("")`
2180 /// will prevent loop unrolling and will result in a negative performance impact.
2182 /// Additionally, differences have been observed between aarch64 and x86_64 assembly output,
2183 /// with aarch64 tending to producing faster assembly in more cases when using `.collect::<String>()`
2184 #[clippy::version = "1.61.0"]
2185 pub UNNECESSARY_JOIN,
2187 "using `.collect::<Vec<String>>().join(\"\")` on an iterator"
2190 declare_clippy_lint! {
2191 /// ### What it does
2192 /// Checks for no-op uses of `Option::{as_deref, as_deref_mut}`,
2193 /// for example, `Option<&T>::as_deref()` returns the same type.
2195 /// ### Why is this bad?
2196 /// Redundant code and improving readability.
2200 /// let a = Some(&1);
2201 /// let b = a.as_deref(); // goes from Option<&i32> to Option<&i32>
2206 /// let a = Some(&1);
2209 #[clippy::version = "1.57.0"]
2210 pub NEEDLESS_OPTION_AS_DEREF,
2212 "no-op use of `deref` or `deref_mut` method to `Option`."
2215 declare_clippy_lint! {
2216 /// ### What it does
2217 /// Finds usages of [`char::is_digit`](https://doc.rust-lang.org/stable/std/primitive.char.html#method.is_digit) that
2218 /// can be replaced with [`is_ascii_digit`](https://doc.rust-lang.org/stable/std/primitive.char.html#method.is_ascii_digit) or
2219 /// [`is_ascii_hexdigit`](https://doc.rust-lang.org/stable/std/primitive.char.html#method.is_ascii_hexdigit).
2221 /// ### Why is this bad?
2222 /// `is_digit(..)` is slower and requires specifying the radix.
2226 /// let c: char = '6';
2232 /// let c: char = '6';
2233 /// c.is_ascii_digit();
2234 /// c.is_ascii_hexdigit();
2236 #[clippy::version = "1.62.0"]
2237 pub IS_DIGIT_ASCII_RADIX,
2239 "use of `char::is_digit(..)` with literal radix of 10 or 16"
2242 declare_clippy_lint! {
2243 /// ### What it does
2244 /// Checks for calling `take` function after `as_ref`.
2246 /// ### Why is this bad?
2247 /// Redundant code. `take` writes `None` to its argument.
2248 /// In this case the modification is useless as it's a temporary that cannot be read from afterwards.
2252 /// let x = Some(3);
2253 /// x.as_ref().take();
2257 /// let x = Some(3);
2260 #[clippy::version = "1.62.0"]
2261 pub NEEDLESS_OPTION_TAKE,
2263 "using `.as_ref().take()` on a temporary value"
2266 declare_clippy_lint! {
2267 /// ### What it does
2268 /// Checks for `replace` statements which have no effect.
2270 /// ### Why is this bad?
2271 /// It's either a mistake or confusing.
2275 /// "1234".replace("12", "12");
2276 /// "1234".replacen("12", "12", 1);
2278 #[clippy::version = "1.63.0"]
2279 pub NO_EFFECT_REPLACE,
2281 "replace with no effect"
2284 declare_clippy_lint! {
2285 /// ### What it does
2286 /// Checks for usages of `.then_some(..).unwrap_or(..)`
2288 /// ### Why is this bad?
2289 /// This can be written more clearly with `if .. else ..`
2292 /// This lint currently only looks for usages of
2293 /// `.then_some(..).unwrap_or(..)`, but will be expanded
2294 /// to account for similar patterns.
2299 /// x.then_some("a").unwrap_or("b");
2304 /// if x { "a" } else { "b" };
2306 #[clippy::version = "1.64.0"]
2307 pub OBFUSCATED_IF_ELSE,
2309 "use of `.then_some(..).unwrap_or(..)` can be written \
2310 more clearly with `if .. else ..`"
2313 declare_clippy_lint! {
2314 /// ### What it does
2316 /// Checks for calls to `iter`, `iter_mut` or `into_iter` on collections containing a single item
2318 /// ### Why is this bad?
2320 /// It is simpler to use the once function from the standard library:
2325 /// let a = [123].iter();
2326 /// let b = Some(123).into_iter();
2331 /// let a = iter::once(&123);
2332 /// let b = iter::once(123);
2335 /// ### Known problems
2337 /// The type of the resulting iterator might become incompatible with its usage
2338 #[clippy::version = "1.64.0"]
2339 pub ITER_ON_SINGLE_ITEMS,
2341 "Iterator for array of length 1"
2344 declare_clippy_lint! {
2345 /// ### What it does
2347 /// Checks for calls to `iter`, `iter_mut` or `into_iter` on empty collections
2349 /// ### Why is this bad?
2351 /// It is simpler to use the empty function from the standard library:
2356 /// use std::{slice, option};
2357 /// let a: slice::Iter<i32> = [].iter();
2358 /// let f: option::IntoIter<i32> = None.into_iter();
2363 /// let a: iter::Empty<i32> = iter::empty();
2364 /// let b: iter::Empty<i32> = iter::empty();
2367 /// ### Known problems
2369 /// The type of the resulting iterator might become incompatible with its usage
2370 #[clippy::version = "1.64.0"]
2371 pub ITER_ON_EMPTY_COLLECTIONS,
2373 "Iterator for empty array"
2376 declare_clippy_lint! {
2377 /// ### What it does
2378 /// Checks for naive byte counts
2380 /// ### Why is this bad?
2381 /// The [`bytecount`](https://crates.io/crates/bytecount)
2382 /// crate has methods to count your bytes faster, especially for large slices.
2384 /// ### Known problems
2385 /// If you have predominantly small slices, the
2386 /// `bytecount::count(..)` method may actually be slower. However, if you can
2387 /// ensure that less than 2³²-1 matches arise, the `naive_count_32(..)` can be
2388 /// faster in those cases.
2392 /// # let vec = vec![1_u8];
2393 /// let count = vec.iter().filter(|x| **x == 0u8).count();
2398 /// # let vec = vec![1_u8];
2399 /// let count = bytecount::count(&vec, 0u8);
2401 #[clippy::version = "pre 1.29.0"]
2402 pub NAIVE_BYTECOUNT,
2404 "use of naive `<slice>.filter(|&x| x == y).count()` to count byte values"
2407 declare_clippy_lint! {
2408 /// ### What it does
2409 /// It checks for `str::bytes().count()` and suggests replacing it with
2412 /// ### Why is this bad?
2413 /// `str::bytes().count()` is longer and may not be as performant as using
2418 /// "hello".bytes().count();
2419 /// String::from("hello").bytes().count();
2424 /// String::from("hello").len();
2426 #[clippy::version = "1.62.0"]
2427 pub BYTES_COUNT_TO_LEN,
2429 "Using `bytes().count()` when `len()` performs the same functionality"
2432 declare_clippy_lint! {
2433 /// ### What it does
2434 /// Checks for calls to `ends_with` with possible file extensions
2435 /// and suggests to use a case-insensitive approach instead.
2437 /// ### Why is this bad?
2438 /// `ends_with` is case-sensitive and may not detect files with a valid extension.
2442 /// fn is_rust_file(filename: &str) -> bool {
2443 /// filename.ends_with(".rs")
2448 /// fn is_rust_file(filename: &str) -> bool {
2449 /// let filename = std::path::Path::new(filename);
2450 /// filename.extension()
2451 /// .map_or(false, |ext| ext.eq_ignore_ascii_case("rs"))
2454 #[clippy::version = "1.51.0"]
2455 pub CASE_SENSITIVE_FILE_EXTENSION_COMPARISONS,
2457 "Checks for calls to ends_with with case-sensitive file extensions"
2460 pub struct Methods {
2461 avoid_breaking_exported_api: bool,
2462 msrv: Option<RustcVersion>,
2463 allow_expect_in_tests: bool,
2464 allow_unwrap_in_tests: bool,
2470 avoid_breaking_exported_api: bool,
2471 msrv: Option<RustcVersion>,
2472 allow_expect_in_tests: bool,
2473 allow_unwrap_in_tests: bool,
2476 avoid_breaking_exported_api,
2478 allow_expect_in_tests,
2479 allow_unwrap_in_tests,
2484 impl_lint_pass!(Methods => [
2487 SHOULD_IMPLEMENT_TRAIT,
2488 WRONG_SELF_CONVENTION,
2490 UNWRAP_OR_ELSE_DEFAULT,
2492 RESULT_MAP_OR_INTO_OPTION,
2494 BIND_INSTEAD_OF_MAP,
2503 ITER_OVEREAGER_CLONED,
2504 CLONED_INSTEAD_OF_COPIED,
2506 INEFFICIENT_TO_STRING,
2508 SINGLE_CHAR_PATTERN,
2509 SINGLE_CHAR_ADD_STR,
2513 FILTER_MAP_IDENTITY,
2521 ITERATOR_STEP_BY_ZERO,
2530 STRING_EXTEND_CHARS,
2531 ITER_CLONED_COLLECT,
2535 UNNECESSARY_FILTER_MAP,
2536 UNNECESSARY_FIND_MAP,
2539 UNINIT_ASSUMED_INIT,
2540 MANUAL_SATURATING_ARITHMETIC,
2543 OPTION_AS_REF_DEREF,
2544 UNNECESSARY_LAZY_EVALUATIONS,
2545 MAP_COLLECT_RESULT_UNIT,
2546 FROM_ITER_INSTEAD_OF_COLLECT,
2554 UNNECESSARY_TO_OWNED,
2557 NEEDLESS_OPTION_AS_DEREF,
2558 IS_DIGIT_ASCII_RADIX,
2559 NEEDLESS_OPTION_TAKE,
2562 ITER_ON_SINGLE_ITEMS,
2563 ITER_ON_EMPTY_COLLECTIONS,
2566 CASE_SENSITIVE_FILE_EXTENSION_COMPARISONS,
2569 /// Extracts a method call name, args, and `Span` of the method name.
2570 fn method_call<'tcx>(recv: &'tcx hir::Expr<'tcx>) -> Option<(&'tcx str, &'tcx [hir::Expr<'tcx>], Span)> {
2571 if let ExprKind::MethodCall(path, args, _) = recv.kind {
2572 if !args.iter().any(|e| e.span.from_expansion()) {
2573 let name = path.ident.name.as_str();
2574 return Some((name, args, path.ident.span));
2580 impl<'tcx> LateLintPass<'tcx> for Methods {
2581 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) {
2582 if expr.span.from_expansion() {
2586 self.check_methods(cx, expr);
2589 hir::ExprKind::Call(func, args) => {
2590 from_iter_instead_of_collect::check(cx, expr, args, func);
2592 hir::ExprKind::MethodCall(method_call, args, _) => {
2593 let method_span = method_call.ident.span;
2594 or_fun_call::check(cx, expr, method_span, method_call.ident.as_str(), args);
2595 expect_fun_call::check(cx, expr, method_span, method_call.ident.as_str(), args);
2596 clone_on_copy::check(cx, expr, method_call.ident.name, args);
2597 clone_on_ref_ptr::check(cx, expr, method_call.ident.name, args);
2598 inefficient_to_string::check(cx, expr, method_call.ident.name, args);
2599 single_char_add_str::check(cx, expr, args);
2600 into_iter_on_ref::check(cx, expr, method_span, method_call.ident.name, args);
2601 single_char_pattern::check(cx, expr, method_call.ident.name, args);
2602 unnecessary_to_owned::check(cx, expr, method_call.ident.name, args, self.msrv);
2604 hir::ExprKind::Binary(op, lhs, rhs) if op.node == hir::BinOpKind::Eq || op.node == hir::BinOpKind::Ne => {
2605 let mut info = BinaryExprInfo {
2609 eq: op.node == hir::BinOpKind::Eq,
2611 lint_binary_expr_with_method_call(cx, &mut info);
2617 #[allow(clippy::too_many_lines)]
2618 fn check_impl_item(&mut self, cx: &LateContext<'tcx>, impl_item: &'tcx hir::ImplItem<'_>) {
2619 if in_external_macro(cx.sess(), impl_item.span) {
2622 let name = impl_item.ident.name.as_str();
2623 let parent = cx.tcx.hir().get_parent_item(impl_item.hir_id());
2624 let item = cx.tcx.hir().expect_item(parent);
2625 let self_ty = cx.tcx.type_of(item.def_id);
2627 let implements_trait = matches!(item.kind, hir::ItemKind::Impl(hir::Impl { of_trait: Some(_), .. }));
2629 if let hir::ImplItemKind::Fn(ref sig, id) = impl_item.kind;
2630 if let Some(first_arg) = iter_input_pats(sig.decl, cx.tcx.hir().body(id)).next();
2632 let method_sig = cx.tcx.fn_sig(impl_item.def_id);
2633 let method_sig = cx.tcx.erase_late_bound_regions(method_sig);
2635 let first_arg_ty = method_sig.inputs().iter().next();
2637 // check conventions w.r.t. conversion method names and predicates
2638 if let Some(first_arg_ty) = first_arg_ty;
2641 // if this impl block implements a trait, lint in trait definition instead
2642 if !implements_trait && cx.access_levels.is_exported(impl_item.def_id) {
2643 // check missing trait implementations
2644 for method_config in &TRAIT_METHODS {
2645 if name == method_config.method_name &&
2646 sig.decl.inputs.len() == method_config.param_count &&
2647 method_config.output_type.matches(&sig.decl.output) &&
2648 method_config.self_kind.matches(cx, self_ty, *first_arg_ty) &&
2649 fn_header_equals(method_config.fn_header, sig.header) &&
2650 method_config.lifetime_param_cond(impl_item)
2654 SHOULD_IMPLEMENT_TRAIT,
2657 "method `{}` can be confused for the standard trait method `{}::{}`",
2658 method_config.method_name,
2659 method_config.trait_name,
2660 method_config.method_name
2664 "consider implementing the trait `{}` or choosing a less ambiguous method name",
2665 method_config.trait_name
2672 if sig.decl.implicit_self.has_implicit_self()
2673 && !(self.avoid_breaking_exported_api
2674 && cx.access_levels.is_exported(impl_item.def_id))
2676 wrong_self_convention::check(
2689 // if this impl block implements a trait, lint in trait definition instead
2690 if implements_trait {
2694 if let hir::ImplItemKind::Fn(_, _) = impl_item.kind {
2695 let ret_ty = return_ty(cx, impl_item.hir_id());
2697 // walk the return type and check for Self (this does not check associated types)
2698 if let Some(self_adt) = self_ty.ty_adt_def() {
2699 if contains_adt_constructor(ret_ty, self_adt) {
2702 } else if contains_ty(ret_ty, self_ty) {
2706 // if return type is impl trait, check the associated types
2707 if let ty::Opaque(def_id, _) = *ret_ty.kind() {
2708 // one of the associated types must be Self
2709 for &(predicate, _span) in cx.tcx.explicit_item_bounds(def_id) {
2710 if let ty::PredicateKind::Projection(projection_predicate) = predicate.kind().skip_binder() {
2711 let assoc_ty = match projection_predicate.term {
2712 ty::Term::Ty(ty) => ty,
2713 ty::Term::Const(_c) => continue,
2715 // walk the associated type and check for Self
2716 if let Some(self_adt) = self_ty.ty_adt_def() {
2717 if contains_adt_constructor(assoc_ty, self_adt) {
2720 } else if contains_ty(assoc_ty, self_ty) {
2727 if name == "new" && ret_ty != self_ty {
2732 "methods called `new` usually return `Self`",
2738 fn check_trait_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx TraitItem<'_>) {
2739 if in_external_macro(cx.tcx.sess, item.span) {
2744 if let TraitItemKind::Fn(ref sig, _) = item.kind;
2745 if sig.decl.implicit_self.has_implicit_self();
2746 if let Some(first_arg_ty) = sig.decl.inputs.iter().next();
2749 let first_arg_span = first_arg_ty.span;
2750 let first_arg_ty = hir_ty_to_ty(cx.tcx, first_arg_ty);
2751 let self_ty = TraitRef::identity(cx.tcx, item.def_id.to_def_id()).self_ty().skip_binder();
2752 wrong_self_convention::check(
2754 item.ident.name.as_str(),
2765 if item.ident.name == sym::new;
2766 if let TraitItemKind::Fn(_, _) = item.kind;
2767 let ret_ty = return_ty(cx, item.hir_id());
2768 let self_ty = TraitRef::identity(cx.tcx, item.def_id.to_def_id()).self_ty().skip_binder();
2769 if !contains_ty(ret_ty, self_ty);
2776 "methods called `new` usually return `Self`",
2782 extract_msrv_attr!(LateContext);
2786 #[allow(clippy::too_many_lines)]
2787 fn check_methods<'tcx>(&self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
2788 if let Some((name, [recv, args @ ..], span)) = method_call(expr) {
2789 match (name, args) {
2790 ("add" | "offset" | "sub" | "wrapping_offset" | "wrapping_add" | "wrapping_sub", [_arg]) => {
2791 zst_offset::check(cx, expr, recv);
2793 ("and_then", [arg]) => {
2794 let biom_option_linted = bind_instead_of_map::OptionAndThenSome::check(cx, expr, recv, arg);
2795 let biom_result_linted = bind_instead_of_map::ResultAndThenOk::check(cx, expr, recv, arg);
2796 if !biom_option_linted && !biom_result_linted {
2797 unnecessary_lazy_eval::check(cx, expr, recv, arg, "and");
2800 ("as_deref" | "as_deref_mut", []) => {
2801 needless_option_as_deref::check(cx, expr, recv, name);
2803 ("as_mut", []) => useless_asref::check(cx, expr, "as_mut", recv),
2804 ("as_ref", []) => useless_asref::check(cx, expr, "as_ref", recv),
2805 ("assume_init", []) => uninit_assumed_init::check(cx, expr, recv),
2806 ("cloned", []) => cloned_instead_of_copied::check(cx, expr, recv, span, self.msrv),
2807 ("collect", []) => match method_call(recv) {
2808 Some((name @ ("cloned" | "copied"), [recv2], _)) => {
2809 iter_cloned_collect::check(cx, name, expr, recv2);
2811 Some(("map", [m_recv, m_arg], _)) => {
2812 map_collect_result_unit::check(cx, expr, m_recv, m_arg, recv);
2814 Some(("take", [take_self_arg, take_arg], _)) => {
2815 if meets_msrv(self.msrv, msrvs::STR_REPEAT) {
2816 manual_str_repeat::check(cx, expr, recv, take_self_arg, take_arg);
2821 ("count", []) if is_trait_method(cx, expr, sym::Iterator) => match method_call(recv) {
2822 Some(("cloned", [recv2], _)) => iter_overeager_cloned::check(cx, expr, recv, recv2, true, false),
2823 Some((name2 @ ("into_iter" | "iter" | "iter_mut"), [recv2], _)) => {
2824 iter_count::check(cx, expr, recv2, name2);
2826 Some(("map", [_, arg], _)) => suspicious_map::check(cx, expr, recv, arg),
2827 Some(("filter", [recv2, arg], _)) => bytecount::check(cx, expr, recv2, arg),
2828 Some(("bytes", [recv2], _)) => bytes_count_to_len::check(cx, expr, recv, recv2),
2831 ("drain", [arg]) => {
2832 iter_with_drain::check(cx, expr, recv, span, arg);
2834 ("ends_with", [arg]) => {
2835 if let ExprKind::MethodCall(_, _, span) = expr.kind {
2836 case_sensitive_file_extension_comparisons::check(cx, expr, span, recv, arg);
2838 ("expect", [_]) => match method_call(recv) {
2839 Some(("ok", [recv], _)) => ok_expect::check(cx, expr, recv),
2840 Some(("err", [recv], err_span)) => err_expect::check(cx, expr, recv, self.msrv, span, err_span),
2841 _ => expect_used::check(cx, expr, recv, false, self.allow_expect_in_tests),
2843 ("expect_err", [_]) => expect_used::check(cx, expr, recv, true, self.allow_expect_in_tests),
2844 ("extend", [arg]) => {
2845 string_extend_chars::check(cx, expr, recv, arg);
2846 extend_with_drain::check(cx, expr, recv, arg);
2848 ("filter_map", [arg]) => {
2849 unnecessary_filter_map::check(cx, expr, arg, name);
2850 filter_map_identity::check(cx, expr, arg, span);
2852 ("find_map", [arg]) => {
2853 unnecessary_filter_map::check(cx, expr, arg, name);
2855 ("flat_map", [arg]) => {
2856 flat_map_identity::check(cx, expr, arg, span);
2857 flat_map_option::check(cx, expr, arg, span);
2859 ("flatten", []) => match method_call(recv) {
2860 Some(("map", [recv, map_arg], map_span)) => map_flatten::check(cx, expr, recv, map_arg, map_span),
2861 Some(("cloned", [recv2], _)) => iter_overeager_cloned::check(cx, expr, recv, recv2, false, true),
2864 ("fold", [init, acc]) => unnecessary_fold::check(cx, expr, init, acc, span),
2865 ("for_each", [_]) => {
2866 if let Some(("inspect", [_, _], span2)) = method_call(recv) {
2867 inspect_for_each::check(cx, expr, span2);
2870 ("get", [arg]) => get_last_with_len::check(cx, expr, recv, arg),
2871 ("get_or_insert_with", [arg]) => unnecessary_lazy_eval::check(cx, expr, recv, arg, "get_or_insert"),
2872 ("is_file", []) => filetype_is_file::check(cx, expr, recv),
2873 ("is_digit", [radix]) => is_digit_ascii_radix::check(cx, expr, recv, radix, self.msrv),
2874 ("is_none", []) => check_is_some_is_none(cx, expr, recv, false),
2875 ("is_some", []) => check_is_some_is_none(cx, expr, recv, true),
2876 ("iter" | "iter_mut" | "into_iter", []) => {
2877 iter_on_single_or_empty_collections::check(cx, expr, name, recv);
2879 ("join", [join_arg]) => {
2880 if let Some(("collect", _, span)) = method_call(recv) {
2881 unnecessary_join::check(cx, expr, recv, join_arg, span);
2884 ("last", []) | ("skip", [_]) => {
2885 if let Some((name2, [recv2, args2 @ ..], _span2)) = method_call(recv) {
2886 if let ("cloned", []) = (name2, args2) {
2887 iter_overeager_cloned::check(cx, expr, recv, recv2, false, false);
2891 (name @ ("map" | "map_err"), [m_arg]) => {
2892 if let Some((name, [recv2, args @ ..], span2)) = method_call(recv) {
2893 match (name, args) {
2894 ("as_mut", []) => option_as_ref_deref::check(cx, expr, recv2, m_arg, true, self.msrv),
2895 ("as_ref", []) => option_as_ref_deref::check(cx, expr, recv2, m_arg, false, self.msrv),
2896 ("filter", [f_arg]) => {
2897 filter_map::check(cx, expr, recv2, f_arg, span2, recv, m_arg, span, false);
2899 ("find", [f_arg]) => {
2900 filter_map::check(cx, expr, recv2, f_arg, span2, recv, m_arg, span, true);
2905 map_identity::check(cx, expr, recv, m_arg, name, span);
2907 ("map_or", [def, map]) => option_map_or_none::check(cx, expr, recv, def, map),
2909 if let Some((name2, [recv2, args2 @ ..], _)) = method_call(recv) {
2910 match (name2, args2) {
2911 ("cloned", []) => iter_overeager_cloned::check(cx, expr, recv, recv2, false, false),
2912 ("filter", [arg]) => filter_next::check(cx, expr, recv2, arg),
2913 ("filter_map", [arg]) => filter_map_next::check(cx, expr, recv2, arg, self.msrv),
2914 ("iter", []) => iter_next_slice::check(cx, expr, recv2),
2915 ("skip", [arg]) => iter_skip_next::check(cx, expr, recv2, arg),
2916 ("skip_while", [_]) => skip_while_next::check(cx, expr),
2921 ("nth", [n_arg]) => match method_call(recv) {
2922 Some(("bytes", [recv2], _)) => bytes_nth::check(cx, expr, recv2, n_arg),
2923 Some(("cloned", [recv2], _)) => iter_overeager_cloned::check(cx, expr, recv, recv2, false, false),
2924 Some(("iter", [recv2], _)) => iter_nth::check(cx, expr, recv2, recv, n_arg, false),
2925 Some(("iter_mut", [recv2], _)) => iter_nth::check(cx, expr, recv2, recv, n_arg, true),
2926 _ => iter_nth_zero::check(cx, expr, recv, n_arg),
2928 ("ok_or_else", [arg]) => unnecessary_lazy_eval::check(cx, expr, recv, arg, "ok_or"),
2929 ("or_else", [arg]) => {
2930 if !bind_instead_of_map::ResultOrElseErrInfo::check(cx, expr, recv, arg) {
2931 unnecessary_lazy_eval::check(cx, expr, recv, arg, "or");
2934 ("splitn" | "rsplitn", [count_arg, pat_arg]) => {
2935 if let Some((Constant::Int(count), _)) = constant(cx, cx.typeck_results(), count_arg) {
2936 suspicious_splitn::check(cx, name, expr, recv, count);
2937 str_splitn::check(cx, name, expr, recv, pat_arg, count, self.msrv);
2940 ("splitn_mut" | "rsplitn_mut", [count_arg, _]) => {
2941 if let Some((Constant::Int(count), _)) = constant(cx, cx.typeck_results(), count_arg) {
2942 suspicious_splitn::check(cx, name, expr, recv, count);
2945 ("step_by", [arg]) => iterator_step_by_zero::check(cx, expr, arg),
2946 ("take", [_arg]) => {
2947 if let Some((name2, [recv2, args2 @ ..], _span2)) = method_call(recv) {
2948 if let ("cloned", []) = (name2, args2) {
2949 iter_overeager_cloned::check(cx, expr, recv, recv2, false, false);
2953 ("take", []) => needless_option_take::check(cx, expr, recv),
2954 ("then", [arg]) => {
2955 if !meets_msrv(self.msrv, msrvs::BOOL_THEN_SOME) {
2958 unnecessary_lazy_eval::check(cx, expr, recv, arg, "then_some");
2960 ("to_os_string" | "to_owned" | "to_path_buf" | "to_vec", []) => {
2961 implicit_clone::check(cx, name, expr, recv);
2964 match method_call(recv) {
2965 Some(("get", [recv, get_arg], _)) => {
2966 get_unwrap::check(cx, expr, recv, get_arg, false);
2968 Some(("get_mut", [recv, get_arg], _)) => {
2969 get_unwrap::check(cx, expr, recv, get_arg, true);
2971 Some(("or", [recv, or_arg], or_span)) => {
2972 or_then_unwrap::check(cx, expr, recv, or_arg, or_span);
2976 unwrap_used::check(cx, expr, recv, false, self.allow_unwrap_in_tests);
2978 ("unwrap_err", []) => unwrap_used::check(cx, expr, recv, true, self.allow_unwrap_in_tests),
2979 ("unwrap_or", [u_arg]) => match method_call(recv) {
2980 Some((arith @ ("checked_add" | "checked_sub" | "checked_mul"), [lhs, rhs], _)) => {
2981 manual_saturating_arithmetic::check(cx, expr, lhs, rhs, u_arg, &arith["checked_".len()..]);
2983 Some(("map", [m_recv, m_arg], span)) => {
2984 option_map_unwrap_or::check(cx, expr, m_recv, m_arg, recv, u_arg, span);
2986 Some(("then_some", [t_recv, t_arg], _)) => {
2987 obfuscated_if_else::check(cx, expr, t_recv, t_arg, u_arg);
2991 ("unwrap_or_else", [u_arg]) => match method_call(recv) {
2992 Some(("map", [recv, map_arg], _))
2993 if map_unwrap_or::check(cx, expr, recv, map_arg, u_arg, self.msrv) => {},
2995 unwrap_or_else_default::check(cx, expr, recv, u_arg);
2996 unnecessary_lazy_eval::check(cx, expr, recv, u_arg, "unwrap_or");
2999 ("replace" | "replacen", [arg1, arg2] | [arg1, arg2, _]) => {
3000 no_effect_replace::check(cx, expr, arg1, arg2);
3008 fn check_is_some_is_none(cx: &LateContext<'_>, expr: &Expr<'_>, recv: &Expr<'_>, is_some: bool) {
3009 if let Some((name @ ("find" | "position" | "rposition"), [f_recv, arg], span)) = method_call(recv) {
3010 search_is_some::check(cx, expr, name, is_some, f_recv, arg, recv, span);
3014 /// Used for `lint_binary_expr_with_method_call`.
3015 #[derive(Copy, Clone)]
3016 struct BinaryExprInfo<'a> {
3017 expr: &'a hir::Expr<'a>,
3018 chain: &'a hir::Expr<'a>,
3019 other: &'a hir::Expr<'a>,
3023 /// Checks for the `CHARS_NEXT_CMP` and `CHARS_LAST_CMP` lints.
3024 fn lint_binary_expr_with_method_call(cx: &LateContext<'_>, info: &mut BinaryExprInfo<'_>) {
3025 macro_rules! lint_with_both_lhs_and_rhs {
3026 ($func:expr, $cx:expr, $info:ident) => {
3027 if !$func($cx, $info) {
3028 ::std::mem::swap(&mut $info.chain, &mut $info.other);
3029 if $func($cx, $info) {
3036 lint_with_both_lhs_and_rhs!(chars_next_cmp::check, cx, info);
3037 lint_with_both_lhs_and_rhs!(chars_last_cmp::check, cx, info);
3038 lint_with_both_lhs_and_rhs!(chars_next_cmp_with_unwrap::check, cx, info);
3039 lint_with_both_lhs_and_rhs!(chars_last_cmp_with_unwrap::check, cx, info);
3042 const FN_HEADER: hir::FnHeader = hir::FnHeader {
3043 unsafety: hir::Unsafety::Normal,
3044 constness: hir::Constness::NotConst,
3045 asyncness: hir::IsAsync::NotAsync,
3046 abi: rustc_target::spec::abi::Abi::Rust,
3049 struct ShouldImplTraitCase {
3050 trait_name: &'static str,
3051 method_name: &'static str,
3053 fn_header: hir::FnHeader,
3054 // implicit self kind expected (none, self, &self, ...)
3055 self_kind: SelfKind,
3056 // checks against the output type
3057 output_type: OutType,
3058 // certain methods with explicit lifetimes can't implement the equivalent trait method
3059 lint_explicit_lifetime: bool,
3061 impl ShouldImplTraitCase {
3063 trait_name: &'static str,
3064 method_name: &'static str,
3066 fn_header: hir::FnHeader,
3067 self_kind: SelfKind,
3068 output_type: OutType,
3069 lint_explicit_lifetime: bool,
3070 ) -> ShouldImplTraitCase {
3071 ShouldImplTraitCase {
3078 lint_explicit_lifetime,
3082 fn lifetime_param_cond(&self, impl_item: &hir::ImplItem<'_>) -> bool {
3083 self.lint_explicit_lifetime
3084 || !impl_item.generics.params.iter().any(|p| {
3087 hir::GenericParamKind::Lifetime {
3088 kind: hir::LifetimeParamKind::Explicit
3096 const TRAIT_METHODS: [ShouldImplTraitCase; 30] = [
3097 ShouldImplTraitCase::new("std::ops::Add", "add", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3098 ShouldImplTraitCase::new("std::convert::AsMut", "as_mut", 1, FN_HEADER, SelfKind::RefMut, OutType::Ref, true),
3099 ShouldImplTraitCase::new("std::convert::AsRef", "as_ref", 1, FN_HEADER, SelfKind::Ref, OutType::Ref, true),
3100 ShouldImplTraitCase::new("std::ops::BitAnd", "bitand", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3101 ShouldImplTraitCase::new("std::ops::BitOr", "bitor", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3102 ShouldImplTraitCase::new("std::ops::BitXor", "bitxor", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3103 ShouldImplTraitCase::new("std::borrow::Borrow", "borrow", 1, FN_HEADER, SelfKind::Ref, OutType::Ref, true),
3104 ShouldImplTraitCase::new("std::borrow::BorrowMut", "borrow_mut", 1, FN_HEADER, SelfKind::RefMut, OutType::Ref, true),
3105 ShouldImplTraitCase::new("std::clone::Clone", "clone", 1, FN_HEADER, SelfKind::Ref, OutType::Any, true),
3106 ShouldImplTraitCase::new("std::cmp::Ord", "cmp", 2, FN_HEADER, SelfKind::Ref, OutType::Any, true),
3107 // FIXME: default doesn't work
3108 ShouldImplTraitCase::new("std::default::Default", "default", 0, FN_HEADER, SelfKind::No, OutType::Any, true),
3109 ShouldImplTraitCase::new("std::ops::Deref", "deref", 1, FN_HEADER, SelfKind::Ref, OutType::Ref, true),
3110 ShouldImplTraitCase::new("std::ops::DerefMut", "deref_mut", 1, FN_HEADER, SelfKind::RefMut, OutType::Ref, true),
3111 ShouldImplTraitCase::new("std::ops::Div", "div", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3112 ShouldImplTraitCase::new("std::ops::Drop", "drop", 1, FN_HEADER, SelfKind::RefMut, OutType::Unit, true),
3113 ShouldImplTraitCase::new("std::cmp::PartialEq", "eq", 2, FN_HEADER, SelfKind::Ref, OutType::Bool, true),
3114 ShouldImplTraitCase::new("std::iter::FromIterator", "from_iter", 1, FN_HEADER, SelfKind::No, OutType::Any, true),
3115 ShouldImplTraitCase::new("std::str::FromStr", "from_str", 1, FN_HEADER, SelfKind::No, OutType::Any, true),
3116 ShouldImplTraitCase::new("std::hash::Hash", "hash", 2, FN_HEADER, SelfKind::Ref, OutType::Unit, true),
3117 ShouldImplTraitCase::new("std::ops::Index", "index", 2, FN_HEADER, SelfKind::Ref, OutType::Ref, true),
3118 ShouldImplTraitCase::new("std::ops::IndexMut", "index_mut", 2, FN_HEADER, SelfKind::RefMut, OutType::Ref, true),
3119 ShouldImplTraitCase::new("std::iter::IntoIterator", "into_iter", 1, FN_HEADER, SelfKind::Value, OutType::Any, true),
3120 ShouldImplTraitCase::new("std::ops::Mul", "mul", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3121 ShouldImplTraitCase::new("std::ops::Neg", "neg", 1, FN_HEADER, SelfKind::Value, OutType::Any, true),
3122 ShouldImplTraitCase::new("std::iter::Iterator", "next", 1, FN_HEADER, SelfKind::RefMut, OutType::Any, false),
3123 ShouldImplTraitCase::new("std::ops::Not", "not", 1, FN_HEADER, SelfKind::Value, OutType::Any, true),
3124 ShouldImplTraitCase::new("std::ops::Rem", "rem", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3125 ShouldImplTraitCase::new("std::ops::Shl", "shl", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3126 ShouldImplTraitCase::new("std::ops::Shr", "shr", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3127 ShouldImplTraitCase::new("std::ops::Sub", "sub", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3130 #[derive(Clone, Copy, PartialEq, Eq, Debug)]
3139 fn matches<'a>(self, cx: &LateContext<'a>, parent_ty: Ty<'a>, ty: Ty<'a>) -> bool {
3140 fn matches_value<'a>(cx: &LateContext<'a>, parent_ty: Ty<'a>, ty: Ty<'a>) -> bool {
3141 if ty == parent_ty {
3143 } else if ty.is_box() {
3144 ty.boxed_ty() == parent_ty
3145 } else if is_type_diagnostic_item(cx, ty, sym::Rc) || is_type_diagnostic_item(cx, ty, sym::Arc) {
3146 if let ty::Adt(_, substs) = ty.kind() {
3147 substs.types().next().map_or(false, |t| t == parent_ty)
3156 fn matches_ref<'a>(cx: &LateContext<'a>, mutability: hir::Mutability, parent_ty: Ty<'a>, ty: Ty<'a>) -> bool {
3157 if let ty::Ref(_, t, m) = *ty.kind() {
3158 return m == mutability && t == parent_ty;
3161 let trait_path = match mutability {
3162 hir::Mutability::Not => &paths::ASREF_TRAIT,
3163 hir::Mutability::Mut => &paths::ASMUT_TRAIT,
3166 let trait_def_id = match get_trait_def_id(cx, trait_path) {
3168 None => return false,
3170 implements_trait(cx, ty, trait_def_id, &[parent_ty.into()])
3173 fn matches_none<'a>(cx: &LateContext<'a>, parent_ty: Ty<'a>, ty: Ty<'a>) -> bool {
3174 !matches_value(cx, parent_ty, ty)
3175 && !matches_ref(cx, hir::Mutability::Not, parent_ty, ty)
3176 && !matches_ref(cx, hir::Mutability::Mut, parent_ty, ty)
3180 Self::Value => matches_value(cx, parent_ty, ty),
3181 Self::Ref => matches_ref(cx, hir::Mutability::Not, parent_ty, ty) || ty == parent_ty && is_copy(cx, ty),
3182 Self::RefMut => matches_ref(cx, hir::Mutability::Mut, parent_ty, ty),
3183 Self::No => matches_none(cx, parent_ty, ty),
3188 fn description(self) -> &'static str {
3190 Self::Value => "`self` by value",
3191 Self::Ref => "`self` by reference",
3192 Self::RefMut => "`self` by mutable reference",
3193 Self::No => "no `self`",
3198 #[derive(Clone, Copy)]
3207 fn matches(self, ty: &hir::FnRetTy<'_>) -> bool {
3208 let is_unit = |ty: &hir::Ty<'_>| matches!(ty.kind, hir::TyKind::Tup(&[]));
3210 (Self::Unit, &hir::FnRetTy::DefaultReturn(_)) => true,
3211 (Self::Unit, &hir::FnRetTy::Return(ty)) if is_unit(ty) => true,
3212 (Self::Bool, &hir::FnRetTy::Return(ty)) if is_bool(ty) => true,
3213 (Self::Any, &hir::FnRetTy::Return(ty)) if !is_unit(ty) => true,
3214 (Self::Ref, &hir::FnRetTy::Return(ty)) => matches!(ty.kind, hir::TyKind::Rptr(_, _)),
3220 fn is_bool(ty: &hir::Ty<'_>) -> bool {
3221 if let hir::TyKind::Path(QPath::Resolved(_, path)) = ty.kind {
3222 matches!(path.res, Res::PrimTy(PrimTy::Bool))
3228 fn fn_header_equals(expected: hir::FnHeader, actual: hir::FnHeader) -> bool {
3229 expected.constness == actual.constness
3230 && expected.unsafety == actual.unsafety
3231 && expected.asyncness == actual.asyncness