1 mod bind_instead_of_map;
4 mod chars_cmp_with_unwrap;
6 mod chars_last_cmp_with_unwrap;
8 mod chars_next_cmp_with_unwrap;
11 mod cloned_instead_of_copied;
15 mod extend_with_drain;
18 mod filter_map_identity;
21 mod flat_map_identity;
23 mod from_iter_instead_of_collect;
24 mod get_last_with_len;
27 mod inefficient_to_string;
30 mod is_digit_ascii_radix;
31 mod iter_cloned_collect;
36 mod iter_overeager_cloned;
39 mod iterator_step_by_zero;
40 mod manual_saturating_arithmetic;
41 mod manual_str_repeat;
42 mod map_collect_result_unit;
46 mod needless_option_as_deref;
47 mod needless_option_take;
48 mod no_effect_replace;
50 mod option_as_ref_deref;
51 mod option_map_or_none;
52 mod option_map_unwrap_or;
56 mod single_char_add_str;
57 mod single_char_insert_string;
58 mod single_char_pattern;
59 mod single_char_push_string;
62 mod string_extend_chars;
64 mod suspicious_splitn;
65 mod uninit_assumed_init;
66 mod unnecessary_filter_map;
68 mod unnecessary_iter_cloned;
70 mod unnecessary_lazy_eval;
71 mod unnecessary_to_owned;
72 mod unwrap_or_else_default;
76 mod wrong_self_convention;
79 use bind_instead_of_map::BindInsteadOfMap;
80 use clippy_utils::consts::{constant, Constant};
81 use clippy_utils::diagnostics::{span_lint, span_lint_and_help};
82 use clippy_utils::ty::{contains_adt_constructor, contains_ty, implements_trait, is_copy, is_type_diagnostic_item};
83 use clippy_utils::{contains_return, get_trait_def_id, iter_input_pats, meets_msrv, msrvs, paths, return_ty};
84 use if_chain::if_chain;
86 use rustc_hir::def::Res;
87 use rustc_hir::{Expr, ExprKind, PrimTy, QPath, TraitItem, TraitItemKind};
88 use rustc_lint::{LateContext, LateLintPass, LintContext};
89 use rustc_middle::lint::in_external_macro;
90 use rustc_middle::ty::{self, TraitRef, Ty};
91 use rustc_semver::RustcVersion;
92 use rustc_session::{declare_tool_lint, impl_lint_pass};
93 use rustc_span::{sym, Span};
94 use rustc_typeck::hir_ty_to_ty;
96 declare_clippy_lint! {
98 /// Checks for usages of `cloned()` on an `Iterator` or `Option` where
99 /// `copied()` could be used instead.
101 /// ### Why is this bad?
102 /// `copied()` is better because it guarantees that the type being cloned
103 /// implements `Copy`.
107 /// [1, 2, 3].iter().cloned();
111 /// [1, 2, 3].iter().copied();
113 #[clippy::version = "1.53.0"]
114 pub CLONED_INSTEAD_OF_COPIED,
116 "used `cloned` where `copied` could be used instead"
119 declare_clippy_lint! {
121 /// Checks for usage of `_.cloned().<func>()` where call to `.cloned()` can be postponed.
123 /// ### Why is this bad?
124 /// It's often inefficient to clone all elements of an iterator, when eventually, only some
125 /// of them will be consumed.
129 /// # let vec = vec!["string".to_string()];
132 /// vec.iter().cloned().take(10);
135 /// vec.iter().take(10).cloned();
138 /// vec.iter().cloned().last();
141 /// vec.iter().last().cloned();
144 /// ### Known Problems
145 /// This `lint` removes the side of effect of cloning items in the iterator.
146 /// A code that relies on that side-effect could fail.
148 #[clippy::version = "1.59.0"]
149 pub ITER_OVEREAGER_CLONED,
151 "using `cloned()` early with `Iterator::iter()` can lead to some performance inefficiencies"
154 declare_clippy_lint! {
156 /// Checks for usages of `Iterator::flat_map()` where `filter_map()` could be
159 /// ### Why is this bad?
160 /// When applicable, `filter_map()` is more clear since it shows that
161 /// `Option` is used to produce 0 or 1 items.
165 /// let nums: Vec<i32> = ["1", "2", "whee!"].iter().flat_map(|x| x.parse().ok()).collect();
169 /// let nums: Vec<i32> = ["1", "2", "whee!"].iter().filter_map(|x| x.parse().ok()).collect();
171 #[clippy::version = "1.53.0"]
174 "used `flat_map` where `filter_map` could be used instead"
177 declare_clippy_lint! {
179 /// Checks for `.unwrap()` calls on `Option`s and on `Result`s.
181 /// ### Why is this bad?
182 /// It is better to handle the `None` or `Err` case,
183 /// or at least call `.expect(_)` with a more helpful message. Still, for a lot of
184 /// quick-and-dirty code, `unwrap` is a good choice, which is why this lint is
185 /// `Allow` by default.
187 /// `result.unwrap()` will let the thread panic on `Err` values.
188 /// Normally, you want to implement more sophisticated error handling,
189 /// and propagate errors upwards with `?` operator.
191 /// Even if you want to panic on errors, not all `Error`s implement good
192 /// messages on display. Therefore, it may be beneficial to look at the places
193 /// where they may get displayed. Activate this lint to do just that.
197 /// # let opt = Some(1);
203 /// opt.expect("more helpful message");
209 /// # let res: Result<usize, ()> = Ok(1);
215 /// res.expect("more helpful message");
217 #[clippy::version = "1.45.0"]
220 "using `.unwrap()` on `Result` or `Option`, which should at least get a better message using `expect()`"
223 declare_clippy_lint! {
225 /// Checks for `.expect()` calls on `Option`s and `Result`s.
227 /// ### Why is this bad?
228 /// Usually it is better to handle the `None` or `Err` case.
229 /// Still, for a lot of quick-and-dirty code, `expect` is a good choice, which is why
230 /// this lint is `Allow` by default.
232 /// `result.expect()` will let the thread panic on `Err`
233 /// values. Normally, you want to implement more sophisticated error handling,
234 /// and propagate errors upwards with `?` operator.
238 /// # let opt = Some(1);
241 /// opt.expect("one");
244 /// let opt = Some(1);
251 /// # let res: Result<usize, ()> = Ok(1);
254 /// res.expect("one");
258 /// # Ok::<(), ()>(())
260 #[clippy::version = "1.45.0"]
263 "using `.expect()` on `Result` or `Option`, which might be better handled"
266 declare_clippy_lint! {
268 /// Checks for methods that should live in a trait
269 /// implementation of a `std` trait (see [llogiq's blog
270 /// post](http://llogiq.github.io/2015/07/30/traits.html) for further
271 /// information) instead of an inherent implementation.
273 /// ### Why is this bad?
274 /// Implementing the traits improve ergonomics for users of
275 /// the code, often with very little cost. Also people seeing a `mul(...)`
277 /// may expect `*` to work equally, so you should have good reason to disappoint
284 /// fn add(&self, other: &X) -> X {
290 #[clippy::version = "pre 1.29.0"]
291 pub SHOULD_IMPLEMENT_TRAIT,
293 "defining a method that should be implementing a std trait"
296 declare_clippy_lint! {
298 /// Checks for methods with certain name prefixes and which
299 /// doesn't match how self is taken. The actual rules are:
301 /// |Prefix |Postfix |`self` taken | `self` type |
302 /// |-------|------------|-------------------------------|--------------|
303 /// |`as_` | none |`&self` or `&mut self` | any |
304 /// |`from_`| none | none | any |
305 /// |`into_`| none |`self` | any |
306 /// |`is_` | none |`&mut self` or `&self` or none | any |
307 /// |`to_` | `_mut` |`&mut self` | any |
308 /// |`to_` | not `_mut` |`self` | `Copy` |
309 /// |`to_` | not `_mut` |`&self` | not `Copy` |
311 /// Note: Clippy doesn't trigger methods with `to_` prefix in:
312 /// - Traits definition.
313 /// Clippy can not tell if a type that implements a trait is `Copy` or not.
314 /// - Traits implementation, when `&self` is taken.
315 /// The method signature is controlled by the trait and often `&self` is required for all types that implement the trait
316 /// (see e.g. the `std::string::ToString` trait).
318 /// Clippy allows `Pin<&Self>` and `Pin<&mut Self>` if `&self` and `&mut self` is required.
320 /// Please find more info here:
321 /// https://rust-lang.github.io/api-guidelines/naming.html#ad-hoc-conversions-follow-as_-to_-into_-conventions-c-conv
323 /// ### Why is this bad?
324 /// Consistency breeds readability. If you follow the
325 /// conventions, your users won't be surprised that they, e.g., need to supply a
326 /// mutable reference to a `as_..` function.
332 /// fn as_str(self) -> &'static str {
338 #[clippy::version = "pre 1.29.0"]
339 pub WRONG_SELF_CONVENTION,
341 "defining a method named with an established prefix (like \"into_\") that takes `self` with the wrong convention"
344 declare_clippy_lint! {
346 /// Checks for usage of `ok().expect(..)`.
348 /// ### Why is this bad?
349 /// Because you usually call `expect()` on the `Result`
350 /// directly to get a better error message.
352 /// ### Known problems
353 /// The error type needs to implement `Debug`
357 /// # let x = Ok::<_, ()>(());
360 /// x.ok().expect("why did I do this again?");
363 /// x.expect("why did I do this again?");
365 #[clippy::version = "pre 1.29.0"]
368 "using `ok().expect()`, which gives worse error messages than calling `expect` directly on the Result"
371 declare_clippy_lint! {
373 /// Checks for `.err().expect()` calls on the `Result` type.
375 /// ### Why is this bad?
376 /// `.expect_err()` can be called directly to avoid the extra type conversion from `err()`.
380 /// let x: Result<u32, &str> = Ok(10);
381 /// x.err().expect("Testing err().expect()");
385 /// let x: Result<u32, &str> = Ok(10);
386 /// x.expect_err("Testing expect_err");
388 #[clippy::version = "1.61.0"]
391 r#"using `.err().expect("")` when `.expect_err("")` can be used"#
394 declare_clippy_lint! {
396 /// Checks for usages of `_.unwrap_or_else(Default::default)` on `Option` and
399 /// ### Why is this bad?
400 /// Readability, these can be written as `_.unwrap_or_default`, which is
401 /// simpler and more concise.
405 /// # let x = Some(1);
408 /// x.unwrap_or_else(Default::default);
409 /// x.unwrap_or_else(u32::default);
412 /// x.unwrap_or_default();
414 #[clippy::version = "1.56.0"]
415 pub UNWRAP_OR_ELSE_DEFAULT,
417 "using `.unwrap_or_else(Default::default)`, which is more succinctly expressed as `.unwrap_or_default()`"
420 declare_clippy_lint! {
422 /// Checks for usage of `option.map(_).unwrap_or(_)` or `option.map(_).unwrap_or_else(_)` or
423 /// `result.map(_).unwrap_or_else(_)`.
425 /// ### Why is this bad?
426 /// Readability, these can be written more concisely (resp.) as
427 /// `option.map_or(_, _)`, `option.map_or_else(_, _)` and `result.map_or_else(_, _)`.
429 /// ### Known problems
430 /// The order of the arguments is not in execution order
434 /// # let x = Some(1);
437 /// x.map(|a| a + 1).unwrap_or(0);
440 /// x.map_or(0, |a| a + 1);
446 /// # let x: Result<usize, ()> = Ok(1);
447 /// # fn some_function(foo: ()) -> usize { 1 }
450 /// x.map(|a| a + 1).unwrap_or_else(some_function);
453 /// x.map_or_else(some_function, |a| a + 1);
455 #[clippy::version = "1.45.0"]
458 "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)`"
461 declare_clippy_lint! {
463 /// Checks for usage of `_.map_or(None, _)`.
465 /// ### Why is this bad?
466 /// Readability, this can be written more concisely as
469 /// ### Known problems
470 /// The order of the arguments is not in execution order.
474 /// # let opt = Some(1);
477 /// opt.map_or(None, |a| Some(a + 1));
480 /// opt.and_then(|a| Some(a + 1));
482 #[clippy::version = "pre 1.29.0"]
483 pub OPTION_MAP_OR_NONE,
485 "using `Option.map_or(None, f)`, which is more succinctly expressed as `and_then(f)`"
488 declare_clippy_lint! {
490 /// Checks for usage of `_.map_or(None, Some)`.
492 /// ### Why is this bad?
493 /// Readability, this can be written more concisely as
499 /// # let r: Result<u32, &str> = Ok(1);
500 /// assert_eq!(Some(1), r.map_or(None, Some));
505 /// # let r: Result<u32, &str> = Ok(1);
506 /// assert_eq!(Some(1), r.ok());
508 #[clippy::version = "1.44.0"]
509 pub RESULT_MAP_OR_INTO_OPTION,
511 "using `Result.map_or(None, Some)`, which is more succinctly expressed as `ok()`"
514 declare_clippy_lint! {
516 /// Checks for usage of `_.and_then(|x| Some(y))`, `_.and_then(|x| Ok(y))` or
517 /// `_.or_else(|x| Err(y))`.
519 /// ### Why is this bad?
520 /// Readability, this can be written more concisely as
521 /// `_.map(|x| y)` or `_.map_err(|x| y)`.
525 /// # fn opt() -> Option<&'static str> { Some("42") }
526 /// # fn res() -> Result<&'static str, &'static str> { Ok("42") }
527 /// let _ = opt().and_then(|s| Some(s.len()));
528 /// let _ = res().and_then(|s| if s.len() == 42 { Ok(10) } else { Ok(20) });
529 /// let _ = res().or_else(|s| if s.len() == 42 { Err(10) } else { Err(20) });
532 /// The correct use would be:
535 /// # fn opt() -> Option<&'static str> { Some("42") }
536 /// # fn res() -> Result<&'static str, &'static str> { Ok("42") }
537 /// let _ = opt().map(|s| s.len());
538 /// let _ = res().map(|s| if s.len() == 42 { 10 } else { 20 });
539 /// let _ = res().map_err(|s| if s.len() == 42 { 10 } else { 20 });
541 #[clippy::version = "1.45.0"]
542 pub BIND_INSTEAD_OF_MAP,
544 "using `Option.and_then(|x| Some(y))`, which is more succinctly expressed as `map(|x| y)`"
547 declare_clippy_lint! {
549 /// Checks for usage of `_.filter(_).next()`.
551 /// ### Why is this bad?
552 /// Readability, this can be written more concisely as
557 /// # let vec = vec![1];
558 /// vec.iter().filter(|x| **x == 0).next();
560 /// Could be written as
562 /// # let vec = vec![1];
563 /// vec.iter().find(|x| **x == 0);
565 #[clippy::version = "pre 1.29.0"]
568 "using `filter(p).next()`, which is more succinctly expressed as `.find(p)`"
571 declare_clippy_lint! {
573 /// Checks for usage of `_.skip_while(condition).next()`.
575 /// ### Why is this bad?
576 /// Readability, this can be written more concisely as
577 /// `_.find(!condition)`.
581 /// # let vec = vec![1];
582 /// vec.iter().skip_while(|x| **x == 0).next();
584 /// Could be written as
586 /// # let vec = vec![1];
587 /// vec.iter().find(|x| **x != 0);
589 #[clippy::version = "1.42.0"]
592 "using `skip_while(p).next()`, which is more succinctly expressed as `.find(!p)`"
595 declare_clippy_lint! {
597 /// Checks for usage of `_.map(_).flatten(_)` on `Iterator` and `Option`
599 /// ### Why is this bad?
600 /// Readability, this can be written more concisely as
601 /// `_.flat_map(_)` for `Iterator` or `_.and_then(_)` for `Option`
605 /// let vec = vec![vec![1]];
606 /// let opt = Some(5);
609 /// vec.iter().map(|x| x.iter()).flatten();
610 /// opt.map(|x| Some(x * 2)).flatten();
613 /// vec.iter().flat_map(|x| x.iter());
614 /// opt.and_then(|x| Some(x * 2));
616 #[clippy::version = "1.31.0"]
619 "using combinations of `flatten` and `map` which can usually be written as a single method call"
622 declare_clippy_lint! {
624 /// Checks for usage of `_.filter(_).map(_)` that can be written more simply
625 /// as `filter_map(_)`.
627 /// ### Why is this bad?
628 /// Redundant code in the `filter` and `map` operations is poor style and
635 /// .filter(|n| n.checked_add(1).is_some())
636 /// .map(|n| n.checked_add(1).unwrap());
641 /// (0_i32..10).filter_map(|n| n.checked_add(1));
643 #[clippy::version = "1.51.0"]
644 pub MANUAL_FILTER_MAP,
646 "using `_.filter(_).map(_)` in a way that can be written more simply as `filter_map(_)`"
649 declare_clippy_lint! {
651 /// Checks for usage of `_.find(_).map(_)` that can be written more simply
652 /// as `find_map(_)`.
654 /// ### Why is this bad?
655 /// Redundant code in the `find` and `map` operations is poor style and
662 /// .find(|n| n.checked_add(1).is_some())
663 /// .map(|n| n.checked_add(1).unwrap());
668 /// (0_i32..10).find_map(|n| n.checked_add(1));
670 #[clippy::version = "1.51.0"]
673 "using `_.find(_).map(_)` in a way that can be written more simply as `find_map(_)`"
676 declare_clippy_lint! {
678 /// Checks for usage of `_.filter_map(_).next()`.
680 /// ### Why is this bad?
681 /// Readability, this can be written more concisely as
686 /// (0..3).filter_map(|x| if x == 2 { Some(x) } else { None }).next();
688 /// Can be written as
691 /// (0..3).find_map(|x| if x == 2 { Some(x) } else { None });
693 #[clippy::version = "1.36.0"]
696 "using combination of `filter_map` and `next` which can usually be written as a single method call"
699 declare_clippy_lint! {
701 /// Checks for usage of `flat_map(|x| x)`.
703 /// ### Why is this bad?
704 /// Readability, this can be written more concisely by using `flatten`.
708 /// # let iter = vec![vec![0]].into_iter();
709 /// iter.flat_map(|x| x);
711 /// Can be written as
713 /// # let iter = vec![vec![0]].into_iter();
716 #[clippy::version = "1.39.0"]
717 pub FLAT_MAP_IDENTITY,
719 "call to `flat_map` where `flatten` is sufficient"
722 declare_clippy_lint! {
724 /// Checks for an iterator or string search (such as `find()`,
725 /// `position()`, or `rposition()`) followed by a call to `is_some()` or `is_none()`.
727 /// ### Why is this bad?
728 /// Readability, this can be written more concisely as:
729 /// * `_.any(_)`, or `_.contains(_)` for `is_some()`,
730 /// * `!_.any(_)`, or `!_.contains(_)` for `is_none()`.
734 /// let vec = vec![1];
735 /// vec.iter().find(|x| **x == 0).is_some();
737 /// let _ = "hello world".find("world").is_none();
739 /// Could be written as
741 /// let vec = vec![1];
742 /// vec.iter().any(|x| *x == 0);
744 /// let _ = !"hello world".contains("world");
746 #[clippy::version = "pre 1.29.0"]
749 "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()`)"
752 declare_clippy_lint! {
754 /// Checks for usage of `.chars().next()` on a `str` to check
755 /// if it starts with a given char.
757 /// ### Why is this bad?
758 /// Readability, this can be written more concisely as
759 /// `_.starts_with(_)`.
763 /// let name = "foo";
764 /// if name.chars().next() == Some('_') {};
766 /// Could be written as
768 /// let name = "foo";
769 /// if name.starts_with('_') {};
771 #[clippy::version = "pre 1.29.0"]
774 "using `.chars().next()` to check if a string starts with a char"
777 declare_clippy_lint! {
779 /// Checks for calls to `.or(foo(..))`, `.unwrap_or(foo(..))`,
780 /// etc., and suggests to use `or_else`, `unwrap_or_else`, etc., or
781 /// `unwrap_or_default` instead.
783 /// ### Why is this bad?
784 /// The function will always be called and potentially
785 /// allocate an object acting as the default.
787 /// ### Known problems
788 /// If the function has side-effects, not calling it will
789 /// change the semantic of the program, but you shouldn't rely on that anyway.
793 /// # let foo = Some(String::new());
794 /// foo.unwrap_or(String::new());
796 /// this can instead be written:
798 /// # let foo = Some(String::new());
799 /// foo.unwrap_or_else(String::new);
803 /// # let foo = Some(String::new());
804 /// foo.unwrap_or_default();
806 #[clippy::version = "pre 1.29.0"]
809 "using any `*or` method with a function call, which suggests `*or_else`"
812 declare_clippy_lint! {
814 /// Checks for `.or(…).unwrap()` calls to Options and Results.
816 /// ### Why is this bad?
817 /// You should use `.unwrap_or(…)` instead for clarity.
821 /// # let fallback = "fallback";
823 /// # type Error = &'static str;
824 /// # let result: Result<&str, Error> = Err("error");
825 /// let value = result.or::<Error>(Ok(fallback)).unwrap();
828 /// # let option: Option<&str> = None;
829 /// let value = option.or(Some(fallback)).unwrap();
833 /// # let fallback = "fallback";
835 /// # let result: Result<&str, &str> = Err("error");
836 /// let value = result.unwrap_or(fallback);
839 /// # let option: Option<&str> = None;
840 /// let value = option.unwrap_or(fallback);
842 #[clippy::version = "1.61.0"]
845 "checks for `.or(…).unwrap()` calls to Options and Results."
848 declare_clippy_lint! {
850 /// Checks for calls to `.expect(&format!(...))`, `.expect(foo(..))`,
851 /// etc., and suggests to use `unwrap_or_else` instead
853 /// ### Why is this bad?
854 /// The function will always be called.
856 /// ### Known problems
857 /// If the function has side-effects, not calling it will
858 /// change the semantics of the program, but you shouldn't rely on that anyway.
862 /// # let foo = Some(String::new());
863 /// # let err_code = "418";
864 /// # let err_msg = "I'm a teapot";
865 /// foo.expect(&format!("Err {}: {}", err_code, err_msg));
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).as_str());
874 /// this can instead be written:
876 /// # let foo = Some(String::new());
877 /// # let err_code = "418";
878 /// # let err_msg = "I'm a teapot";
879 /// foo.unwrap_or_else(|| panic!("Err {}: {}", err_code, err_msg));
881 #[clippy::version = "pre 1.29.0"]
884 "using any `expect` method with a function call"
887 declare_clippy_lint! {
889 /// Checks for usage of `.clone()` on a `Copy` type.
891 /// ### Why is this bad?
892 /// The only reason `Copy` types implement `Clone` is for
893 /// generics, not for using the `clone` method on a concrete type.
899 #[clippy::version = "pre 1.29.0"]
902 "using `clone` on a `Copy` type"
905 declare_clippy_lint! {
907 /// Checks for usage of `.clone()` on a ref-counted pointer,
908 /// (`Rc`, `Arc`, `rc::Weak`, or `sync::Weak`), and suggests calling Clone via unified
909 /// function syntax instead (e.g., `Rc::clone(foo)`).
911 /// ### Why is this bad?
912 /// Calling '.clone()' on an Rc, Arc, or Weak
913 /// can obscure the fact that only the pointer is being cloned, not the underlying
918 /// # use std::rc::Rc;
919 /// let x = Rc::new(1);
927 #[clippy::version = "pre 1.29.0"]
928 pub CLONE_ON_REF_PTR,
930 "using 'clone' on a ref-counted pointer"
933 declare_clippy_lint! {
935 /// Checks for usage of `.clone()` on an `&&T`.
937 /// ### Why is this bad?
938 /// Cloning an `&&T` copies the inner `&T`, instead of
939 /// cloning the underlying `T`.
946 /// let z = y.clone();
947 /// println!("{:p} {:p}", *y, z); // prints out the same pointer
950 #[clippy::version = "pre 1.29.0"]
951 pub CLONE_DOUBLE_REF,
953 "using `clone` on `&&T`"
956 declare_clippy_lint! {
958 /// Checks for usage of `.to_string()` on an `&&T` where
959 /// `T` implements `ToString` directly (like `&&str` or `&&String`).
961 /// ### Why is this bad?
962 /// This bypasses the specialized implementation of
963 /// `ToString` and instead goes through the more expensive string formatting
968 /// // Generic implementation for `T: Display` is used (slow)
969 /// ["foo", "bar"].iter().map(|s| s.to_string());
971 /// // OK, the specialized impl is used
972 /// ["foo", "bar"].iter().map(|&s| s.to_string());
974 #[clippy::version = "1.40.0"]
975 pub INEFFICIENT_TO_STRING,
977 "using `to_string` on `&&T` where `T: ToString`"
980 declare_clippy_lint! {
982 /// Checks for `new` not returning a type that contains `Self`.
984 /// ### Why is this bad?
985 /// As a convention, `new` methods are used to make a new
986 /// instance of a type.
989 /// In an impl block:
992 /// # struct NotAFoo;
994 /// fn new() -> NotAFoo {
1002 /// struct Bar(Foo);
1004 /// // Bad. The type name must contain `Self`
1005 /// fn new() -> Bar {
1013 /// # struct FooError;
1015 /// // Good. Return type contains `Self`
1016 /// fn new() -> Result<Foo, FooError> {
1022 /// Or in a trait definition:
1024 /// pub trait Trait {
1025 /// // Bad. The type name must contain `Self`
1031 /// pub trait Trait {
1032 /// // Good. Return type contains `Self`
1033 /// fn new() -> Self;
1036 #[clippy::version = "pre 1.29.0"]
1037 pub NEW_RET_NO_SELF,
1039 "not returning type containing `Self` in a `new` method"
1042 declare_clippy_lint! {
1043 /// ### What it does
1044 /// Checks for string methods that receive a single-character
1045 /// `str` as an argument, e.g., `_.split("x")`.
1047 /// ### Why is this bad?
1048 /// Performing these methods using a `char` is faster than
1051 /// ### Known problems
1052 /// Does not catch multi-byte unicode characters.
1061 #[clippy::version = "pre 1.29.0"]
1062 pub SINGLE_CHAR_PATTERN,
1064 "using a single-character str where a char could be used, e.g., `_.split(\"x\")`"
1067 declare_clippy_lint! {
1068 /// ### What it does
1069 /// Checks for calling `.step_by(0)` on iterators which panics.
1071 /// ### Why is this bad?
1072 /// This very much looks like an oversight. Use `panic!()` instead if you
1073 /// actually intend to panic.
1076 /// ```rust,should_panic
1077 /// for x in (0..100).step_by(0) {
1081 #[clippy::version = "pre 1.29.0"]
1082 pub ITERATOR_STEP_BY_ZERO,
1084 "using `Iterator::step_by(0)`, which will panic at runtime"
1087 declare_clippy_lint! {
1088 /// ### What it does
1089 /// Checks for indirect collection of populated `Option`
1091 /// ### Why is this bad?
1092 /// `Option` is like a collection of 0-1 things, so `flatten`
1093 /// automatically does this without suspicious-looking `unwrap` calls.
1097 /// let _ = std::iter::empty::<Option<i32>>().filter(Option::is_some).map(Option::unwrap);
1101 /// let _ = std::iter::empty::<Option<i32>>().flatten();
1103 #[clippy::version = "1.53.0"]
1104 pub OPTION_FILTER_MAP,
1106 "filtering `Option` for `Some` then force-unwrapping, which can be one type-safe operation"
1109 declare_clippy_lint! {
1110 /// ### What it does
1111 /// Checks for the use of `iter.nth(0)`.
1113 /// ### Why is this bad?
1114 /// `iter.next()` is equivalent to
1115 /// `iter.nth(0)`, as they both consume the next element,
1116 /// but is more readable.
1120 /// # use std::collections::HashSet;
1122 /// # let mut s = HashSet::new();
1124 /// let x = s.iter().nth(0);
1127 /// # let mut s = HashSet::new();
1129 /// let x = s.iter().next();
1131 #[clippy::version = "1.42.0"]
1134 "replace `iter.nth(0)` with `iter.next()`"
1137 declare_clippy_lint! {
1138 /// ### What it does
1139 /// Checks for use of `.iter().nth()` (and the related
1140 /// `.iter_mut().nth()`) on standard library types with *O*(1) element access.
1142 /// ### Why is this bad?
1143 /// `.get()` and `.get_mut()` are more efficient and more
1148 /// let some_vec = vec![0, 1, 2, 3];
1149 /// let bad_vec = some_vec.iter().nth(3);
1150 /// let bad_slice = &some_vec[..].iter().nth(3);
1152 /// The correct use would be:
1154 /// let some_vec = vec![0, 1, 2, 3];
1155 /// let bad_vec = some_vec.get(3);
1156 /// let bad_slice = &some_vec[..].get(3);
1158 #[clippy::version = "pre 1.29.0"]
1161 "using `.iter().nth()` on a standard library type with O(1) element access"
1164 declare_clippy_lint! {
1165 /// ### What it does
1166 /// Checks for use of `.skip(x).next()` on iterators.
1168 /// ### Why is this bad?
1169 /// `.nth(x)` is cleaner
1173 /// let some_vec = vec![0, 1, 2, 3];
1174 /// let bad_vec = some_vec.iter().skip(3).next();
1175 /// let bad_slice = &some_vec[..].iter().skip(3).next();
1177 /// The correct use would be:
1179 /// let some_vec = vec![0, 1, 2, 3];
1180 /// let bad_vec = some_vec.iter().nth(3);
1181 /// let bad_slice = &some_vec[..].iter().nth(3);
1183 #[clippy::version = "pre 1.29.0"]
1186 "using `.skip(x).next()` on an iterator"
1189 declare_clippy_lint! {
1190 /// ### What it does
1191 /// Checks for use of `.drain(..)` on `Vec` and `VecDeque` for iteration.
1193 /// ### Why is this bad?
1194 /// `.into_iter()` is simpler with better performance.
1198 /// # use std::collections::HashSet;
1199 /// let mut foo = vec![0, 1, 2, 3];
1200 /// let bar: HashSet<usize> = foo.drain(..).collect();
1204 /// # use std::collections::HashSet;
1205 /// let foo = vec![0, 1, 2, 3];
1206 /// let bar: HashSet<usize> = foo.into_iter().collect();
1208 #[clippy::version = "1.61.0"]
1209 pub ITER_WITH_DRAIN,
1211 "replace `.drain(..)` with `.into_iter()`"
1214 declare_clippy_lint! {
1215 /// ### What it does
1216 /// Checks for using `x.get(x.len() - 1)` instead of
1219 /// ### Why is this bad?
1220 /// Using `x.last()` is easier to read and has the same
1223 /// Note that using `x[x.len() - 1]` is semantically different from
1224 /// `x.last()`. Indexing into the array will panic on out-of-bounds
1225 /// accesses, while `x.get()` and `x.last()` will return `None`.
1227 /// There is another lint (get_unwrap) that covers the case of using
1228 /// `x.get(index).unwrap()` instead of `x[index]`.
1233 /// let x = vec![2, 3, 5];
1234 /// let last_element = x.get(x.len() - 1);
1237 /// let x = vec![2, 3, 5];
1238 /// let last_element = x.last();
1240 #[clippy::version = "1.37.0"]
1241 pub GET_LAST_WITH_LEN,
1243 "Using `x.get(x.len() - 1)` when `x.last()` is correct and simpler"
1246 declare_clippy_lint! {
1247 /// ### What it does
1248 /// Checks for use of `.get().unwrap()` (or
1249 /// `.get_mut().unwrap`) on a standard library type which implements `Index`
1251 /// ### Why is this bad?
1252 /// Using the Index trait (`[]`) is more clear and more
1255 /// ### Known problems
1256 /// Not a replacement for error handling: Using either
1257 /// `.unwrap()` or the Index trait (`[]`) carries the risk of causing a `panic`
1258 /// if the value being accessed is `None`. If the use of `.get().unwrap()` is a
1259 /// temporary placeholder for dealing with the `Option` type, then this does
1260 /// not mitigate the need for error handling. If there is a chance that `.get()`
1261 /// will be `None` in your program, then it is advisable that the `None` case
1262 /// is handled in a future refactor instead of using `.unwrap()` or the Index
1267 /// let mut some_vec = vec![0, 1, 2, 3];
1268 /// let last = some_vec.get(3).unwrap();
1269 /// *some_vec.get_mut(0).unwrap() = 1;
1271 /// The correct use would be:
1273 /// let mut some_vec = vec![0, 1, 2, 3];
1274 /// let last = some_vec[3];
1275 /// some_vec[0] = 1;
1277 #[clippy::version = "pre 1.29.0"]
1280 "using `.get().unwrap()` or `.get_mut().unwrap()` when using `[]` would work instead"
1283 declare_clippy_lint! {
1284 /// ### What it does
1285 /// Checks for occurrences where one vector gets extended instead of append
1287 /// ### Why is this bad?
1288 /// Using `append` instead of `extend` is more concise and faster
1292 /// let mut a = vec![1, 2, 3];
1293 /// let mut b = vec![4, 5, 6];
1296 /// a.extend(b.drain(..));
1299 /// a.append(&mut b);
1301 #[clippy::version = "1.55.0"]
1302 pub EXTEND_WITH_DRAIN,
1304 "using vec.append(&mut vec) to move the full range of a vector to another"
1307 declare_clippy_lint! {
1308 /// ### What it does
1309 /// Checks for the use of `.extend(s.chars())` where s is a
1310 /// `&str` or `String`.
1312 /// ### Why is this bad?
1313 /// `.push_str(s)` is clearer
1317 /// let abc = "abc";
1318 /// let def = String::from("def");
1319 /// let mut s = String::new();
1320 /// s.extend(abc.chars());
1321 /// s.extend(def.chars());
1323 /// The correct use would be:
1325 /// let abc = "abc";
1326 /// let def = String::from("def");
1327 /// let mut s = String::new();
1328 /// s.push_str(abc);
1329 /// s.push_str(&def);
1331 #[clippy::version = "pre 1.29.0"]
1332 pub STRING_EXTEND_CHARS,
1334 "using `x.extend(s.chars())` where s is a `&str` or `String`"
1337 declare_clippy_lint! {
1338 /// ### What it does
1339 /// Checks for the use of `.cloned().collect()` on slice to
1342 /// ### Why is this bad?
1343 /// `.to_vec()` is clearer
1347 /// let s = [1, 2, 3, 4, 5];
1348 /// let s2: Vec<isize> = s[..].iter().cloned().collect();
1350 /// The better use would be:
1352 /// let s = [1, 2, 3, 4, 5];
1353 /// let s2: Vec<isize> = s.to_vec();
1355 #[clippy::version = "pre 1.29.0"]
1356 pub ITER_CLONED_COLLECT,
1358 "using `.cloned().collect()` on slice to create a `Vec`"
1361 declare_clippy_lint! {
1362 /// ### What it does
1363 /// Checks for usage of `_.chars().last()` or
1364 /// `_.chars().next_back()` on a `str` to check if it ends with a given char.
1366 /// ### Why is this bad?
1367 /// Readability, this can be written more concisely as
1368 /// `_.ends_with(_)`.
1372 /// # let name = "_";
1375 /// name.chars().last() == Some('_') || name.chars().next_back() == Some('-');
1378 /// name.ends_with('_') || name.ends_with('-');
1380 #[clippy::version = "pre 1.29.0"]
1383 "using `.chars().last()` or `.chars().next_back()` to check if a string ends with a char"
1386 declare_clippy_lint! {
1387 /// ### What it does
1388 /// Checks for usage of `.as_ref()` or `.as_mut()` where the
1389 /// types before and after the call are the same.
1391 /// ### Why is this bad?
1392 /// The call is unnecessary.
1396 /// # fn do_stuff(x: &[i32]) {}
1397 /// let x: &[i32] = &[1, 2, 3, 4, 5];
1398 /// do_stuff(x.as_ref());
1400 /// The correct use would be:
1402 /// # fn do_stuff(x: &[i32]) {}
1403 /// let x: &[i32] = &[1, 2, 3, 4, 5];
1406 #[clippy::version = "pre 1.29.0"]
1409 "using `as_ref` where the types before and after the call are the same"
1412 declare_clippy_lint! {
1413 /// ### What it does
1414 /// Checks for using `fold` when a more succinct alternative exists.
1415 /// Specifically, this checks for `fold`s which could be replaced by `any`, `all`,
1416 /// `sum` or `product`.
1418 /// ### Why is this bad?
1423 /// let _ = (0..3).fold(false, |acc, x| acc || x > 2);
1425 /// This could be written as:
1427 /// let _ = (0..3).any(|x| x > 2);
1429 #[clippy::version = "pre 1.29.0"]
1430 pub UNNECESSARY_FOLD,
1432 "using `fold` when a more succinct alternative exists"
1435 declare_clippy_lint! {
1436 /// ### What it does
1437 /// Checks for `filter_map` calls that could be replaced by `filter` or `map`.
1438 /// More specifically it checks if the closure provided is only performing one of the
1439 /// filter or map operations and suggests the appropriate option.
1441 /// ### Why is this bad?
1442 /// Complexity. The intent is also clearer if only a single
1443 /// operation is being performed.
1447 /// let _ = (0..3).filter_map(|x| if x > 2 { Some(x) } else { None });
1449 /// // As there is no transformation of the argument this could be written as:
1450 /// let _ = (0..3).filter(|&x| x > 2);
1454 /// let _ = (0..4).filter_map(|x| Some(x + 1));
1456 /// // As there is no conditional check on the argument this could be written as:
1457 /// let _ = (0..4).map(|x| x + 1);
1459 #[clippy::version = "1.31.0"]
1460 pub UNNECESSARY_FILTER_MAP,
1462 "using `filter_map` when a more succinct alternative exists"
1465 declare_clippy_lint! {
1466 /// ### What it does
1467 /// Checks for `find_map` calls that could be replaced by `find` or `map`. More
1468 /// specifically it checks if the closure provided is only performing one of the
1469 /// find or map operations and suggests the appropriate option.
1471 /// ### Why is this bad?
1472 /// Complexity. The intent is also clearer if only a single
1473 /// operation is being performed.
1477 /// let _ = (0..3).find_map(|x| if x > 2 { Some(x) } else { None });
1479 /// // As there is no transformation of the argument this could be written as:
1480 /// let _ = (0..3).find(|&x| x > 2);
1484 /// let _ = (0..4).find_map(|x| Some(x + 1));
1486 /// // As there is no conditional check on the argument this could be written as:
1487 /// let _ = (0..4).map(|x| x + 1).next();
1489 #[clippy::version = "1.61.0"]
1490 pub UNNECESSARY_FIND_MAP,
1492 "using `find_map` when a more succinct alternative exists"
1495 declare_clippy_lint! {
1496 /// ### What it does
1497 /// Checks for `into_iter` calls on references which should be replaced by `iter`
1500 /// ### Why is this bad?
1501 /// Readability. Calling `into_iter` on a reference will not move out its
1502 /// content into the resulting iterator, which is confusing. It is better just call `iter` or
1503 /// `iter_mut` directly.
1508 /// let _ = (&vec![3, 4, 5]).into_iter();
1511 /// let _ = (&vec![3, 4, 5]).iter();
1513 #[clippy::version = "1.32.0"]
1514 pub INTO_ITER_ON_REF,
1516 "using `.into_iter()` on a reference"
1519 declare_clippy_lint! {
1520 /// ### What it does
1521 /// Checks for calls to `map` followed by a `count`.
1523 /// ### Why is this bad?
1524 /// It looks suspicious. Maybe `map` was confused with `filter`.
1525 /// If the `map` call is intentional, this should be rewritten
1526 /// using `inspect`. Or, if you intend to drive the iterator to
1527 /// completion, you can just use `for_each` instead.
1531 /// let _ = (0..3).map(|x| x + 2).count();
1533 #[clippy::version = "1.39.0"]
1536 "suspicious usage of map"
1539 declare_clippy_lint! {
1540 /// ### What it does
1541 /// Checks for `MaybeUninit::uninit().assume_init()`.
1543 /// ### Why is this bad?
1544 /// For most types, this is undefined behavior.
1546 /// ### Known problems
1547 /// For now, we accept empty tuples and tuples / arrays
1548 /// of `MaybeUninit`. There may be other types that allow uninitialized
1549 /// data, but those are not yet rigorously defined.
1553 /// // Beware the UB
1554 /// use std::mem::MaybeUninit;
1556 /// let _: usize = unsafe { MaybeUninit::uninit().assume_init() };
1559 /// Note that the following is OK:
1562 /// use std::mem::MaybeUninit;
1564 /// let _: [MaybeUninit<bool>; 5] = unsafe {
1565 /// MaybeUninit::uninit().assume_init()
1568 #[clippy::version = "1.39.0"]
1569 pub UNINIT_ASSUMED_INIT,
1571 "`MaybeUninit::uninit().assume_init()`"
1574 declare_clippy_lint! {
1575 /// ### What it does
1576 /// Checks for `.checked_add/sub(x).unwrap_or(MAX/MIN)`.
1578 /// ### Why is this bad?
1579 /// These can be written simply with `saturating_add/sub` methods.
1583 /// # let y: u32 = 0;
1584 /// # let x: u32 = 100;
1585 /// let add = x.checked_add(y).unwrap_or(u32::MAX);
1586 /// let sub = x.checked_sub(y).unwrap_or(u32::MIN);
1589 /// can be written using dedicated methods for saturating addition/subtraction as:
1592 /// # let y: u32 = 0;
1593 /// # let x: u32 = 100;
1594 /// let add = x.saturating_add(y);
1595 /// let sub = x.saturating_sub(y);
1597 #[clippy::version = "1.39.0"]
1598 pub MANUAL_SATURATING_ARITHMETIC,
1600 "`.checked_add/sub(x).unwrap_or(MAX/MIN)`"
1603 declare_clippy_lint! {
1604 /// ### What it does
1605 /// Checks for `offset(_)`, `wrapping_`{`add`, `sub`}, etc. on raw pointers to
1606 /// zero-sized types
1608 /// ### Why is this bad?
1609 /// This is a no-op, and likely unintended
1613 /// unsafe { (&() as *const ()).offset(1) };
1615 #[clippy::version = "1.41.0"]
1618 "Check for offset calculations on raw pointers to zero-sized types"
1621 declare_clippy_lint! {
1622 /// ### What it does
1623 /// Checks for `FileType::is_file()`.
1625 /// ### Why is this bad?
1626 /// When people testing a file type with `FileType::is_file`
1627 /// they are testing whether a path is something they can get bytes from. But
1628 /// `is_file` doesn't cover special file types in unix-like systems, and doesn't cover
1629 /// symlink in windows. Using `!FileType::is_dir()` is a better way to that intention.
1634 /// let metadata = std::fs::metadata("foo.txt")?;
1635 /// let filetype = metadata.file_type();
1637 /// if filetype.is_file() {
1640 /// # Ok::<_, std::io::Error>(())
1644 /// should be written as:
1648 /// let metadata = std::fs::metadata("foo.txt")?;
1649 /// let filetype = metadata.file_type();
1651 /// if !filetype.is_dir() {
1654 /// # Ok::<_, std::io::Error>(())
1657 #[clippy::version = "1.42.0"]
1658 pub FILETYPE_IS_FILE,
1660 "`FileType::is_file` is not recommended to test for readable file type"
1663 declare_clippy_lint! {
1664 /// ### What it does
1665 /// Checks for usage of `_.as_ref().map(Deref::deref)` or it's aliases (such as String::as_str).
1667 /// ### Why is this bad?
1668 /// Readability, this can be written more concisely as
1673 /// # let opt = Some("".to_string());
1674 /// opt.as_ref().map(String::as_str)
1677 /// Can be written as
1679 /// # let opt = Some("".to_string());
1683 #[clippy::version = "1.42.0"]
1684 pub OPTION_AS_REF_DEREF,
1686 "using `as_ref().map(Deref::deref)`, which is more succinctly expressed as `as_deref()`"
1689 declare_clippy_lint! {
1690 /// ### What it does
1691 /// Checks for usage of `iter().next()` on a Slice or an Array
1693 /// ### Why is this bad?
1694 /// These can be shortened into `.get()`
1698 /// # let a = [1, 2, 3];
1699 /// # let b = vec![1, 2, 3];
1700 /// a[2..].iter().next();
1701 /// b.iter().next();
1703 /// should be written as:
1705 /// # let a = [1, 2, 3];
1706 /// # let b = vec![1, 2, 3];
1710 #[clippy::version = "1.46.0"]
1711 pub ITER_NEXT_SLICE,
1713 "using `.iter().next()` on a sliced array, which can be shortened to just `.get()`"
1716 declare_clippy_lint! {
1717 /// ### What it does
1718 /// Warns when using `push_str`/`insert_str` with a single-character string literal
1719 /// where `push`/`insert` with a `char` would work fine.
1721 /// ### Why is this bad?
1722 /// It's less clear that we are pushing a single character.
1726 /// let mut string = String::new();
1727 /// string.insert_str(0, "R");
1728 /// string.push_str("R");
1730 /// Could be written as
1732 /// let mut string = String::new();
1733 /// string.insert(0, 'R');
1734 /// string.push('R');
1736 #[clippy::version = "1.49.0"]
1737 pub SINGLE_CHAR_ADD_STR,
1739 "`push_str()` or `insert_str()` used with a single-character string literal as parameter"
1742 declare_clippy_lint! {
1743 /// ### What it does
1744 /// As the counterpart to `or_fun_call`, this lint looks for unnecessary
1745 /// lazily evaluated closures on `Option` and `Result`.
1747 /// This lint suggests changing the following functions, when eager evaluation results in
1749 /// - `unwrap_or_else` to `unwrap_or`
1750 /// - `and_then` to `and`
1751 /// - `or_else` to `or`
1752 /// - `get_or_insert_with` to `get_or_insert`
1753 /// - `ok_or_else` to `ok_or`
1755 /// ### Why is this bad?
1756 /// Using eager evaluation is shorter and simpler in some cases.
1758 /// ### Known problems
1759 /// It is possible, but not recommended for `Deref` and `Index` to have
1760 /// side effects. Eagerly evaluating them can change the semantics of the program.
1764 /// // example code where clippy issues a warning
1765 /// let opt: Option<u32> = None;
1767 /// opt.unwrap_or_else(|| 42);
1771 /// let opt: Option<u32> = None;
1773 /// opt.unwrap_or(42);
1775 #[clippy::version = "1.48.0"]
1776 pub UNNECESSARY_LAZY_EVALUATIONS,
1778 "using unnecessary lazy evaluation, which can be replaced with simpler eager evaluation"
1781 declare_clippy_lint! {
1782 /// ### What it does
1783 /// Checks for usage of `_.map(_).collect::<Result<(), _>()`.
1785 /// ### Why is this bad?
1786 /// Using `try_for_each` instead is more readable and idiomatic.
1790 /// (0..3).map(|t| Err(t)).collect::<Result<(), _>>();
1794 /// (0..3).try_for_each(|t| Err(t));
1796 #[clippy::version = "1.49.0"]
1797 pub MAP_COLLECT_RESULT_UNIT,
1799 "using `.map(_).collect::<Result<(),_>()`, which can be replaced with `try_for_each`"
1802 declare_clippy_lint! {
1803 /// ### What it does
1804 /// Checks for `from_iter()` function calls on types that implement the `FromIterator`
1807 /// ### Why is this bad?
1808 /// It is recommended style to use collect. See
1809 /// [FromIterator documentation](https://doc.rust-lang.org/std/iter/trait.FromIterator.html)
1813 /// let five_fives = std::iter::repeat(5).take(5);
1815 /// let v = Vec::from_iter(five_fives);
1817 /// assert_eq!(v, vec![5, 5, 5, 5, 5]);
1821 /// let five_fives = std::iter::repeat(5).take(5);
1823 /// let v: Vec<i32> = five_fives.collect();
1825 /// assert_eq!(v, vec![5, 5, 5, 5, 5]);
1827 #[clippy::version = "1.49.0"]
1828 pub FROM_ITER_INSTEAD_OF_COLLECT,
1830 "use `.collect()` instead of `::from_iter()`"
1833 declare_clippy_lint! {
1834 /// ### What it does
1835 /// Checks for usage of `inspect().for_each()`.
1837 /// ### Why is this bad?
1838 /// It is the same as performing the computation
1839 /// inside `inspect` at the beginning of the closure in `for_each`.
1843 /// [1,2,3,4,5].iter()
1844 /// .inspect(|&x| println!("inspect the number: {}", x))
1845 /// .for_each(|&x| {
1846 /// assert!(x >= 0);
1849 /// Can be written as
1851 /// [1,2,3,4,5].iter()
1852 /// .for_each(|&x| {
1853 /// println!("inspect the number: {}", x);
1854 /// assert!(x >= 0);
1857 #[clippy::version = "1.51.0"]
1858 pub INSPECT_FOR_EACH,
1860 "using `.inspect().for_each()`, which can be replaced with `.for_each()`"
1863 declare_clippy_lint! {
1864 /// ### What it does
1865 /// Checks for usage of `filter_map(|x| x)`.
1867 /// ### Why is this bad?
1868 /// Readability, this can be written more concisely by using `flatten`.
1872 /// # let iter = vec![Some(1)].into_iter();
1873 /// iter.filter_map(|x| x);
1877 /// # let iter = vec![Some(1)].into_iter();
1880 #[clippy::version = "1.52.0"]
1881 pub FILTER_MAP_IDENTITY,
1883 "call to `filter_map` where `flatten` is sufficient"
1886 declare_clippy_lint! {
1887 /// ### What it does
1888 /// Checks for instances of `map(f)` where `f` is the identity function.
1890 /// ### Why is this bad?
1891 /// It can be written more concisely without the call to `map`.
1895 /// let x = [1, 2, 3];
1896 /// let y: Vec<_> = x.iter().map(|x| x).map(|x| 2*x).collect();
1900 /// let x = [1, 2, 3];
1901 /// let y: Vec<_> = x.iter().map(|x| 2*x).collect();
1903 #[clippy::version = "1.52.0"]
1906 "using iterator.map(|x| x)"
1909 declare_clippy_lint! {
1910 /// ### What it does
1911 /// Checks for the use of `.bytes().nth()`.
1913 /// ### Why is this bad?
1914 /// `.as_bytes().get()` is more efficient and more
1920 /// let _ = "Hello".bytes().nth(3);
1923 /// let _ = "Hello".as_bytes().get(3);
1925 #[clippy::version = "1.52.0"]
1928 "replace `.bytes().nth()` with `.as_bytes().get()`"
1931 declare_clippy_lint! {
1932 /// ### What it does
1933 /// Checks for the usage of `_.to_owned()`, `vec.to_vec()`, or similar when calling `_.clone()` would be clearer.
1935 /// ### Why is this bad?
1936 /// These methods do the same thing as `_.clone()` but may be confusing as
1937 /// to why we are calling `to_vec` on something that is already a `Vec` or calling `to_owned` on something that is already owned.
1941 /// let a = vec![1, 2, 3];
1942 /// let b = a.to_vec();
1943 /// let c = a.to_owned();
1947 /// let a = vec![1, 2, 3];
1948 /// let b = a.clone();
1949 /// let c = a.clone();
1951 #[clippy::version = "1.52.0"]
1954 "implicitly cloning a value by invoking a function on its dereferenced type"
1957 declare_clippy_lint! {
1958 /// ### What it does
1959 /// Checks for the use of `.iter().count()`.
1961 /// ### Why is this bad?
1962 /// `.len()` is more efficient and more
1968 /// let some_vec = vec![0, 1, 2, 3];
1969 /// let _ = some_vec.iter().count();
1970 /// let _ = &some_vec[..].iter().count();
1973 /// let some_vec = vec![0, 1, 2, 3];
1974 /// let _ = some_vec.len();
1975 /// let _ = &some_vec[..].len();
1977 #[clippy::version = "1.52.0"]
1980 "replace `.iter().count()` with `.len()`"
1983 declare_clippy_lint! {
1984 /// ### What it does
1985 /// Checks for calls to [`splitn`]
1986 /// (https://doc.rust-lang.org/std/primitive.str.html#method.splitn) and
1987 /// related functions with either zero or one splits.
1989 /// ### Why is this bad?
1990 /// These calls don't actually split the value and are
1991 /// likely to be intended as a different number.
1997 /// for x in s.splitn(1, ":") {
2003 /// for x in s.splitn(2, ":") {
2007 #[clippy::version = "1.54.0"]
2008 pub SUSPICIOUS_SPLITN,
2010 "checks for `.splitn(0, ..)` and `.splitn(1, ..)`"
2013 declare_clippy_lint! {
2014 /// ### What it does
2015 /// Checks for manual implementations of `str::repeat`
2017 /// ### Why is this bad?
2018 /// These are both harder to read, as well as less performant.
2023 /// let x: String = std::iter::repeat('x').take(10).collect();
2026 /// let x: String = "x".repeat(10);
2028 #[clippy::version = "1.54.0"]
2029 pub MANUAL_STR_REPEAT,
2031 "manual implementation of `str::repeat`"
2034 declare_clippy_lint! {
2035 /// ### What it does
2036 /// Checks for usages of `str::splitn(2, _)`
2038 /// ### Why is this bad?
2039 /// `split_once` is both clearer in intent and slightly more efficient.
2044 /// let s = "key=value=add";
2045 /// let (key, value) = s.splitn(2, '=').next_tuple()?;
2046 /// let value = s.splitn(2, '=').nth(1)?;
2048 /// let mut parts = s.splitn(2, '=');
2049 /// let key = parts.next()?;
2050 /// let value = parts.next()?;
2055 /// let s = "key=value=add";
2056 /// let (key, value) = s.split_once('=')?;
2057 /// let value = s.split_once('=')?.1;
2059 /// let (key, value) = s.split_once('=')?;
2063 /// The multiple statement variant currently only detects `iter.next()?`/`iter.next().unwrap()`
2064 /// in two separate `let` statements that immediately follow the `splitn()`
2065 #[clippy::version = "1.57.0"]
2066 pub MANUAL_SPLIT_ONCE,
2068 "replace `.splitn(2, pat)` with `.split_once(pat)`"
2071 declare_clippy_lint! {
2072 /// ### What it does
2073 /// Checks for usages of `str::splitn` (or `str::rsplitn`) where using `str::split` would be the same.
2074 /// ### Why is this bad?
2075 /// The function `split` is simpler and there is no performance difference in these cases, considering
2076 /// that both functions return a lazy iterator.
2080 /// let str = "key=value=add";
2081 /// let _ = str.splitn(3, '=').next().unwrap();
2086 /// let str = "key=value=add";
2087 /// let _ = str.split('=').next().unwrap();
2089 #[clippy::version = "1.58.0"]
2090 pub NEEDLESS_SPLITN,
2092 "usages of `str::splitn` that can be replaced with `str::split`"
2095 declare_clippy_lint! {
2096 /// ### What it does
2097 /// Checks for unnecessary calls to [`ToOwned::to_owned`](https://doc.rust-lang.org/std/borrow/trait.ToOwned.html#tymethod.to_owned)
2098 /// and other `to_owned`-like functions.
2100 /// ### Why is this bad?
2101 /// The unnecessary calls result in useless allocations.
2103 /// ### Known problems
2104 /// `unnecessary_to_owned` can falsely trigger if `IntoIterator::into_iter` is applied to an
2105 /// owned copy of a resource and the resource is later used mutably. See
2106 /// [#8148](https://github.com/rust-lang/rust-clippy/issues/8148).
2110 /// let path = std::path::Path::new("x");
2111 /// foo(&path.to_string_lossy().to_string());
2112 /// fn foo(s: &str) {}
2116 /// let path = std::path::Path::new("x");
2117 /// foo(&path.to_string_lossy());
2118 /// fn foo(s: &str) {}
2120 #[clippy::version = "1.58.0"]
2121 pub UNNECESSARY_TO_OWNED,
2123 "unnecessary calls to `to_owned`-like functions"
2126 declare_clippy_lint! {
2127 /// ### What it does
2128 /// Checks for use of `.collect::<Vec<String>>().join("")` on iterators.
2130 /// ### Why is this bad?
2131 /// `.collect::<String>()` is more concise and might be more performant
2135 /// let vector = vec!["hello", "world"];
2136 /// let output = vector.iter().map(|item| item.to_uppercase()).collect::<Vec<String>>().join("");
2137 /// println!("{}", output);
2139 /// The correct use would be:
2141 /// let vector = vec!["hello", "world"];
2142 /// let output = vector.iter().map(|item| item.to_uppercase()).collect::<String>();
2143 /// println!("{}", output);
2145 /// ### Known problems
2146 /// While `.collect::<String>()` is sometimes more performant, there are cases where
2147 /// using `.collect::<String>()` over `.collect::<Vec<String>>().join("")`
2148 /// will prevent loop unrolling and will result in a negative performance impact.
2150 /// Additionally, differences have been observed between aarch64 and x86_64 assembly output,
2151 /// with aarch64 tending to producing faster assembly in more cases when using `.collect::<String>()`
2152 #[clippy::version = "1.61.0"]
2153 pub UNNECESSARY_JOIN,
2155 "using `.collect::<Vec<String>>().join(\"\")` on an iterator"
2158 declare_clippy_lint! {
2159 /// ### What it does
2160 /// Checks for no-op uses of `Option::{as_deref, as_deref_mut}`,
2161 /// for example, `Option<&T>::as_deref()` returns the same type.
2163 /// ### Why is this bad?
2164 /// Redundant code and improving readability.
2168 /// let a = Some(&1);
2169 /// let b = a.as_deref(); // goes from Option<&i32> to Option<&i32>
2171 /// Could be written as:
2173 /// let a = Some(&1);
2176 #[clippy::version = "1.57.0"]
2177 pub NEEDLESS_OPTION_AS_DEREF,
2179 "no-op use of `deref` or `deref_mut` method to `Option`."
2182 declare_clippy_lint! {
2183 /// ### What it does
2184 /// Finds usages of [`char::is_digit`]
2185 /// (https://doc.rust-lang.org/stable/std/primitive.char.html#method.is_digit) that
2186 /// can be replaced with [`is_ascii_digit`]
2187 /// (https://doc.rust-lang.org/stable/std/primitive.char.html#method.is_ascii_digit) or
2188 /// [`is_ascii_hexdigit`]
2189 /// (https://doc.rust-lang.org/stable/std/primitive.char.html#method.is_ascii_hexdigit).
2191 /// ### Why is this bad?
2192 /// `is_digit(..)` is slower and requires specifying the radix.
2196 /// let c: char = '6';
2202 /// let c: char = '6';
2203 /// c.is_ascii_digit();
2204 /// c.is_ascii_hexdigit();
2206 #[clippy::version = "1.61.0"]
2207 pub IS_DIGIT_ASCII_RADIX,
2209 "use of `char::is_digit(..)` with literal radix of 10 or 16"
2212 declare_clippy_lint! {
2214 /// ### Why is this bad?
2218 /// let x = Some(3);
2219 /// x.as_ref().take();
2223 /// let x = Some(3);
2226 #[clippy::version = "1.61.0"]
2227 pub NEEDLESS_OPTION_TAKE,
2229 "using `.as_ref().take()` on a temporary value"
2232 declare_clippy_lint! {
2233 /// ### What it does
2234 /// Checks for `replace` statements which have no effect.
2236 /// ### Why is this bad?
2237 /// It's either a mistake or confusing.
2241 /// "1234".replace("12", "12");
2242 /// "1234".replacen("12", "12", 1);
2244 #[clippy::version = "1.62.0"]
2245 pub NO_EFFECT_REPLACE,
2247 "replace with no effect"
2250 pub struct Methods {
2251 avoid_breaking_exported_api: bool,
2252 msrv: Option<RustcVersion>,
2253 allow_expect_in_tests: bool,
2254 allow_unwrap_in_tests: bool,
2260 avoid_breaking_exported_api: bool,
2261 msrv: Option<RustcVersion>,
2262 allow_expect_in_tests: bool,
2263 allow_unwrap_in_tests: bool,
2266 avoid_breaking_exported_api,
2268 allow_expect_in_tests,
2269 allow_unwrap_in_tests,
2274 impl_lint_pass!(Methods => [
2277 SHOULD_IMPLEMENT_TRAIT,
2278 WRONG_SELF_CONVENTION,
2280 UNWRAP_OR_ELSE_DEFAULT,
2282 RESULT_MAP_OR_INTO_OPTION,
2284 BIND_INSTEAD_OF_MAP,
2293 ITER_OVEREAGER_CLONED,
2294 CLONED_INSTEAD_OF_COPIED,
2296 INEFFICIENT_TO_STRING,
2298 SINGLE_CHAR_PATTERN,
2299 SINGLE_CHAR_ADD_STR,
2303 FILTER_MAP_IDENTITY,
2311 ITERATOR_STEP_BY_ZERO,
2320 STRING_EXTEND_CHARS,
2321 ITER_CLONED_COLLECT,
2325 UNNECESSARY_FILTER_MAP,
2326 UNNECESSARY_FIND_MAP,
2329 UNINIT_ASSUMED_INIT,
2330 MANUAL_SATURATING_ARITHMETIC,
2333 OPTION_AS_REF_DEREF,
2334 UNNECESSARY_LAZY_EVALUATIONS,
2335 MAP_COLLECT_RESULT_UNIT,
2336 FROM_ITER_INSTEAD_OF_COLLECT,
2344 UNNECESSARY_TO_OWNED,
2347 NEEDLESS_OPTION_AS_DEREF,
2348 IS_DIGIT_ASCII_RADIX,
2349 NEEDLESS_OPTION_TAKE,
2353 /// Extracts a method call name, args, and `Span` of the method name.
2354 fn method_call<'tcx>(recv: &'tcx hir::Expr<'tcx>) -> Option<(&'tcx str, &'tcx [hir::Expr<'tcx>], Span)> {
2355 if let ExprKind::MethodCall(path, args, _) = recv.kind {
2356 if !args.iter().any(|e| e.span.from_expansion()) {
2357 let name = path.ident.name.as_str();
2358 return Some((name, args, path.ident.span));
2364 impl<'tcx> LateLintPass<'tcx> for Methods {
2365 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) {
2366 if expr.span.from_expansion() {
2370 self.check_methods(cx, expr);
2373 hir::ExprKind::Call(func, args) => {
2374 from_iter_instead_of_collect::check(cx, expr, args, func);
2376 hir::ExprKind::MethodCall(method_call, args, _) => {
2377 let method_span = method_call.ident.span;
2378 or_fun_call::check(cx, expr, method_span, method_call.ident.as_str(), args);
2379 expect_fun_call::check(cx, expr, method_span, method_call.ident.as_str(), args);
2380 clone_on_copy::check(cx, expr, method_call.ident.name, args);
2381 clone_on_ref_ptr::check(cx, expr, method_call.ident.name, args);
2382 inefficient_to_string::check(cx, expr, method_call.ident.name, args);
2383 single_char_add_str::check(cx, expr, args);
2384 into_iter_on_ref::check(cx, expr, method_span, method_call.ident.name, args);
2385 single_char_pattern::check(cx, expr, method_call.ident.name, args);
2386 unnecessary_to_owned::check(cx, expr, method_call.ident.name, args, self.msrv);
2388 hir::ExprKind::Binary(op, lhs, rhs) if op.node == hir::BinOpKind::Eq || op.node == hir::BinOpKind::Ne => {
2389 let mut info = BinaryExprInfo {
2393 eq: op.node == hir::BinOpKind::Eq,
2395 lint_binary_expr_with_method_call(cx, &mut info);
2401 #[allow(clippy::too_many_lines)]
2402 fn check_impl_item(&mut self, cx: &LateContext<'tcx>, impl_item: &'tcx hir::ImplItem<'_>) {
2403 if in_external_macro(cx.sess(), impl_item.span) {
2406 let name = impl_item.ident.name.as_str();
2407 let parent = cx.tcx.hir().get_parent_item(impl_item.hir_id());
2408 let item = cx.tcx.hir().expect_item(parent);
2409 let self_ty = cx.tcx.type_of(item.def_id);
2411 let implements_trait = matches!(item.kind, hir::ItemKind::Impl(hir::Impl { of_trait: Some(_), .. }));
2413 if let hir::ImplItemKind::Fn(ref sig, id) = impl_item.kind;
2414 if let Some(first_arg) = iter_input_pats(sig.decl, cx.tcx.hir().body(id)).next();
2416 let method_sig = cx.tcx.fn_sig(impl_item.def_id);
2417 let method_sig = cx.tcx.erase_late_bound_regions(method_sig);
2419 let first_arg_ty = method_sig.inputs().iter().next();
2421 // check conventions w.r.t. conversion method names and predicates
2422 if let Some(first_arg_ty) = first_arg_ty;
2425 // if this impl block implements a trait, lint in trait definition instead
2426 if !implements_trait && cx.access_levels.is_exported(impl_item.def_id) {
2427 // check missing trait implementations
2428 for method_config in &TRAIT_METHODS {
2429 if name == method_config.method_name &&
2430 sig.decl.inputs.len() == method_config.param_count &&
2431 method_config.output_type.matches(&sig.decl.output) &&
2432 method_config.self_kind.matches(cx, self_ty, *first_arg_ty) &&
2433 fn_header_equals(method_config.fn_header, sig.header) &&
2434 method_config.lifetime_param_cond(impl_item)
2438 SHOULD_IMPLEMENT_TRAIT,
2441 "method `{}` can be confused for the standard trait method `{}::{}`",
2442 method_config.method_name,
2443 method_config.trait_name,
2444 method_config.method_name
2448 "consider implementing the trait `{}` or choosing a less ambiguous method name",
2449 method_config.trait_name
2456 if sig.decl.implicit_self.has_implicit_self()
2457 && !(self.avoid_breaking_exported_api
2458 && cx.access_levels.is_exported(impl_item.def_id))
2460 wrong_self_convention::check(
2473 // if this impl block implements a trait, lint in trait definition instead
2474 if implements_trait {
2478 if let hir::ImplItemKind::Fn(_, _) = impl_item.kind {
2479 let ret_ty = return_ty(cx, impl_item.hir_id());
2481 // walk the return type and check for Self (this does not check associated types)
2482 if let Some(self_adt) = self_ty.ty_adt_def() {
2483 if contains_adt_constructor(ret_ty, self_adt) {
2486 } else if contains_ty(ret_ty, self_ty) {
2490 // if return type is impl trait, check the associated types
2491 if let ty::Opaque(def_id, _) = *ret_ty.kind() {
2492 // one of the associated types must be Self
2493 for &(predicate, _span) in cx.tcx.explicit_item_bounds(def_id) {
2494 if let ty::PredicateKind::Projection(projection_predicate) = predicate.kind().skip_binder() {
2495 let assoc_ty = match projection_predicate.term {
2496 ty::Term::Ty(ty) => ty,
2497 ty::Term::Const(_c) => continue,
2499 // walk the associated type and check for Self
2500 if let Some(self_adt) = self_ty.ty_adt_def() {
2501 if contains_adt_constructor(assoc_ty, self_adt) {
2504 } else if contains_ty(assoc_ty, self_ty) {
2511 if name == "new" && ret_ty != self_ty {
2516 "methods called `new` usually return `Self`",
2522 fn check_trait_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx TraitItem<'_>) {
2523 if in_external_macro(cx.tcx.sess, item.span) {
2528 if let TraitItemKind::Fn(ref sig, _) = item.kind;
2529 if sig.decl.implicit_self.has_implicit_self();
2530 if let Some(first_arg_ty) = sig.decl.inputs.iter().next();
2533 let first_arg_span = first_arg_ty.span;
2534 let first_arg_ty = hir_ty_to_ty(cx.tcx, first_arg_ty);
2535 let self_ty = TraitRef::identity(cx.tcx, item.def_id.to_def_id()).self_ty().skip_binder();
2536 wrong_self_convention::check(
2538 item.ident.name.as_str(),
2549 if item.ident.name == sym::new;
2550 if let TraitItemKind::Fn(_, _) = item.kind;
2551 let ret_ty = return_ty(cx, item.hir_id());
2552 let self_ty = TraitRef::identity(cx.tcx, item.def_id.to_def_id()).self_ty().skip_binder();
2553 if !contains_ty(ret_ty, self_ty);
2560 "methods called `new` usually return `Self`",
2566 extract_msrv_attr!(LateContext);
2570 #[allow(clippy::too_many_lines)]
2571 fn check_methods<'tcx>(&self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
2572 if let Some((name, [recv, args @ ..], span)) = method_call(expr) {
2573 match (name, args) {
2574 ("add" | "offset" | "sub" | "wrapping_offset" | "wrapping_add" | "wrapping_sub", [_arg]) => {
2575 zst_offset::check(cx, expr, recv);
2577 ("and_then", [arg]) => {
2578 let biom_option_linted = bind_instead_of_map::OptionAndThenSome::check(cx, expr, recv, arg);
2579 let biom_result_linted = bind_instead_of_map::ResultAndThenOk::check(cx, expr, recv, arg);
2580 if !biom_option_linted && !biom_result_linted {
2581 unnecessary_lazy_eval::check(cx, expr, recv, arg, "and");
2584 ("as_deref" | "as_deref_mut", []) => {
2585 needless_option_as_deref::check(cx, expr, recv, name);
2587 ("as_mut", []) => useless_asref::check(cx, expr, "as_mut", recv),
2588 ("as_ref", []) => useless_asref::check(cx, expr, "as_ref", recv),
2589 ("assume_init", []) => uninit_assumed_init::check(cx, expr, recv),
2590 ("cloned", []) => cloned_instead_of_copied::check(cx, expr, recv, span, self.msrv),
2591 ("collect", []) => match method_call(recv) {
2592 Some((name @ ("cloned" | "copied"), [recv2], _)) => {
2593 iter_cloned_collect::check(cx, name, expr, recv2);
2595 Some(("map", [m_recv, m_arg], _)) => {
2596 map_collect_result_unit::check(cx, expr, m_recv, m_arg, recv);
2598 Some(("take", [take_self_arg, take_arg], _)) => {
2599 if meets_msrv(self.msrv, msrvs::STR_REPEAT) {
2600 manual_str_repeat::check(cx, expr, recv, take_self_arg, take_arg);
2605 (name @ "count", args @ []) => match method_call(recv) {
2606 Some(("cloned", [recv2], _)) => iter_overeager_cloned::check(cx, expr, recv2, name, args),
2607 Some((name2 @ ("into_iter" | "iter" | "iter_mut"), [recv2], _)) => {
2608 iter_count::check(cx, expr, recv2, name2);
2610 Some(("map", [_, arg], _)) => suspicious_map::check(cx, expr, recv, arg),
2613 ("drain", [arg]) => {
2614 iter_with_drain::check(cx, expr, recv, span, arg);
2616 ("expect", [_]) => match method_call(recv) {
2617 Some(("ok", [recv], _)) => ok_expect::check(cx, expr, recv),
2618 Some(("err", [recv], err_span)) => err_expect::check(cx, expr, recv, self.msrv, span, err_span),
2619 _ => expect_used::check(cx, expr, recv, self.allow_expect_in_tests),
2621 ("extend", [arg]) => {
2622 string_extend_chars::check(cx, expr, recv, arg);
2623 extend_with_drain::check(cx, expr, recv, arg);
2625 ("filter_map", [arg]) => {
2626 unnecessary_filter_map::check(cx, expr, arg, name);
2627 filter_map_identity::check(cx, expr, arg, span);
2629 ("find_map", [arg]) => {
2630 unnecessary_filter_map::check(cx, expr, arg, name);
2632 ("flat_map", [arg]) => {
2633 flat_map_identity::check(cx, expr, arg, span);
2634 flat_map_option::check(cx, expr, arg, span);
2636 (name @ "flatten", args @ []) => match method_call(recv) {
2637 Some(("map", [recv, map_arg], map_span)) => map_flatten::check(cx, expr, recv, map_arg, map_span),
2638 Some(("cloned", [recv2], _)) => iter_overeager_cloned::check(cx, expr, recv2, name, args),
2641 ("fold", [init, acc]) => unnecessary_fold::check(cx, expr, init, acc, span),
2642 ("for_each", [_]) => {
2643 if let Some(("inspect", [_, _], span2)) = method_call(recv) {
2644 inspect_for_each::check(cx, expr, span2);
2647 ("get", [arg]) => get_last_with_len::check(cx, expr, recv, arg),
2648 ("get_or_insert_with", [arg]) => unnecessary_lazy_eval::check(cx, expr, recv, arg, "get_or_insert"),
2649 ("is_file", []) => filetype_is_file::check(cx, expr, recv),
2650 ("is_digit", [radix]) => is_digit_ascii_radix::check(cx, expr, recv, radix, self.msrv),
2651 ("is_none", []) => check_is_some_is_none(cx, expr, recv, false),
2652 ("is_some", []) => check_is_some_is_none(cx, expr, recv, true),
2653 ("join", [join_arg]) => {
2654 if let Some(("collect", _, span)) = method_call(recv) {
2655 unnecessary_join::check(cx, expr, recv, join_arg, span);
2658 ("last", args @ []) | ("skip", args @ [_]) => {
2659 if let Some((name2, [recv2, args2 @ ..], _span2)) = method_call(recv) {
2660 if let ("cloned", []) = (name2, args2) {
2661 iter_overeager_cloned::check(cx, expr, recv2, name, args);
2665 (name @ ("map" | "map_err"), [m_arg]) => {
2666 if let Some((name, [recv2, args @ ..], span2)) = method_call(recv) {
2667 match (name, args) {
2668 ("as_mut", []) => option_as_ref_deref::check(cx, expr, recv2, m_arg, true, self.msrv),
2669 ("as_ref", []) => option_as_ref_deref::check(cx, expr, recv2, m_arg, false, self.msrv),
2670 ("filter", [f_arg]) => {
2671 filter_map::check(cx, expr, recv2, f_arg, span2, recv, m_arg, span, false);
2673 ("find", [f_arg]) => {
2674 filter_map::check(cx, expr, recv2, f_arg, span2, recv, m_arg, span, true);
2679 map_identity::check(cx, expr, recv, m_arg, name, span);
2681 ("map_or", [def, map]) => option_map_or_none::check(cx, expr, recv, def, map),
2682 (name @ "next", args @ []) => {
2683 if let Some((name2, [recv2, args2 @ ..], _)) = method_call(recv) {
2684 match (name2, args2) {
2685 ("cloned", []) => iter_overeager_cloned::check(cx, expr, recv2, name, args),
2686 ("filter", [arg]) => filter_next::check(cx, expr, recv2, arg),
2687 ("filter_map", [arg]) => filter_map_next::check(cx, expr, recv2, arg, self.msrv),
2688 ("iter", []) => iter_next_slice::check(cx, expr, recv2),
2689 ("skip", [arg]) => iter_skip_next::check(cx, expr, recv2, arg),
2690 ("skip_while", [_]) => skip_while_next::check(cx, expr),
2695 ("nth", args @ [n_arg]) => match method_call(recv) {
2696 Some(("bytes", [recv2], _)) => bytes_nth::check(cx, expr, recv2, n_arg),
2697 Some(("cloned", [recv2], _)) => iter_overeager_cloned::check(cx, expr, recv2, name, args),
2698 Some(("iter", [recv2], _)) => iter_nth::check(cx, expr, recv2, recv, n_arg, false),
2699 Some(("iter_mut", [recv2], _)) => iter_nth::check(cx, expr, recv2, recv, n_arg, true),
2700 _ => iter_nth_zero::check(cx, expr, recv, n_arg),
2702 ("ok_or_else", [arg]) => unnecessary_lazy_eval::check(cx, expr, recv, arg, "ok_or"),
2703 ("or_else", [arg]) => {
2704 if !bind_instead_of_map::ResultOrElseErrInfo::check(cx, expr, recv, arg) {
2705 unnecessary_lazy_eval::check(cx, expr, recv, arg, "or");
2708 ("splitn" | "rsplitn", [count_arg, pat_arg]) => {
2709 if let Some((Constant::Int(count), _)) = constant(cx, cx.typeck_results(), count_arg) {
2710 suspicious_splitn::check(cx, name, expr, recv, count);
2711 str_splitn::check(cx, name, expr, recv, pat_arg, count, self.msrv);
2714 ("splitn_mut" | "rsplitn_mut", [count_arg, _]) => {
2715 if let Some((Constant::Int(count), _)) = constant(cx, cx.typeck_results(), count_arg) {
2716 suspicious_splitn::check(cx, name, expr, recv, count);
2719 ("step_by", [arg]) => iterator_step_by_zero::check(cx, expr, arg),
2720 ("take", args @ [_arg]) => {
2721 if let Some((name2, [recv2, args2 @ ..], _span2)) = method_call(recv) {
2722 if let ("cloned", []) = (name2, args2) {
2723 iter_overeager_cloned::check(cx, expr, recv2, name, args);
2727 ("take", []) => needless_option_take::check(cx, expr, recv),
2728 ("to_os_string" | "to_owned" | "to_path_buf" | "to_vec", []) => {
2729 implicit_clone::check(cx, name, expr, recv);
2732 match method_call(recv) {
2733 Some(("get", [recv, get_arg], _)) => {
2734 get_unwrap::check(cx, expr, recv, get_arg, false);
2736 Some(("get_mut", [recv, get_arg], _)) => {
2737 get_unwrap::check(cx, expr, recv, get_arg, true);
2739 Some(("or", [recv, or_arg], or_span)) => {
2740 or_then_unwrap::check(cx, expr, recv, or_arg, or_span);
2744 unwrap_used::check(cx, expr, recv, self.allow_unwrap_in_tests);
2746 ("unwrap_or", [u_arg]) => match method_call(recv) {
2747 Some((arith @ ("checked_add" | "checked_sub" | "checked_mul"), [lhs, rhs], _)) => {
2748 manual_saturating_arithmetic::check(cx, expr, lhs, rhs, u_arg, &arith["checked_".len()..]);
2750 Some(("map", [m_recv, m_arg], span)) => {
2751 option_map_unwrap_or::check(cx, expr, m_recv, m_arg, recv, u_arg, span);
2755 ("unwrap_or_else", [u_arg]) => match method_call(recv) {
2756 Some(("map", [recv, map_arg], _))
2757 if map_unwrap_or::check(cx, expr, recv, map_arg, u_arg, self.msrv) => {},
2759 unwrap_or_else_default::check(cx, expr, recv, u_arg);
2760 unnecessary_lazy_eval::check(cx, expr, recv, u_arg, "unwrap_or");
2763 ("replace" | "replacen", [arg1, arg2] | [arg1, arg2, _]) => {
2764 no_effect_replace::check(cx, expr, arg1, arg2);
2772 fn check_is_some_is_none(cx: &LateContext<'_>, expr: &Expr<'_>, recv: &Expr<'_>, is_some: bool) {
2773 if let Some((name @ ("find" | "position" | "rposition"), [f_recv, arg], span)) = method_call(recv) {
2774 search_is_some::check(cx, expr, name, is_some, f_recv, arg, recv, span);
2778 /// Used for `lint_binary_expr_with_method_call`.
2779 #[derive(Copy, Clone)]
2780 struct BinaryExprInfo<'a> {
2781 expr: &'a hir::Expr<'a>,
2782 chain: &'a hir::Expr<'a>,
2783 other: &'a hir::Expr<'a>,
2787 /// Checks for the `CHARS_NEXT_CMP` and `CHARS_LAST_CMP` lints.
2788 fn lint_binary_expr_with_method_call(cx: &LateContext<'_>, info: &mut BinaryExprInfo<'_>) {
2789 macro_rules! lint_with_both_lhs_and_rhs {
2790 ($func:expr, $cx:expr, $info:ident) => {
2791 if !$func($cx, $info) {
2792 ::std::mem::swap(&mut $info.chain, &mut $info.other);
2793 if $func($cx, $info) {
2800 lint_with_both_lhs_and_rhs!(chars_next_cmp::check, cx, info);
2801 lint_with_both_lhs_and_rhs!(chars_last_cmp::check, cx, info);
2802 lint_with_both_lhs_and_rhs!(chars_next_cmp_with_unwrap::check, cx, info);
2803 lint_with_both_lhs_and_rhs!(chars_last_cmp_with_unwrap::check, cx, info);
2806 const FN_HEADER: hir::FnHeader = hir::FnHeader {
2807 unsafety: hir::Unsafety::Normal,
2808 constness: hir::Constness::NotConst,
2809 asyncness: hir::IsAsync::NotAsync,
2810 abi: rustc_target::spec::abi::Abi::Rust,
2813 struct ShouldImplTraitCase {
2814 trait_name: &'static str,
2815 method_name: &'static str,
2817 fn_header: hir::FnHeader,
2818 // implicit self kind expected (none, self, &self, ...)
2819 self_kind: SelfKind,
2820 // checks against the output type
2821 output_type: OutType,
2822 // certain methods with explicit lifetimes can't implement the equivalent trait method
2823 lint_explicit_lifetime: bool,
2825 impl ShouldImplTraitCase {
2827 trait_name: &'static str,
2828 method_name: &'static str,
2830 fn_header: hir::FnHeader,
2831 self_kind: SelfKind,
2832 output_type: OutType,
2833 lint_explicit_lifetime: bool,
2834 ) -> ShouldImplTraitCase {
2835 ShouldImplTraitCase {
2842 lint_explicit_lifetime,
2846 fn lifetime_param_cond(&self, impl_item: &hir::ImplItem<'_>) -> bool {
2847 self.lint_explicit_lifetime
2848 || !impl_item.generics.params.iter().any(|p| {
2851 hir::GenericParamKind::Lifetime {
2852 kind: hir::LifetimeParamKind::Explicit
2860 const TRAIT_METHODS: [ShouldImplTraitCase; 30] = [
2861 ShouldImplTraitCase::new("std::ops::Add", "add", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
2862 ShouldImplTraitCase::new("std::convert::AsMut", "as_mut", 1, FN_HEADER, SelfKind::RefMut, OutType::Ref, true),
2863 ShouldImplTraitCase::new("std::convert::AsRef", "as_ref", 1, FN_HEADER, SelfKind::Ref, OutType::Ref, true),
2864 ShouldImplTraitCase::new("std::ops::BitAnd", "bitand", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
2865 ShouldImplTraitCase::new("std::ops::BitOr", "bitor", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
2866 ShouldImplTraitCase::new("std::ops::BitXor", "bitxor", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
2867 ShouldImplTraitCase::new("std::borrow::Borrow", "borrow", 1, FN_HEADER, SelfKind::Ref, OutType::Ref, true),
2868 ShouldImplTraitCase::new("std::borrow::BorrowMut", "borrow_mut", 1, FN_HEADER, SelfKind::RefMut, OutType::Ref, true),
2869 ShouldImplTraitCase::new("std::clone::Clone", "clone", 1, FN_HEADER, SelfKind::Ref, OutType::Any, true),
2870 ShouldImplTraitCase::new("std::cmp::Ord", "cmp", 2, FN_HEADER, SelfKind::Ref, OutType::Any, true),
2871 // FIXME: default doesn't work
2872 ShouldImplTraitCase::new("std::default::Default", "default", 0, FN_HEADER, SelfKind::No, OutType::Any, true),
2873 ShouldImplTraitCase::new("std::ops::Deref", "deref", 1, FN_HEADER, SelfKind::Ref, OutType::Ref, true),
2874 ShouldImplTraitCase::new("std::ops::DerefMut", "deref_mut", 1, FN_HEADER, SelfKind::RefMut, OutType::Ref, true),
2875 ShouldImplTraitCase::new("std::ops::Div", "div", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
2876 ShouldImplTraitCase::new("std::ops::Drop", "drop", 1, FN_HEADER, SelfKind::RefMut, OutType::Unit, true),
2877 ShouldImplTraitCase::new("std::cmp::PartialEq", "eq", 2, FN_HEADER, SelfKind::Ref, OutType::Bool, true),
2878 ShouldImplTraitCase::new("std::iter::FromIterator", "from_iter", 1, FN_HEADER, SelfKind::No, OutType::Any, true),
2879 ShouldImplTraitCase::new("std::str::FromStr", "from_str", 1, FN_HEADER, SelfKind::No, OutType::Any, true),
2880 ShouldImplTraitCase::new("std::hash::Hash", "hash", 2, FN_HEADER, SelfKind::Ref, OutType::Unit, true),
2881 ShouldImplTraitCase::new("std::ops::Index", "index", 2, FN_HEADER, SelfKind::Ref, OutType::Ref, true),
2882 ShouldImplTraitCase::new("std::ops::IndexMut", "index_mut", 2, FN_HEADER, SelfKind::RefMut, OutType::Ref, true),
2883 ShouldImplTraitCase::new("std::iter::IntoIterator", "into_iter", 1, FN_HEADER, SelfKind::Value, OutType::Any, true),
2884 ShouldImplTraitCase::new("std::ops::Mul", "mul", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
2885 ShouldImplTraitCase::new("std::ops::Neg", "neg", 1, FN_HEADER, SelfKind::Value, OutType::Any, true),
2886 ShouldImplTraitCase::new("std::iter::Iterator", "next", 1, FN_HEADER, SelfKind::RefMut, OutType::Any, false),
2887 ShouldImplTraitCase::new("std::ops::Not", "not", 1, FN_HEADER, SelfKind::Value, OutType::Any, true),
2888 ShouldImplTraitCase::new("std::ops::Rem", "rem", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
2889 ShouldImplTraitCase::new("std::ops::Shl", "shl", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
2890 ShouldImplTraitCase::new("std::ops::Shr", "shr", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
2891 ShouldImplTraitCase::new("std::ops::Sub", "sub", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
2894 #[derive(Clone, Copy, PartialEq, Eq, Debug)]
2903 fn matches<'a>(self, cx: &LateContext<'a>, parent_ty: Ty<'a>, ty: Ty<'a>) -> bool {
2904 fn matches_value<'a>(cx: &LateContext<'a>, parent_ty: Ty<'_>, ty: Ty<'_>) -> bool {
2905 if ty == parent_ty {
2907 } else if ty.is_box() {
2908 ty.boxed_ty() == parent_ty
2909 } else if is_type_diagnostic_item(cx, ty, sym::Rc) || is_type_diagnostic_item(cx, ty, sym::Arc) {
2910 if let ty::Adt(_, substs) = ty.kind() {
2911 substs.types().next().map_or(false, |t| t == parent_ty)
2920 fn matches_ref<'a>(cx: &LateContext<'a>, mutability: hir::Mutability, parent_ty: Ty<'a>, ty: Ty<'a>) -> bool {
2921 if let ty::Ref(_, t, m) = *ty.kind() {
2922 return m == mutability && t == parent_ty;
2925 let trait_path = match mutability {
2926 hir::Mutability::Not => &paths::ASREF_TRAIT,
2927 hir::Mutability::Mut => &paths::ASMUT_TRAIT,
2930 let trait_def_id = match get_trait_def_id(cx, trait_path) {
2932 None => return false,
2934 implements_trait(cx, ty, trait_def_id, &[parent_ty.into()])
2937 fn matches_none<'a>(cx: &LateContext<'a>, parent_ty: Ty<'a>, ty: Ty<'a>) -> bool {
2938 !matches_value(cx, parent_ty, ty)
2939 && !matches_ref(cx, hir::Mutability::Not, parent_ty, ty)
2940 && !matches_ref(cx, hir::Mutability::Mut, parent_ty, ty)
2944 Self::Value => matches_value(cx, parent_ty, ty),
2945 Self::Ref => matches_ref(cx, hir::Mutability::Not, parent_ty, ty) || ty == parent_ty && is_copy(cx, ty),
2946 Self::RefMut => matches_ref(cx, hir::Mutability::Mut, parent_ty, ty),
2947 Self::No => matches_none(cx, parent_ty, ty),
2952 fn description(self) -> &'static str {
2954 Self::Value => "`self` by value",
2955 Self::Ref => "`self` by reference",
2956 Self::RefMut => "`self` by mutable reference",
2957 Self::No => "no `self`",
2962 #[derive(Clone, Copy)]
2971 fn matches(self, ty: &hir::FnRetTy<'_>) -> bool {
2972 let is_unit = |ty: &hir::Ty<'_>| matches!(ty.kind, hir::TyKind::Tup(&[]));
2974 (Self::Unit, &hir::FnRetTy::DefaultReturn(_)) => true,
2975 (Self::Unit, &hir::FnRetTy::Return(ty)) if is_unit(ty) => true,
2976 (Self::Bool, &hir::FnRetTy::Return(ty)) if is_bool(ty) => true,
2977 (Self::Any, &hir::FnRetTy::Return(ty)) if !is_unit(ty) => true,
2978 (Self::Ref, &hir::FnRetTy::Return(ty)) => matches!(ty.kind, hir::TyKind::Rptr(_, _)),
2984 fn is_bool(ty: &hir::Ty<'_>) -> bool {
2985 if let hir::TyKind::Path(QPath::Resolved(_, path)) = ty.kind {
2986 matches!(path.res, Res::PrimTy(PrimTy::Bool))
2992 fn fn_header_equals(expected: hir::FnHeader, actual: hir::FnHeader) -> bool {
2993 expected.constness == actual.constness
2994 && expected.unsafety == actual.unsafety
2995 && expected.asyncness == actual.asyncness