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.
127 /// ### Known Problems
128 /// This `lint` removes the side of effect of cloning items in the iterator.
129 /// A code that relies on that side-effect could fail.
133 /// # let vec = vec!["string".to_string()];
134 /// vec.iter().cloned().take(10);
135 /// vec.iter().cloned().last();
140 /// # let vec = vec!["string".to_string()];
141 /// vec.iter().take(10).cloned();
142 /// vec.iter().last().cloned();
144 #[clippy::version = "1.59.0"]
145 pub ITER_OVEREAGER_CLONED,
147 "using `cloned()` early with `Iterator::iter()` can lead to some performance inefficiencies"
150 declare_clippy_lint! {
152 /// Checks for usages of `Iterator::flat_map()` where `filter_map()` could be
155 /// ### Why is this bad?
156 /// When applicable, `filter_map()` is more clear since it shows that
157 /// `Option` is used to produce 0 or 1 items.
161 /// let nums: Vec<i32> = ["1", "2", "whee!"].iter().flat_map(|x| x.parse().ok()).collect();
165 /// let nums: Vec<i32> = ["1", "2", "whee!"].iter().filter_map(|x| x.parse().ok()).collect();
167 #[clippy::version = "1.53.0"]
170 "used `flat_map` where `filter_map` could be used instead"
173 declare_clippy_lint! {
175 /// Checks for `.unwrap()` calls on `Option`s and on `Result`s.
177 /// ### Why is this bad?
178 /// It is better to handle the `None` or `Err` case,
179 /// or at least call `.expect(_)` with a more helpful message. Still, for a lot of
180 /// quick-and-dirty code, `unwrap` is a good choice, which is why this lint is
181 /// `Allow` by default.
183 /// `result.unwrap()` will let the thread panic on `Err` values.
184 /// Normally, you want to implement more sophisticated error handling,
185 /// and propagate errors upwards with `?` operator.
187 /// Even if you want to panic on errors, not all `Error`s implement good
188 /// messages on display. Therefore, it may be beneficial to look at the places
189 /// where they may get displayed. Activate this lint to do just that.
193 /// # let option = Some(1);
194 /// # let result: Result<usize, ()> = Ok(1);
201 /// # let option = Some(1);
202 /// # let result: Result<usize, ()> = Ok(1);
203 /// option.expect("more helpful message");
204 /// result.expect("more helpful message");
206 #[clippy::version = "1.45.0"]
209 "using `.unwrap()` on `Result` or `Option`, which should at least get a better message using `expect()`"
212 declare_clippy_lint! {
214 /// Checks for `.expect()` calls on `Option`s and `Result`s.
216 /// ### Why is this bad?
217 /// Usually it is better to handle the `None` or `Err` case.
218 /// Still, for a lot of quick-and-dirty code, `expect` is a good choice, which is why
219 /// this lint is `Allow` by default.
221 /// `result.expect()` will let the thread panic on `Err`
222 /// values. Normally, you want to implement more sophisticated error handling,
223 /// and propagate errors upwards with `?` operator.
227 /// # let option = Some(1);
228 /// # let result: Result<usize, ()> = Ok(1);
229 /// option.expect("one");
230 /// result.expect("one");
235 /// # let option = Some(1);
236 /// # let result: Result<usize, ()> = Ok(1);
243 #[clippy::version = "1.45.0"]
246 "using `.expect()` on `Result` or `Option`, which might be better handled"
249 declare_clippy_lint! {
251 /// Checks for methods that should live in a trait
252 /// implementation of a `std` trait (see [llogiq's blog
253 /// post](http://llogiq.github.io/2015/07/30/traits.html) for further
254 /// information) instead of an inherent implementation.
256 /// ### Why is this bad?
257 /// Implementing the traits improve ergonomics for users of
258 /// the code, often with very little cost. Also people seeing a `mul(...)`
260 /// may expect `*` to work equally, so you should have good reason to disappoint
267 /// fn add(&self, other: &X) -> X {
273 #[clippy::version = "pre 1.29.0"]
274 pub SHOULD_IMPLEMENT_TRAIT,
276 "defining a method that should be implementing a std trait"
279 declare_clippy_lint! {
281 /// Checks for methods with certain name prefixes and which
282 /// doesn't match how self is taken. The actual rules are:
284 /// |Prefix |Postfix |`self` taken | `self` type |
285 /// |-------|------------|-------------------------------|--------------|
286 /// |`as_` | none |`&self` or `&mut self` | any |
287 /// |`from_`| none | none | any |
288 /// |`into_`| none |`self` | any |
289 /// |`is_` | none |`&mut self` or `&self` or none | any |
290 /// |`to_` | `_mut` |`&mut self` | any |
291 /// |`to_` | not `_mut` |`self` | `Copy` |
292 /// |`to_` | not `_mut` |`&self` | not `Copy` |
294 /// Note: Clippy doesn't trigger methods with `to_` prefix in:
295 /// - Traits definition.
296 /// Clippy can not tell if a type that implements a trait is `Copy` or not.
297 /// - Traits implementation, when `&self` is taken.
298 /// The method signature is controlled by the trait and often `&self` is required for all types that implement the trait
299 /// (see e.g. the `std::string::ToString` trait).
301 /// Clippy allows `Pin<&Self>` and `Pin<&mut Self>` if `&self` and `&mut self` is required.
303 /// Please find more info here:
304 /// https://rust-lang.github.io/api-guidelines/naming.html#ad-hoc-conversions-follow-as_-to_-into_-conventions-c-conv
306 /// ### Why is this bad?
307 /// Consistency breeds readability. If you follow the
308 /// conventions, your users won't be surprised that they, e.g., need to supply a
309 /// mutable reference to a `as_..` function.
315 /// fn as_str(self) -> &'static str {
321 #[clippy::version = "pre 1.29.0"]
322 pub WRONG_SELF_CONVENTION,
324 "defining a method named with an established prefix (like \"into_\") that takes `self` with the wrong convention"
327 declare_clippy_lint! {
329 /// Checks for usage of `ok().expect(..)`.
331 /// ### Why is this bad?
332 /// Because you usually call `expect()` on the `Result`
333 /// directly to get a better error message.
335 /// ### Known problems
336 /// The error type needs to implement `Debug`
340 /// # let x = Ok::<_, ()>(());
341 /// x.ok().expect("why did I do this again?");
346 /// # let x = Ok::<_, ()>(());
347 /// x.expect("why did I do this again?");
349 #[clippy::version = "pre 1.29.0"]
352 "using `ok().expect()`, which gives worse error messages than calling `expect` directly on the Result"
355 declare_clippy_lint! {
357 /// Checks for `.err().expect()` calls on the `Result` type.
359 /// ### Why is this bad?
360 /// `.expect_err()` can be called directly to avoid the extra type conversion from `err()`.
364 /// let x: Result<u32, &str> = Ok(10);
365 /// x.err().expect("Testing err().expect()");
369 /// let x: Result<u32, &str> = Ok(10);
370 /// x.expect_err("Testing expect_err");
372 #[clippy::version = "1.61.0"]
375 r#"using `.err().expect("")` when `.expect_err("")` can be used"#
378 declare_clippy_lint! {
380 /// Checks for usages of `_.unwrap_or_else(Default::default)` on `Option` and
383 /// ### Why is this bad?
384 /// Readability, these can be written as `_.unwrap_or_default`, which is
385 /// simpler and more concise.
389 /// # let x = Some(1);
390 /// x.unwrap_or_else(Default::default);
391 /// x.unwrap_or_else(u32::default);
396 /// # let x = Some(1);
397 /// x.unwrap_or_default();
399 #[clippy::version = "1.56.0"]
400 pub UNWRAP_OR_ELSE_DEFAULT,
402 "using `.unwrap_or_else(Default::default)`, which is more succinctly expressed as `.unwrap_or_default()`"
405 declare_clippy_lint! {
407 /// Checks for usage of `option.map(_).unwrap_or(_)` or `option.map(_).unwrap_or_else(_)` or
408 /// `result.map(_).unwrap_or_else(_)`.
410 /// ### Why is this bad?
411 /// Readability, these can be written more concisely (resp.) as
412 /// `option.map_or(_, _)`, `option.map_or_else(_, _)` and `result.map_or_else(_, _)`.
414 /// ### Known problems
415 /// The order of the arguments is not in execution order
419 /// # let option = Some(1);
420 /// # let result: Result<usize, ()> = Ok(1);
421 /// # fn some_function(foo: ()) -> usize { 1 }
422 /// option.map(|a| a + 1).unwrap_or(0);
423 /// result.map(|a| a + 1).unwrap_or_else(some_function);
428 /// # let option = Some(1);
429 /// # let result: Result<usize, ()> = Ok(1);
430 /// # fn some_function(foo: ()) -> usize { 1 }
431 /// option.map_or(0, |a| a + 1);
432 /// result.map_or_else(some_function, |a| a + 1);
434 #[clippy::version = "1.45.0"]
437 "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)`"
440 declare_clippy_lint! {
442 /// Checks for usage of `_.map_or(None, _)`.
444 /// ### Why is this bad?
445 /// Readability, this can be written more concisely as
448 /// ### Known problems
449 /// The order of the arguments is not in execution order.
453 /// # let opt = Some(1);
454 /// opt.map_or(None, |a| Some(a + 1));
459 /// # let opt = Some(1);
460 /// opt.and_then(|a| Some(a + 1));
462 #[clippy::version = "pre 1.29.0"]
463 pub OPTION_MAP_OR_NONE,
465 "using `Option.map_or(None, f)`, which is more succinctly expressed as `and_then(f)`"
468 declare_clippy_lint! {
470 /// Checks for usage of `_.map_or(None, Some)`.
472 /// ### Why is this bad?
473 /// Readability, this can be written more concisely as
478 /// # let r: Result<u32, &str> = Ok(1);
479 /// assert_eq!(Some(1), r.map_or(None, Some));
484 /// # let r: Result<u32, &str> = Ok(1);
485 /// assert_eq!(Some(1), r.ok());
487 #[clippy::version = "1.44.0"]
488 pub RESULT_MAP_OR_INTO_OPTION,
490 "using `Result.map_or(None, Some)`, which is more succinctly expressed as `ok()`"
493 declare_clippy_lint! {
495 /// Checks for usage of `_.and_then(|x| Some(y))`, `_.and_then(|x| Ok(y))` or
496 /// `_.or_else(|x| Err(y))`.
498 /// ### Why is this bad?
499 /// Readability, this can be written more concisely as
500 /// `_.map(|x| y)` or `_.map_err(|x| y)`.
504 /// # fn opt() -> Option<&'static str> { Some("42") }
505 /// # fn res() -> Result<&'static str, &'static str> { Ok("42") }
506 /// let _ = opt().and_then(|s| Some(s.len()));
507 /// let _ = res().and_then(|s| if s.len() == 42 { Ok(10) } else { Ok(20) });
508 /// let _ = res().or_else(|s| if s.len() == 42 { Err(10) } else { Err(20) });
511 /// The correct use would be:
514 /// # fn opt() -> Option<&'static str> { Some("42") }
515 /// # fn res() -> Result<&'static str, &'static str> { Ok("42") }
516 /// let _ = opt().map(|s| s.len());
517 /// let _ = res().map(|s| if s.len() == 42 { 10 } else { 20 });
518 /// let _ = res().map_err(|s| if s.len() == 42 { 10 } else { 20 });
520 #[clippy::version = "1.45.0"]
521 pub BIND_INSTEAD_OF_MAP,
523 "using `Option.and_then(|x| Some(y))`, which is more succinctly expressed as `map(|x| y)`"
526 declare_clippy_lint! {
528 /// Checks for usage of `_.filter(_).next()`.
530 /// ### Why is this bad?
531 /// Readability, this can be written more concisely as
536 /// # let vec = vec![1];
537 /// vec.iter().filter(|x| **x == 0).next();
542 /// # let vec = vec![1];
543 /// vec.iter().find(|x| **x == 0);
545 #[clippy::version = "pre 1.29.0"]
548 "using `filter(p).next()`, which is more succinctly expressed as `.find(p)`"
551 declare_clippy_lint! {
553 /// Checks for usage of `_.skip_while(condition).next()`.
555 /// ### Why is this bad?
556 /// Readability, this can be written more concisely as
557 /// `_.find(!condition)`.
561 /// # let vec = vec![1];
562 /// vec.iter().skip_while(|x| **x == 0).next();
567 /// # let vec = vec![1];
568 /// vec.iter().find(|x| **x != 0);
570 #[clippy::version = "1.42.0"]
573 "using `skip_while(p).next()`, which is more succinctly expressed as `.find(!p)`"
576 declare_clippy_lint! {
578 /// Checks for usage of `_.map(_).flatten(_)` on `Iterator` and `Option`
580 /// ### Why is this bad?
581 /// Readability, this can be written more concisely as
582 /// `_.flat_map(_)` for `Iterator` or `_.and_then(_)` for `Option`
586 /// let vec = vec![vec![1]];
587 /// let opt = Some(5);
589 /// vec.iter().map(|x| x.iter()).flatten();
590 /// opt.map(|x| Some(x * 2)).flatten();
595 /// # let vec = vec![vec![1]];
596 /// # let opt = Some(5);
597 /// vec.iter().flat_map(|x| x.iter());
598 /// opt.and_then(|x| Some(x * 2));
600 #[clippy::version = "1.31.0"]
603 "using combinations of `flatten` and `map` which can usually be written as a single method call"
606 declare_clippy_lint! {
608 /// Checks for usage of `_.filter(_).map(_)` that can be written more simply
609 /// as `filter_map(_)`.
611 /// ### Why is this bad?
612 /// Redundant code in the `filter` and `map` operations is poor style and
617 /// # #![allow(unused)]
619 /// .filter(|n| n.checked_add(1).is_some())
620 /// .map(|n| n.checked_add(1).unwrap());
625 /// # #[allow(unused)]
626 /// (0_i32..10).filter_map(|n| n.checked_add(1));
628 #[clippy::version = "1.51.0"]
629 pub MANUAL_FILTER_MAP,
631 "using `_.filter(_).map(_)` in a way that can be written more simply as `filter_map(_)`"
634 declare_clippy_lint! {
636 /// Checks for usage of `_.find(_).map(_)` that can be written more simply
637 /// as `find_map(_)`.
639 /// ### Why is this bad?
640 /// Redundant code in the `find` and `map` operations is poor style and
646 /// .find(|n| n.checked_add(1).is_some())
647 /// .map(|n| n.checked_add(1).unwrap());
652 /// (0_i32..10).find_map(|n| n.checked_add(1));
654 #[clippy::version = "1.51.0"]
657 "using `_.find(_).map(_)` in a way that can be written more simply as `find_map(_)`"
660 declare_clippy_lint! {
662 /// Checks for usage of `_.filter_map(_).next()`.
664 /// ### Why is this bad?
665 /// Readability, this can be written more concisely as
670 /// (0..3).filter_map(|x| if x == 2 { Some(x) } else { None }).next();
672 /// Can be written as
675 /// (0..3).find_map(|x| if x == 2 { Some(x) } else { None });
677 #[clippy::version = "1.36.0"]
680 "using combination of `filter_map` and `next` which can usually be written as a single method call"
683 declare_clippy_lint! {
685 /// Checks for usage of `flat_map(|x| x)`.
687 /// ### Why is this bad?
688 /// Readability, this can be written more concisely by using `flatten`.
692 /// # let iter = vec![vec![0]].into_iter();
693 /// iter.flat_map(|x| x);
695 /// Can be written as
697 /// # let iter = vec![vec![0]].into_iter();
700 #[clippy::version = "1.39.0"]
701 pub FLAT_MAP_IDENTITY,
703 "call to `flat_map` where `flatten` is sufficient"
706 declare_clippy_lint! {
708 /// Checks for an iterator or string search (such as `find()`,
709 /// `position()`, or `rposition()`) followed by a call to `is_some()` or `is_none()`.
711 /// ### Why is this bad?
712 /// Readability, this can be written more concisely as:
713 /// * `_.any(_)`, or `_.contains(_)` for `is_some()`,
714 /// * `!_.any(_)`, or `!_.contains(_)` for `is_none()`.
718 /// # #![allow(unused)]
719 /// let vec = vec![1];
720 /// vec.iter().find(|x| **x == 0).is_some();
722 /// "hello world".find("world").is_none();
727 /// let vec = vec![1];
728 /// vec.iter().any(|x| *x == 0);
730 /// # #[allow(unused)]
731 /// !"hello world".contains("world");
733 #[clippy::version = "pre 1.29.0"]
736 "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()`)"
739 declare_clippy_lint! {
741 /// Checks for usage of `.chars().next()` on a `str` to check
742 /// if it starts with a given char.
744 /// ### Why is this bad?
745 /// Readability, this can be written more concisely as
746 /// `_.starts_with(_)`.
750 /// let name = "foo";
751 /// if name.chars().next() == Some('_') {};
756 /// let name = "foo";
757 /// if name.starts_with('_') {};
759 #[clippy::version = "pre 1.29.0"]
762 "using `.chars().next()` to check if a string starts with a char"
765 declare_clippy_lint! {
767 /// Checks for calls to `.or(foo(..))`, `.unwrap_or(foo(..))`,
768 /// etc., and suggests to use `or_else`, `unwrap_or_else`, etc., or
769 /// `unwrap_or_default` instead.
771 /// ### Why is this bad?
772 /// The function will always be called and potentially
773 /// allocate an object acting as the default.
775 /// ### Known problems
776 /// If the function has side-effects, not calling it will
777 /// change the semantic of the program, but you shouldn't rely on that anyway.
781 /// # let foo = Some(String::new());
782 /// foo.unwrap_or(String::new());
787 /// # let foo = Some(String::new());
788 /// foo.unwrap_or_else(String::new);
792 /// # let foo = Some(String::new());
793 /// foo.unwrap_or_default();
795 #[clippy::version = "pre 1.29.0"]
798 "using any `*or` method with a function call, which suggests `*or_else`"
801 declare_clippy_lint! {
803 /// Checks for `.or(…).unwrap()` calls to Options and Results.
805 /// ### Why is this bad?
806 /// You should use `.unwrap_or(…)` instead for clarity.
810 /// # let fallback = "fallback";
812 /// # type Error = &'static str;
813 /// # let result: Result<&str, Error> = Err("error");
814 /// let value = result.or::<Error>(Ok(fallback)).unwrap();
817 /// # let option: Option<&str> = None;
818 /// let value = option.or(Some(fallback)).unwrap();
822 /// # let fallback = "fallback";
824 /// # let result: Result<&str, &str> = Err("error");
825 /// let value = result.unwrap_or(fallback);
828 /// # let option: Option<&str> = None;
829 /// let value = option.unwrap_or(fallback);
831 #[clippy::version = "1.61.0"]
834 "checks for `.or(…).unwrap()` calls to Options and Results."
837 declare_clippy_lint! {
839 /// Checks for calls to `.expect(&format!(...))`, `.expect(foo(..))`,
840 /// etc., and suggests to use `unwrap_or_else` instead
842 /// ### Why is this bad?
843 /// The function will always be called.
845 /// ### Known problems
846 /// If the function has side-effects, not calling it will
847 /// change the semantics of the program, but you shouldn't rely on that anyway.
851 /// # let foo = Some(String::new());
852 /// # let err_code = "418";
853 /// # let err_msg = "I'm a teapot";
854 /// foo.expect(&format!("Err {}: {}", err_code, err_msg));
858 /// # let foo = Some(String::new());
859 /// foo.expect(format!("Err {}: {}", err_code, err_msg).as_str());
864 /// # let foo = Some(String::new());
865 /// # let err_code = "418";
866 /// # let err_msg = "I'm a teapot";
867 /// foo.unwrap_or_else(|| panic!("Err {}: {}", err_code, err_msg));
869 #[clippy::version = "pre 1.29.0"]
872 "using any `expect` method with a function call"
875 declare_clippy_lint! {
877 /// Checks for usage of `.clone()` on a `Copy` type.
879 /// ### Why is this bad?
880 /// The only reason `Copy` types implement `Clone` is for
881 /// generics, not for using the `clone` method on a concrete type.
887 #[clippy::version = "pre 1.29.0"]
890 "using `clone` on a `Copy` type"
893 declare_clippy_lint! {
895 /// Checks for usage of `.clone()` on a ref-counted pointer,
896 /// (`Rc`, `Arc`, `rc::Weak`, or `sync::Weak`), and suggests calling Clone via unified
897 /// function syntax instead (e.g., `Rc::clone(foo)`).
899 /// ### Why is this bad?
900 /// Calling '.clone()' on an Rc, Arc, or Weak
901 /// can obscure the fact that only the pointer is being cloned, not the underlying
906 /// # use std::rc::Rc;
907 /// let x = Rc::new(1);
914 /// # use std::rc::Rc;
915 /// # let x = Rc::new(1);
918 #[clippy::version = "pre 1.29.0"]
919 pub CLONE_ON_REF_PTR,
921 "using 'clone' on a ref-counted pointer"
924 declare_clippy_lint! {
926 /// Checks for usage of `.clone()` on an `&&T`.
928 /// ### Why is this bad?
929 /// Cloning an `&&T` copies the inner `&T`, instead of
930 /// cloning the underlying `T`.
937 /// let z = y.clone();
938 /// println!("{:p} {:p}", *y, z); // prints out the same pointer
941 #[clippy::version = "pre 1.29.0"]
942 pub CLONE_DOUBLE_REF,
944 "using `clone` on `&&T`"
947 declare_clippy_lint! {
949 /// Checks for usage of `.to_string()` on an `&&T` where
950 /// `T` implements `ToString` directly (like `&&str` or `&&String`).
952 /// ### Why is this bad?
953 /// This bypasses the specialized implementation of
954 /// `ToString` and instead goes through the more expensive string formatting
959 /// // Generic implementation for `T: Display` is used (slow)
960 /// ["foo", "bar"].iter().map(|s| s.to_string());
962 /// // OK, the specialized impl is used
963 /// ["foo", "bar"].iter().map(|&s| s.to_string());
965 #[clippy::version = "1.40.0"]
966 pub INEFFICIENT_TO_STRING,
968 "using `to_string` on `&&T` where `T: ToString`"
971 declare_clippy_lint! {
973 /// Checks for `new` not returning a type that contains `Self`.
975 /// ### Why is this bad?
976 /// As a convention, `new` methods are used to make a new
977 /// instance of a type.
980 /// In an impl block:
983 /// # struct NotAFoo;
985 /// fn new() -> NotAFoo {
995 /// // Bad. The type name must contain `Self`
996 /// fn new() -> Bar {
1004 /// # struct FooError;
1006 /// // Good. Return type contains `Self`
1007 /// fn new() -> Result<Foo, FooError> {
1013 /// Or in a trait definition:
1015 /// pub trait Trait {
1016 /// // Bad. The type name must contain `Self`
1022 /// pub trait Trait {
1023 /// // Good. Return type contains `Self`
1024 /// fn new() -> Self;
1027 #[clippy::version = "pre 1.29.0"]
1028 pub NEW_RET_NO_SELF,
1030 "not returning type containing `Self` in a `new` method"
1033 declare_clippy_lint! {
1034 /// ### What it does
1035 /// Checks for string methods that receive a single-character
1036 /// `str` as an argument, e.g., `_.split("x")`.
1038 /// ### Why is this bad?
1039 /// Performing these methods using a `char` is faster than
1042 /// ### Known problems
1043 /// Does not catch multi-byte unicode characters.
1054 #[clippy::version = "pre 1.29.0"]
1055 pub SINGLE_CHAR_PATTERN,
1057 "using a single-character str where a char could be used, e.g., `_.split(\"x\")`"
1060 declare_clippy_lint! {
1061 /// ### What it does
1062 /// Checks for calling `.step_by(0)` on iterators which panics.
1064 /// ### Why is this bad?
1065 /// This very much looks like an oversight. Use `panic!()` instead if you
1066 /// actually intend to panic.
1069 /// ```rust,should_panic
1070 /// for x in (0..100).step_by(0) {
1074 #[clippy::version = "pre 1.29.0"]
1075 pub ITERATOR_STEP_BY_ZERO,
1077 "using `Iterator::step_by(0)`, which will panic at runtime"
1080 declare_clippy_lint! {
1081 /// ### What it does
1082 /// Checks for indirect collection of populated `Option`
1084 /// ### Why is this bad?
1085 /// `Option` is like a collection of 0-1 things, so `flatten`
1086 /// automatically does this without suspicious-looking `unwrap` calls.
1090 /// let _ = std::iter::empty::<Option<i32>>().filter(Option::is_some).map(Option::unwrap);
1094 /// let _ = std::iter::empty::<Option<i32>>().flatten();
1096 #[clippy::version = "1.53.0"]
1097 pub OPTION_FILTER_MAP,
1099 "filtering `Option` for `Some` then force-unwrapping, which can be one type-safe operation"
1102 declare_clippy_lint! {
1103 /// ### What it does
1104 /// Checks for the use of `iter.nth(0)`.
1106 /// ### Why is this bad?
1107 /// `iter.next()` is equivalent to
1108 /// `iter.nth(0)`, as they both consume the next element,
1109 /// but is more readable.
1113 /// # use std::collections::HashSet;
1114 /// # let mut s = HashSet::new();
1116 /// let x = s.iter().nth(0);
1121 /// # use std::collections::HashSet;
1122 /// # let mut s = HashSet::new();
1124 /// let x = s.iter().next();
1126 #[clippy::version = "1.42.0"]
1129 "replace `iter.nth(0)` with `iter.next()`"
1132 declare_clippy_lint! {
1133 /// ### What it does
1134 /// Checks for use of `.iter().nth()` (and the related
1135 /// `.iter_mut().nth()`) on standard library types with *O*(1) element access.
1137 /// ### Why is this bad?
1138 /// `.get()` and `.get_mut()` are more efficient and more
1143 /// let some_vec = vec![0, 1, 2, 3];
1144 /// let bad_vec = some_vec.iter().nth(3);
1145 /// let bad_slice = &some_vec[..].iter().nth(3);
1147 /// The correct use would be:
1149 /// let some_vec = vec![0, 1, 2, 3];
1150 /// let bad_vec = some_vec.get(3);
1151 /// let bad_slice = &some_vec[..].get(3);
1153 #[clippy::version = "pre 1.29.0"]
1156 "using `.iter().nth()` on a standard library type with O(1) element access"
1159 declare_clippy_lint! {
1160 /// ### What it does
1161 /// Checks for use of `.skip(x).next()` on iterators.
1163 /// ### Why is this bad?
1164 /// `.nth(x)` is cleaner
1168 /// let some_vec = vec![0, 1, 2, 3];
1169 /// let bad_vec = some_vec.iter().skip(3).next();
1170 /// let bad_slice = &some_vec[..].iter().skip(3).next();
1172 /// The correct use would be:
1174 /// let some_vec = vec![0, 1, 2, 3];
1175 /// let bad_vec = some_vec.iter().nth(3);
1176 /// let bad_slice = &some_vec[..].iter().nth(3);
1178 #[clippy::version = "pre 1.29.0"]
1181 "using `.skip(x).next()` on an iterator"
1184 declare_clippy_lint! {
1185 /// ### What it does
1186 /// Checks for use of `.drain(..)` on `Vec` and `VecDeque` for iteration.
1188 /// ### Why is this bad?
1189 /// `.into_iter()` is simpler with better performance.
1193 /// # use std::collections::HashSet;
1194 /// let mut foo = vec![0, 1, 2, 3];
1195 /// let bar: HashSet<usize> = foo.drain(..).collect();
1199 /// # use std::collections::HashSet;
1200 /// let foo = vec![0, 1, 2, 3];
1201 /// let bar: HashSet<usize> = foo.into_iter().collect();
1203 #[clippy::version = "1.61.0"]
1204 pub ITER_WITH_DRAIN,
1206 "replace `.drain(..)` with `.into_iter()`"
1209 declare_clippy_lint! {
1210 /// ### What it does
1211 /// Checks for using `x.get(x.len() - 1)` instead of
1214 /// ### Why is this bad?
1215 /// Using `x.last()` is easier to read and has the same
1218 /// Note that using `x[x.len() - 1]` is semantically different from
1219 /// `x.last()`. Indexing into the array will panic on out-of-bounds
1220 /// accesses, while `x.get()` and `x.last()` will return `None`.
1222 /// There is another lint (get_unwrap) that covers the case of using
1223 /// `x.get(index).unwrap()` instead of `x[index]`.
1227 /// let x = vec![2, 3, 5];
1228 /// let last_element = x.get(x.len() - 1);
1233 /// let x = vec![2, 3, 5];
1234 /// let last_element = x.last();
1236 #[clippy::version = "1.37.0"]
1237 pub GET_LAST_WITH_LEN,
1239 "Using `x.get(x.len() - 1)` when `x.last()` is correct and simpler"
1242 declare_clippy_lint! {
1243 /// ### What it does
1244 /// Checks for use of `.get().unwrap()` (or
1245 /// `.get_mut().unwrap`) on a standard library type which implements `Index`
1247 /// ### Why is this bad?
1248 /// Using the Index trait (`[]`) is more clear and more
1251 /// ### Known problems
1252 /// Not a replacement for error handling: Using either
1253 /// `.unwrap()` or the Index trait (`[]`) carries the risk of causing a `panic`
1254 /// if the value being accessed is `None`. If the use of `.get().unwrap()` is a
1255 /// temporary placeholder for dealing with the `Option` type, then this does
1256 /// not mitigate the need for error handling. If there is a chance that `.get()`
1257 /// will be `None` in your program, then it is advisable that the `None` case
1258 /// is handled in a future refactor instead of using `.unwrap()` or the Index
1263 /// let mut some_vec = vec![0, 1, 2, 3];
1264 /// let last = some_vec.get(3).unwrap();
1265 /// *some_vec.get_mut(0).unwrap() = 1;
1267 /// The correct use would be:
1269 /// let mut some_vec = vec![0, 1, 2, 3];
1270 /// let last = some_vec[3];
1271 /// some_vec[0] = 1;
1273 #[clippy::version = "pre 1.29.0"]
1276 "using `.get().unwrap()` or `.get_mut().unwrap()` when using `[]` would work instead"
1279 declare_clippy_lint! {
1280 /// ### What it does
1281 /// Checks for occurrences where one vector gets extended instead of append
1283 /// ### Why is this bad?
1284 /// Using `append` instead of `extend` is more concise and faster
1288 /// let mut a = vec![1, 2, 3];
1289 /// let mut b = vec![4, 5, 6];
1291 /// a.extend(b.drain(..));
1296 /// let mut a = vec![1, 2, 3];
1297 /// let mut b = vec![4, 5, 6];
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 = "_";
1373 /// name.chars().last() == Some('_') || name.chars().next_back() == Some('-');
1378 /// # let name = "_";
1379 /// name.ends_with('_') || name.ends_with('-');
1381 #[clippy::version = "pre 1.29.0"]
1384 "using `.chars().last()` or `.chars().next_back()` to check if a string ends with a char"
1387 declare_clippy_lint! {
1388 /// ### What it does
1389 /// Checks for usage of `.as_ref()` or `.as_mut()` where the
1390 /// types before and after the call are the same.
1392 /// ### Why is this bad?
1393 /// The call is unnecessary.
1397 /// # fn do_stuff(x: &[i32]) {}
1398 /// let x: &[i32] = &[1, 2, 3, 4, 5];
1399 /// do_stuff(x.as_ref());
1401 /// The correct use would be:
1403 /// # fn do_stuff(x: &[i32]) {}
1404 /// let x: &[i32] = &[1, 2, 3, 4, 5];
1407 #[clippy::version = "pre 1.29.0"]
1410 "using `as_ref` where the types before and after the call are the same"
1413 declare_clippy_lint! {
1414 /// ### What it does
1415 /// Checks for using `fold` when a more succinct alternative exists.
1416 /// Specifically, this checks for `fold`s which could be replaced by `any`, `all`,
1417 /// `sum` or `product`.
1419 /// ### Why is this bad?
1424 /// # #[allow(unused)]
1425 /// (0..3).fold(false, |acc, x| acc || x > 2);
1430 /// (0..3).any(|x| x > 2);
1432 #[clippy::version = "pre 1.29.0"]
1433 pub UNNECESSARY_FOLD,
1435 "using `fold` when a more succinct alternative exists"
1438 declare_clippy_lint! {
1439 /// ### What it does
1440 /// Checks for `filter_map` calls that could be replaced by `filter` or `map`.
1441 /// More specifically it checks if the closure provided is only performing one of the
1442 /// filter or map operations and suggests the appropriate option.
1444 /// ### Why is this bad?
1445 /// Complexity. The intent is also clearer if only a single
1446 /// operation is being performed.
1450 /// let _ = (0..3).filter_map(|x| if x > 2 { Some(x) } else { None });
1452 /// // As there is no transformation of the argument this could be written as:
1453 /// let _ = (0..3).filter(|&x| x > 2);
1457 /// let _ = (0..4).filter_map(|x| Some(x + 1));
1459 /// // As there is no conditional check on the argument this could be written as:
1460 /// let _ = (0..4).map(|x| x + 1);
1462 #[clippy::version = "1.31.0"]
1463 pub UNNECESSARY_FILTER_MAP,
1465 "using `filter_map` when a more succinct alternative exists"
1468 declare_clippy_lint! {
1469 /// ### What it does
1470 /// Checks for `find_map` calls that could be replaced by `find` or `map`. More
1471 /// specifically it checks if the closure provided is only performing one of the
1472 /// find or map operations and suggests the appropriate option.
1474 /// ### Why is this bad?
1475 /// Complexity. The intent is also clearer if only a single
1476 /// operation is being performed.
1480 /// let _ = (0..3).find_map(|x| if x > 2 { Some(x) } else { None });
1482 /// // As there is no transformation of the argument this could be written as:
1483 /// let _ = (0..3).find(|&x| x > 2);
1487 /// let _ = (0..4).find_map(|x| Some(x + 1));
1489 /// // As there is no conditional check on the argument this could be written as:
1490 /// let _ = (0..4).map(|x| x + 1).next();
1492 #[clippy::version = "1.61.0"]
1493 pub UNNECESSARY_FIND_MAP,
1495 "using `find_map` when a more succinct alternative exists"
1498 declare_clippy_lint! {
1499 /// ### What it does
1500 /// Checks for `into_iter` calls on references which should be replaced by `iter`
1503 /// ### Why is this bad?
1504 /// Readability. Calling `into_iter` on a reference will not move out its
1505 /// content into the resulting iterator, which is confusing. It is better just call `iter` or
1506 /// `iter_mut` directly.
1510 /// # let vec = vec![3, 4, 5];
1511 /// (&vec).into_iter();
1516 /// # let vec = vec![3, 4, 5];
1519 #[clippy::version = "1.32.0"]
1520 pub INTO_ITER_ON_REF,
1522 "using `.into_iter()` on a reference"
1525 declare_clippy_lint! {
1526 /// ### What it does
1527 /// Checks for calls to `map` followed by a `count`.
1529 /// ### Why is this bad?
1530 /// It looks suspicious. Maybe `map` was confused with `filter`.
1531 /// If the `map` call is intentional, this should be rewritten
1532 /// using `inspect`. Or, if you intend to drive the iterator to
1533 /// completion, you can just use `for_each` instead.
1537 /// let _ = (0..3).map(|x| x + 2).count();
1539 #[clippy::version = "1.39.0"]
1542 "suspicious usage of map"
1545 declare_clippy_lint! {
1546 /// ### What it does
1547 /// Checks for `MaybeUninit::uninit().assume_init()`.
1549 /// ### Why is this bad?
1550 /// For most types, this is undefined behavior.
1552 /// ### Known problems
1553 /// For now, we accept empty tuples and tuples / arrays
1554 /// of `MaybeUninit`. There may be other types that allow uninitialized
1555 /// data, but those are not yet rigorously defined.
1559 /// // Beware the UB
1560 /// use std::mem::MaybeUninit;
1562 /// let _: usize = unsafe { MaybeUninit::uninit().assume_init() };
1565 /// Note that the following is OK:
1568 /// use std::mem::MaybeUninit;
1570 /// let _: [MaybeUninit<bool>; 5] = unsafe {
1571 /// MaybeUninit::uninit().assume_init()
1574 #[clippy::version = "1.39.0"]
1575 pub UNINIT_ASSUMED_INIT,
1577 "`MaybeUninit::uninit().assume_init()`"
1580 declare_clippy_lint! {
1581 /// ### What it does
1582 /// Checks for `.checked_add/sub(x).unwrap_or(MAX/MIN)`.
1584 /// ### Why is this bad?
1585 /// These can be written simply with `saturating_add/sub` methods.
1589 /// # let y: u32 = 0;
1590 /// # let x: u32 = 100;
1591 /// let add = x.checked_add(y).unwrap_or(u32::MAX);
1592 /// let sub = x.checked_sub(y).unwrap_or(u32::MIN);
1595 /// can be written using dedicated methods for saturating addition/subtraction as:
1598 /// # let y: u32 = 0;
1599 /// # let x: u32 = 100;
1600 /// let add = x.saturating_add(y);
1601 /// let sub = x.saturating_sub(y);
1603 #[clippy::version = "1.39.0"]
1604 pub MANUAL_SATURATING_ARITHMETIC,
1606 "`.checked_add/sub(x).unwrap_or(MAX/MIN)`"
1609 declare_clippy_lint! {
1610 /// ### What it does
1611 /// Checks for `offset(_)`, `wrapping_`{`add`, `sub`}, etc. on raw pointers to
1612 /// zero-sized types
1614 /// ### Why is this bad?
1615 /// This is a no-op, and likely unintended
1619 /// unsafe { (&() as *const ()).offset(1) };
1621 #[clippy::version = "1.41.0"]
1624 "Check for offset calculations on raw pointers to zero-sized types"
1627 declare_clippy_lint! {
1628 /// ### What it does
1629 /// Checks for `FileType::is_file()`.
1631 /// ### Why is this bad?
1632 /// When people testing a file type with `FileType::is_file`
1633 /// they are testing whether a path is something they can get bytes from. But
1634 /// `is_file` doesn't cover special file types in unix-like systems, and doesn't cover
1635 /// symlink in windows. Using `!FileType::is_dir()` is a better way to that intention.
1640 /// let metadata = std::fs::metadata("foo.txt")?;
1641 /// let filetype = metadata.file_type();
1643 /// if filetype.is_file() {
1646 /// # Ok::<_, std::io::Error>(())
1650 /// should be written as:
1654 /// let metadata = std::fs::metadata("foo.txt")?;
1655 /// let filetype = metadata.file_type();
1657 /// if !filetype.is_dir() {
1660 /// # Ok::<_, std::io::Error>(())
1663 #[clippy::version = "1.42.0"]
1664 pub FILETYPE_IS_FILE,
1666 "`FileType::is_file` is not recommended to test for readable file type"
1669 declare_clippy_lint! {
1670 /// ### What it does
1671 /// Checks for usage of `_.as_ref().map(Deref::deref)` or it's aliases (such as String::as_str).
1673 /// ### Why is this bad?
1674 /// Readability, this can be written more concisely as
1679 /// # let opt = Some("".to_string());
1680 /// opt.as_ref().map(String::as_str)
1683 /// Can be written as
1685 /// # let opt = Some("".to_string());
1689 #[clippy::version = "1.42.0"]
1690 pub OPTION_AS_REF_DEREF,
1692 "using `as_ref().map(Deref::deref)`, which is more succinctly expressed as `as_deref()`"
1695 declare_clippy_lint! {
1696 /// ### What it does
1697 /// Checks for usage of `iter().next()` on a Slice or an Array
1699 /// ### Why is this bad?
1700 /// These can be shortened into `.get()`
1704 /// # let a = [1, 2, 3];
1705 /// # let b = vec![1, 2, 3];
1706 /// a[2..].iter().next();
1707 /// b.iter().next();
1709 /// should be written as:
1711 /// # let a = [1, 2, 3];
1712 /// # let b = vec![1, 2, 3];
1716 #[clippy::version = "1.46.0"]
1717 pub ITER_NEXT_SLICE,
1719 "using `.iter().next()` on a sliced array, which can be shortened to just `.get()`"
1722 declare_clippy_lint! {
1723 /// ### What it does
1724 /// Warns when using `push_str`/`insert_str` with a single-character string literal
1725 /// where `push`/`insert` with a `char` would work fine.
1727 /// ### Why is this bad?
1728 /// It's less clear that we are pushing a single character.
1732 /// # let mut string = String::new();
1733 /// string.insert_str(0, "R");
1734 /// string.push_str("R");
1739 /// # let mut string = String::new();
1740 /// string.insert(0, 'R');
1741 /// string.push('R');
1743 #[clippy::version = "1.49.0"]
1744 pub SINGLE_CHAR_ADD_STR,
1746 "`push_str()` or `insert_str()` used with a single-character string literal as parameter"
1749 declare_clippy_lint! {
1750 /// ### What it does
1751 /// As the counterpart to `or_fun_call`, this lint looks for unnecessary
1752 /// lazily evaluated closures on `Option` and `Result`.
1754 /// This lint suggests changing the following functions, when eager evaluation results in
1756 /// - `unwrap_or_else` to `unwrap_or`
1757 /// - `and_then` to `and`
1758 /// - `or_else` to `or`
1759 /// - `get_or_insert_with` to `get_or_insert`
1760 /// - `ok_or_else` to `ok_or`
1762 /// ### Why is this bad?
1763 /// Using eager evaluation is shorter and simpler in some cases.
1765 /// ### Known problems
1766 /// It is possible, but not recommended for `Deref` and `Index` to have
1767 /// side effects. Eagerly evaluating them can change the semantics of the program.
1771 /// // example code where clippy issues a warning
1772 /// let opt: Option<u32> = None;
1774 /// opt.unwrap_or_else(|| 42);
1778 /// let opt: Option<u32> = None;
1780 /// opt.unwrap_or(42);
1782 #[clippy::version = "1.48.0"]
1783 pub UNNECESSARY_LAZY_EVALUATIONS,
1785 "using unnecessary lazy evaluation, which can be replaced with simpler eager evaluation"
1788 declare_clippy_lint! {
1789 /// ### What it does
1790 /// Checks for usage of `_.map(_).collect::<Result<(), _>()`.
1792 /// ### Why is this bad?
1793 /// Using `try_for_each` instead is more readable and idiomatic.
1797 /// (0..3).map(|t| Err(t)).collect::<Result<(), _>>();
1801 /// (0..3).try_for_each(|t| Err(t));
1803 #[clippy::version = "1.49.0"]
1804 pub MAP_COLLECT_RESULT_UNIT,
1806 "using `.map(_).collect::<Result<(),_>()`, which can be replaced with `try_for_each`"
1809 declare_clippy_lint! {
1810 /// ### What it does
1811 /// Checks for `from_iter()` function calls on types that implement the `FromIterator`
1814 /// ### Why is this bad?
1815 /// It is recommended style to use collect. See
1816 /// [FromIterator documentation](https://doc.rust-lang.org/std/iter/trait.FromIterator.html)
1820 /// let five_fives = std::iter::repeat(5).take(5);
1822 /// let v = Vec::from_iter(five_fives);
1824 /// assert_eq!(v, vec![5, 5, 5, 5, 5]);
1828 /// let five_fives = std::iter::repeat(5).take(5);
1830 /// let v: Vec<i32> = five_fives.collect();
1832 /// assert_eq!(v, vec![5, 5, 5, 5, 5]);
1834 #[clippy::version = "1.49.0"]
1835 pub FROM_ITER_INSTEAD_OF_COLLECT,
1837 "use `.collect()` instead of `::from_iter()`"
1840 declare_clippy_lint! {
1841 /// ### What it does
1842 /// Checks for usage of `inspect().for_each()`.
1844 /// ### Why is this bad?
1845 /// It is the same as performing the computation
1846 /// inside `inspect` at the beginning of the closure in `for_each`.
1850 /// [1,2,3,4,5].iter()
1851 /// .inspect(|&x| println!("inspect the number: {}", x))
1852 /// .for_each(|&x| {
1853 /// assert!(x >= 0);
1856 /// Can be written as
1858 /// [1,2,3,4,5].iter()
1859 /// .for_each(|&x| {
1860 /// println!("inspect the number: {}", x);
1861 /// assert!(x >= 0);
1864 #[clippy::version = "1.51.0"]
1865 pub INSPECT_FOR_EACH,
1867 "using `.inspect().for_each()`, which can be replaced with `.for_each()`"
1870 declare_clippy_lint! {
1871 /// ### What it does
1872 /// Checks for usage of `filter_map(|x| x)`.
1874 /// ### Why is this bad?
1875 /// Readability, this can be written more concisely by using `flatten`.
1879 /// # let iter = vec![Some(1)].into_iter();
1880 /// iter.filter_map(|x| x);
1884 /// # let iter = vec![Some(1)].into_iter();
1887 #[clippy::version = "1.52.0"]
1888 pub FILTER_MAP_IDENTITY,
1890 "call to `filter_map` where `flatten` is sufficient"
1893 declare_clippy_lint! {
1894 /// ### What it does
1895 /// Checks for instances of `map(f)` where `f` is the identity function.
1897 /// ### Why is this bad?
1898 /// It can be written more concisely without the call to `map`.
1902 /// let x = [1, 2, 3];
1903 /// let y: Vec<_> = x.iter().map(|x| x).map(|x| 2*x).collect();
1907 /// let x = [1, 2, 3];
1908 /// let y: Vec<_> = x.iter().map(|x| 2*x).collect();
1910 #[clippy::version = "1.52.0"]
1913 "using iterator.map(|x| x)"
1916 declare_clippy_lint! {
1917 /// ### What it does
1918 /// Checks for the use of `.bytes().nth()`.
1920 /// ### Why is this bad?
1921 /// `.as_bytes().get()` is more efficient and more
1926 /// # #[allow(unused)]
1927 /// "Hello".bytes().nth(3);
1932 /// # #[allow(unused)]
1933 /// "Hello".as_bytes().get(3);
1935 #[clippy::version = "1.52.0"]
1938 "replace `.bytes().nth()` with `.as_bytes().get()`"
1941 declare_clippy_lint! {
1942 /// ### What it does
1943 /// Checks for the usage of `_.to_owned()`, `vec.to_vec()`, or similar when calling `_.clone()` would be clearer.
1945 /// ### Why is this bad?
1946 /// These methods do the same thing as `_.clone()` but may be confusing as
1947 /// to why we are calling `to_vec` on something that is already a `Vec` or calling `to_owned` on something that is already owned.
1951 /// let a = vec![1, 2, 3];
1952 /// let b = a.to_vec();
1953 /// let c = a.to_owned();
1957 /// let a = vec![1, 2, 3];
1958 /// let b = a.clone();
1959 /// let c = a.clone();
1961 #[clippy::version = "1.52.0"]
1964 "implicitly cloning a value by invoking a function on its dereferenced type"
1967 declare_clippy_lint! {
1968 /// ### What it does
1969 /// Checks for the use of `.iter().count()`.
1971 /// ### Why is this bad?
1972 /// `.len()` is more efficient and more
1977 /// # #![allow(unused)]
1978 /// let some_vec = vec![0, 1, 2, 3];
1980 /// some_vec.iter().count();
1981 /// &some_vec[..].iter().count();
1986 /// let some_vec = vec![0, 1, 2, 3];
1989 /// &some_vec[..].len();
1991 #[clippy::version = "1.52.0"]
1994 "replace `.iter().count()` with `.len()`"
1997 declare_clippy_lint! {
1998 /// ### What it does
1999 /// Checks for calls to [`splitn`]
2000 /// (https://doc.rust-lang.org/std/primitive.str.html#method.splitn) and
2001 /// related functions with either zero or one splits.
2003 /// ### Why is this bad?
2004 /// These calls don't actually split the value and are
2005 /// likely to be intended as a different number.
2010 /// for x in s.splitn(1, ":") {
2018 /// for x in s.splitn(2, ":") {
2022 #[clippy::version = "1.54.0"]
2023 pub SUSPICIOUS_SPLITN,
2025 "checks for `.splitn(0, ..)` and `.splitn(1, ..)`"
2028 declare_clippy_lint! {
2029 /// ### What it does
2030 /// Checks for manual implementations of `str::repeat`
2032 /// ### Why is this bad?
2033 /// These are both harder to read, as well as less performant.
2037 /// let x: String = std::iter::repeat('x').take(10).collect();
2042 /// let x: String = "x".repeat(10);
2044 #[clippy::version = "1.54.0"]
2045 pub MANUAL_STR_REPEAT,
2047 "manual implementation of `str::repeat`"
2050 declare_clippy_lint! {
2051 /// ### What it does
2052 /// Checks for usages of `str::splitn(2, _)`
2054 /// ### Why is this bad?
2055 /// `split_once` is both clearer in intent and slightly more efficient.
2059 /// let s = "key=value=add";
2060 /// let (key, value) = s.splitn(2, '=').next_tuple()?;
2061 /// let value = s.splitn(2, '=').nth(1)?;
2063 /// let mut parts = s.splitn(2, '=');
2064 /// let key = parts.next()?;
2065 /// let value = parts.next()?;
2070 /// let s = "key=value=add";
2071 /// let (key, value) = s.split_once('=')?;
2072 /// let value = s.split_once('=')?.1;
2074 /// let (key, value) = s.split_once('=')?;
2078 /// The multiple statement variant currently only detects `iter.next()?`/`iter.next().unwrap()`
2079 /// in two separate `let` statements that immediately follow the `splitn()`
2080 #[clippy::version = "1.57.0"]
2081 pub MANUAL_SPLIT_ONCE,
2083 "replace `.splitn(2, pat)` with `.split_once(pat)`"
2086 declare_clippy_lint! {
2087 /// ### What it does
2088 /// Checks for usages of `str::splitn` (or `str::rsplitn`) where using `str::split` would be the same.
2089 /// ### Why is this bad?
2090 /// The function `split` is simpler and there is no performance difference in these cases, considering
2091 /// that both functions return a lazy iterator.
2094 /// let str = "key=value=add";
2095 /// let _ = str.splitn(3, '=').next().unwrap();
2100 /// let str = "key=value=add";
2101 /// let _ = str.split('=').next().unwrap();
2103 #[clippy::version = "1.58.0"]
2104 pub NEEDLESS_SPLITN,
2106 "usages of `str::splitn` that can be replaced with `str::split`"
2109 declare_clippy_lint! {
2110 /// ### What it does
2111 /// Checks for unnecessary calls to [`ToOwned::to_owned`](https://doc.rust-lang.org/std/borrow/trait.ToOwned.html#tymethod.to_owned)
2112 /// and other `to_owned`-like functions.
2114 /// ### Why is this bad?
2115 /// The unnecessary calls result in useless allocations.
2117 /// ### Known problems
2118 /// `unnecessary_to_owned` can falsely trigger if `IntoIterator::into_iter` is applied to an
2119 /// owned copy of a resource and the resource is later used mutably. See
2120 /// [#8148](https://github.com/rust-lang/rust-clippy/issues/8148).
2124 /// let path = std::path::Path::new("x");
2125 /// foo(&path.to_string_lossy().to_string());
2126 /// fn foo(s: &str) {}
2130 /// let path = std::path::Path::new("x");
2131 /// foo(&path.to_string_lossy());
2132 /// fn foo(s: &str) {}
2134 #[clippy::version = "1.58.0"]
2135 pub UNNECESSARY_TO_OWNED,
2137 "unnecessary calls to `to_owned`-like functions"
2140 declare_clippy_lint! {
2141 /// ### What it does
2142 /// Checks for use of `.collect::<Vec<String>>().join("")` on iterators.
2144 /// ### Why is this bad?
2145 /// `.collect::<String>()` is more concise and might be more performant
2149 /// let vector = vec!["hello", "world"];
2150 /// let output = vector.iter().map(|item| item.to_uppercase()).collect::<Vec<String>>().join("");
2151 /// println!("{}", output);
2153 /// The correct use would be:
2155 /// let vector = vec!["hello", "world"];
2156 /// let output = vector.iter().map(|item| item.to_uppercase()).collect::<String>();
2157 /// println!("{}", output);
2159 /// ### Known problems
2160 /// While `.collect::<String>()` is sometimes more performant, there are cases where
2161 /// using `.collect::<String>()` over `.collect::<Vec<String>>().join("")`
2162 /// will prevent loop unrolling and will result in a negative performance impact.
2164 /// Additionally, differences have been observed between aarch64 and x86_64 assembly output,
2165 /// with aarch64 tending to producing faster assembly in more cases when using `.collect::<String>()`
2166 #[clippy::version = "1.61.0"]
2167 pub UNNECESSARY_JOIN,
2169 "using `.collect::<Vec<String>>().join(\"\")` on an iterator"
2172 declare_clippy_lint! {
2173 /// ### What it does
2174 /// Checks for no-op uses of `Option::{as_deref, as_deref_mut}`,
2175 /// for example, `Option<&T>::as_deref()` returns the same type.
2177 /// ### Why is this bad?
2178 /// Redundant code and improving readability.
2182 /// let a = Some(&1);
2183 /// let b = a.as_deref(); // goes from Option<&i32> to Option<&i32>
2188 /// let a = Some(&1);
2191 #[clippy::version = "1.57.0"]
2192 pub NEEDLESS_OPTION_AS_DEREF,
2194 "no-op use of `deref` or `deref_mut` method to `Option`."
2197 declare_clippy_lint! {
2198 /// ### What it does
2199 /// Finds usages of [`char::is_digit`]
2200 /// (https://doc.rust-lang.org/stable/std/primitive.char.html#method.is_digit) that
2201 /// can be replaced with [`is_ascii_digit`]
2202 /// (https://doc.rust-lang.org/stable/std/primitive.char.html#method.is_ascii_digit) or
2203 /// [`is_ascii_hexdigit`]
2204 /// (https://doc.rust-lang.org/stable/std/primitive.char.html#method.is_ascii_hexdigit).
2206 /// ### Why is this bad?
2207 /// `is_digit(..)` is slower and requires specifying the radix.
2211 /// let c: char = '6';
2217 /// let c: char = '6';
2218 /// c.is_ascii_digit();
2219 /// c.is_ascii_hexdigit();
2221 #[clippy::version = "1.61.0"]
2222 pub IS_DIGIT_ASCII_RADIX,
2224 "use of `char::is_digit(..)` with literal radix of 10 or 16"
2227 declare_clippy_lint! {
2229 /// ### Why is this bad?
2233 /// let x = Some(3);
2234 /// x.as_ref().take();
2238 /// let x = Some(3);
2241 #[clippy::version = "1.61.0"]
2242 pub NEEDLESS_OPTION_TAKE,
2244 "using `.as_ref().take()` on a temporary value"
2247 declare_clippy_lint! {
2248 /// ### What it does
2249 /// Checks for `replace` statements which have no effect.
2251 /// ### Why is this bad?
2252 /// It's either a mistake or confusing.
2256 /// "1234".replace("12", "12");
2257 /// "1234".replacen("12", "12", 1);
2259 #[clippy::version = "1.62.0"]
2260 pub NO_EFFECT_REPLACE,
2262 "replace with no effect"
2265 pub struct Methods {
2266 avoid_breaking_exported_api: bool,
2267 msrv: Option<RustcVersion>,
2268 allow_expect_in_tests: bool,
2269 allow_unwrap_in_tests: bool,
2275 avoid_breaking_exported_api: bool,
2276 msrv: Option<RustcVersion>,
2277 allow_expect_in_tests: bool,
2278 allow_unwrap_in_tests: bool,
2281 avoid_breaking_exported_api,
2283 allow_expect_in_tests,
2284 allow_unwrap_in_tests,
2289 impl_lint_pass!(Methods => [
2292 SHOULD_IMPLEMENT_TRAIT,
2293 WRONG_SELF_CONVENTION,
2295 UNWRAP_OR_ELSE_DEFAULT,
2297 RESULT_MAP_OR_INTO_OPTION,
2299 BIND_INSTEAD_OF_MAP,
2308 ITER_OVEREAGER_CLONED,
2309 CLONED_INSTEAD_OF_COPIED,
2311 INEFFICIENT_TO_STRING,
2313 SINGLE_CHAR_PATTERN,
2314 SINGLE_CHAR_ADD_STR,
2318 FILTER_MAP_IDENTITY,
2326 ITERATOR_STEP_BY_ZERO,
2335 STRING_EXTEND_CHARS,
2336 ITER_CLONED_COLLECT,
2340 UNNECESSARY_FILTER_MAP,
2341 UNNECESSARY_FIND_MAP,
2344 UNINIT_ASSUMED_INIT,
2345 MANUAL_SATURATING_ARITHMETIC,
2348 OPTION_AS_REF_DEREF,
2349 UNNECESSARY_LAZY_EVALUATIONS,
2350 MAP_COLLECT_RESULT_UNIT,
2351 FROM_ITER_INSTEAD_OF_COLLECT,
2359 UNNECESSARY_TO_OWNED,
2362 NEEDLESS_OPTION_AS_DEREF,
2363 IS_DIGIT_ASCII_RADIX,
2364 NEEDLESS_OPTION_TAKE,
2368 /// Extracts a method call name, args, and `Span` of the method name.
2369 fn method_call<'tcx>(recv: &'tcx hir::Expr<'tcx>) -> Option<(&'tcx str, &'tcx [hir::Expr<'tcx>], Span)> {
2370 if let ExprKind::MethodCall(path, args, _) = recv.kind {
2371 if !args.iter().any(|e| e.span.from_expansion()) {
2372 let name = path.ident.name.as_str();
2373 return Some((name, args, path.ident.span));
2379 impl<'tcx> LateLintPass<'tcx> for Methods {
2380 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) {
2381 if expr.span.from_expansion() {
2385 self.check_methods(cx, expr);
2388 hir::ExprKind::Call(func, args) => {
2389 from_iter_instead_of_collect::check(cx, expr, args, func);
2391 hir::ExprKind::MethodCall(method_call, args, _) => {
2392 let method_span = method_call.ident.span;
2393 or_fun_call::check(cx, expr, method_span, method_call.ident.as_str(), args);
2394 expect_fun_call::check(cx, expr, method_span, method_call.ident.as_str(), args);
2395 clone_on_copy::check(cx, expr, method_call.ident.name, args);
2396 clone_on_ref_ptr::check(cx, expr, method_call.ident.name, args);
2397 inefficient_to_string::check(cx, expr, method_call.ident.name, args);
2398 single_char_add_str::check(cx, expr, args);
2399 into_iter_on_ref::check(cx, expr, method_span, method_call.ident.name, args);
2400 single_char_pattern::check(cx, expr, method_call.ident.name, args);
2401 unnecessary_to_owned::check(cx, expr, method_call.ident.name, args, self.msrv);
2403 hir::ExprKind::Binary(op, lhs, rhs) if op.node == hir::BinOpKind::Eq || op.node == hir::BinOpKind::Ne => {
2404 let mut info = BinaryExprInfo {
2408 eq: op.node == hir::BinOpKind::Eq,
2410 lint_binary_expr_with_method_call(cx, &mut info);
2416 #[allow(clippy::too_many_lines)]
2417 fn check_impl_item(&mut self, cx: &LateContext<'tcx>, impl_item: &'tcx hir::ImplItem<'_>) {
2418 if in_external_macro(cx.sess(), impl_item.span) {
2421 let name = impl_item.ident.name.as_str();
2422 let parent = cx.tcx.hir().get_parent_item(impl_item.hir_id());
2423 let item = cx.tcx.hir().expect_item(parent);
2424 let self_ty = cx.tcx.type_of(item.def_id);
2426 let implements_trait = matches!(item.kind, hir::ItemKind::Impl(hir::Impl { of_trait: Some(_), .. }));
2428 if let hir::ImplItemKind::Fn(ref sig, id) = impl_item.kind;
2429 if let Some(first_arg) = iter_input_pats(sig.decl, cx.tcx.hir().body(id)).next();
2431 let method_sig = cx.tcx.fn_sig(impl_item.def_id);
2432 let method_sig = cx.tcx.erase_late_bound_regions(method_sig);
2434 let first_arg_ty = method_sig.inputs().iter().next();
2436 // check conventions w.r.t. conversion method names and predicates
2437 if let Some(first_arg_ty) = first_arg_ty;
2440 // if this impl block implements a trait, lint in trait definition instead
2441 if !implements_trait && cx.access_levels.is_exported(impl_item.def_id) {
2442 // check missing trait implementations
2443 for method_config in &TRAIT_METHODS {
2444 if name == method_config.method_name &&
2445 sig.decl.inputs.len() == method_config.param_count &&
2446 method_config.output_type.matches(&sig.decl.output) &&
2447 method_config.self_kind.matches(cx, self_ty, *first_arg_ty) &&
2448 fn_header_equals(method_config.fn_header, sig.header) &&
2449 method_config.lifetime_param_cond(impl_item)
2453 SHOULD_IMPLEMENT_TRAIT,
2456 "method `{}` can be confused for the standard trait method `{}::{}`",
2457 method_config.method_name,
2458 method_config.trait_name,
2459 method_config.method_name
2463 "consider implementing the trait `{}` or choosing a less ambiguous method name",
2464 method_config.trait_name
2471 if sig.decl.implicit_self.has_implicit_self()
2472 && !(self.avoid_breaking_exported_api
2473 && cx.access_levels.is_exported(impl_item.def_id))
2475 wrong_self_convention::check(
2488 // if this impl block implements a trait, lint in trait definition instead
2489 if implements_trait {
2493 if let hir::ImplItemKind::Fn(_, _) = impl_item.kind {
2494 let ret_ty = return_ty(cx, impl_item.hir_id());
2496 // walk the return type and check for Self (this does not check associated types)
2497 if let Some(self_adt) = self_ty.ty_adt_def() {
2498 if contains_adt_constructor(ret_ty, self_adt) {
2501 } else if contains_ty(ret_ty, self_ty) {
2505 // if return type is impl trait, check the associated types
2506 if let ty::Opaque(def_id, _) = *ret_ty.kind() {
2507 // one of the associated types must be Self
2508 for &(predicate, _span) in cx.tcx.explicit_item_bounds(def_id) {
2509 if let ty::PredicateKind::Projection(projection_predicate) = predicate.kind().skip_binder() {
2510 let assoc_ty = match projection_predicate.term {
2511 ty::Term::Ty(ty) => ty,
2512 ty::Term::Const(_c) => continue,
2514 // walk the associated type and check for Self
2515 if let Some(self_adt) = self_ty.ty_adt_def() {
2516 if contains_adt_constructor(assoc_ty, self_adt) {
2519 } else if contains_ty(assoc_ty, self_ty) {
2526 if name == "new" && ret_ty != self_ty {
2531 "methods called `new` usually return `Self`",
2537 fn check_trait_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx TraitItem<'_>) {
2538 if in_external_macro(cx.tcx.sess, item.span) {
2543 if let TraitItemKind::Fn(ref sig, _) = item.kind;
2544 if sig.decl.implicit_self.has_implicit_self();
2545 if let Some(first_arg_ty) = sig.decl.inputs.iter().next();
2548 let first_arg_span = first_arg_ty.span;
2549 let first_arg_ty = hir_ty_to_ty(cx.tcx, first_arg_ty);
2550 let self_ty = TraitRef::identity(cx.tcx, item.def_id.to_def_id()).self_ty().skip_binder();
2551 wrong_self_convention::check(
2553 item.ident.name.as_str(),
2564 if item.ident.name == sym::new;
2565 if let TraitItemKind::Fn(_, _) = item.kind;
2566 let ret_ty = return_ty(cx, item.hir_id());
2567 let self_ty = TraitRef::identity(cx.tcx, item.def_id.to_def_id()).self_ty().skip_binder();
2568 if !contains_ty(ret_ty, self_ty);
2575 "methods called `new` usually return `Self`",
2581 extract_msrv_attr!(LateContext);
2585 #[allow(clippy::too_many_lines)]
2586 fn check_methods<'tcx>(&self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
2587 if let Some((name, [recv, args @ ..], span)) = method_call(expr) {
2588 match (name, args) {
2589 ("add" | "offset" | "sub" | "wrapping_offset" | "wrapping_add" | "wrapping_sub", [_arg]) => {
2590 zst_offset::check(cx, expr, recv);
2592 ("and_then", [arg]) => {
2593 let biom_option_linted = bind_instead_of_map::OptionAndThenSome::check(cx, expr, recv, arg);
2594 let biom_result_linted = bind_instead_of_map::ResultAndThenOk::check(cx, expr, recv, arg);
2595 if !biom_option_linted && !biom_result_linted {
2596 unnecessary_lazy_eval::check(cx, expr, recv, arg, "and");
2599 ("as_deref" | "as_deref_mut", []) => {
2600 needless_option_as_deref::check(cx, expr, recv, name);
2602 ("as_mut", []) => useless_asref::check(cx, expr, "as_mut", recv),
2603 ("as_ref", []) => useless_asref::check(cx, expr, "as_ref", recv),
2604 ("assume_init", []) => uninit_assumed_init::check(cx, expr, recv),
2605 ("cloned", []) => cloned_instead_of_copied::check(cx, expr, recv, span, self.msrv),
2606 ("collect", []) => match method_call(recv) {
2607 Some((name @ ("cloned" | "copied"), [recv2], _)) => {
2608 iter_cloned_collect::check(cx, name, expr, recv2);
2610 Some(("map", [m_recv, m_arg], _)) => {
2611 map_collect_result_unit::check(cx, expr, m_recv, m_arg, recv);
2613 Some(("take", [take_self_arg, take_arg], _)) => {
2614 if meets_msrv(self.msrv, msrvs::STR_REPEAT) {
2615 manual_str_repeat::check(cx, expr, recv, take_self_arg, take_arg);
2620 ("count", []) => match method_call(recv) {
2621 Some(("cloned", [recv2], _)) => iter_overeager_cloned::check(cx, expr, recv, recv2, true, false),
2622 Some((name2 @ ("into_iter" | "iter" | "iter_mut"), [recv2], _)) => {
2623 iter_count::check(cx, expr, recv2, name2);
2625 Some(("map", [_, arg], _)) => suspicious_map::check(cx, expr, recv, arg),
2628 ("drain", [arg]) => {
2629 iter_with_drain::check(cx, expr, recv, span, arg);
2631 ("expect", [_]) => match method_call(recv) {
2632 Some(("ok", [recv], _)) => ok_expect::check(cx, expr, recv),
2633 Some(("err", [recv], err_span)) => err_expect::check(cx, expr, recv, self.msrv, span, err_span),
2634 _ => expect_used::check(cx, expr, recv, self.allow_expect_in_tests),
2636 ("extend", [arg]) => {
2637 string_extend_chars::check(cx, expr, recv, arg);
2638 extend_with_drain::check(cx, expr, recv, arg);
2640 ("filter_map", [arg]) => {
2641 unnecessary_filter_map::check(cx, expr, arg, name);
2642 filter_map_identity::check(cx, expr, arg, span);
2644 ("find_map", [arg]) => {
2645 unnecessary_filter_map::check(cx, expr, arg, name);
2647 ("flat_map", [arg]) => {
2648 flat_map_identity::check(cx, expr, arg, span);
2649 flat_map_option::check(cx, expr, arg, span);
2651 ("flatten", []) => match method_call(recv) {
2652 Some(("map", [recv, map_arg], map_span)) => map_flatten::check(cx, expr, recv, map_arg, map_span),
2653 Some(("cloned", [recv2], _)) => iter_overeager_cloned::check(cx, expr, recv, recv2, false, true),
2656 ("fold", [init, acc]) => unnecessary_fold::check(cx, expr, init, acc, span),
2657 ("for_each", [_]) => {
2658 if let Some(("inspect", [_, _], span2)) = method_call(recv) {
2659 inspect_for_each::check(cx, expr, span2);
2662 ("get", [arg]) => get_last_with_len::check(cx, expr, recv, arg),
2663 ("get_or_insert_with", [arg]) => unnecessary_lazy_eval::check(cx, expr, recv, arg, "get_or_insert"),
2664 ("is_file", []) => filetype_is_file::check(cx, expr, recv),
2665 ("is_digit", [radix]) => is_digit_ascii_radix::check(cx, expr, recv, radix, self.msrv),
2666 ("is_none", []) => check_is_some_is_none(cx, expr, recv, false),
2667 ("is_some", []) => check_is_some_is_none(cx, expr, recv, true),
2668 ("join", [join_arg]) => {
2669 if let Some(("collect", _, span)) = method_call(recv) {
2670 unnecessary_join::check(cx, expr, recv, join_arg, span);
2673 ("last", []) | ("skip", [_]) => {
2674 if let Some((name2, [recv2, args2 @ ..], _span2)) = method_call(recv) {
2675 if let ("cloned", []) = (name2, args2) {
2676 iter_overeager_cloned::check(cx, expr, recv, recv2, false, false);
2680 (name @ ("map" | "map_err"), [m_arg]) => {
2681 if let Some((name, [recv2, args @ ..], span2)) = method_call(recv) {
2682 match (name, args) {
2683 ("as_mut", []) => option_as_ref_deref::check(cx, expr, recv2, m_arg, true, self.msrv),
2684 ("as_ref", []) => option_as_ref_deref::check(cx, expr, recv2, m_arg, false, self.msrv),
2685 ("filter", [f_arg]) => {
2686 filter_map::check(cx, expr, recv2, f_arg, span2, recv, m_arg, span, false);
2688 ("find", [f_arg]) => {
2689 filter_map::check(cx, expr, recv2, f_arg, span2, recv, m_arg, span, true);
2694 map_identity::check(cx, expr, recv, m_arg, name, span);
2696 ("map_or", [def, map]) => option_map_or_none::check(cx, expr, recv, def, map),
2698 if let Some((name2, [recv2, args2 @ ..], _)) = method_call(recv) {
2699 match (name2, args2) {
2700 ("cloned", []) => iter_overeager_cloned::check(cx, expr, recv, recv2, false, false),
2701 ("filter", [arg]) => filter_next::check(cx, expr, recv2, arg),
2702 ("filter_map", [arg]) => filter_map_next::check(cx, expr, recv2, arg, self.msrv),
2703 ("iter", []) => iter_next_slice::check(cx, expr, recv2),
2704 ("skip", [arg]) => iter_skip_next::check(cx, expr, recv2, arg),
2705 ("skip_while", [_]) => skip_while_next::check(cx, expr),
2710 ("nth", [n_arg]) => match method_call(recv) {
2711 Some(("bytes", [recv2], _)) => bytes_nth::check(cx, expr, recv2, n_arg),
2712 Some(("cloned", [recv2], _)) => iter_overeager_cloned::check(cx, expr, recv, recv2, false, false),
2713 Some(("iter", [recv2], _)) => iter_nth::check(cx, expr, recv2, recv, n_arg, false),
2714 Some(("iter_mut", [recv2], _)) => iter_nth::check(cx, expr, recv2, recv, n_arg, true),
2715 _ => iter_nth_zero::check(cx, expr, recv, n_arg),
2717 ("ok_or_else", [arg]) => unnecessary_lazy_eval::check(cx, expr, recv, arg, "ok_or"),
2718 ("or_else", [arg]) => {
2719 if !bind_instead_of_map::ResultOrElseErrInfo::check(cx, expr, recv, arg) {
2720 unnecessary_lazy_eval::check(cx, expr, recv, arg, "or");
2723 ("splitn" | "rsplitn", [count_arg, pat_arg]) => {
2724 if let Some((Constant::Int(count), _)) = constant(cx, cx.typeck_results(), count_arg) {
2725 suspicious_splitn::check(cx, name, expr, recv, count);
2726 str_splitn::check(cx, name, expr, recv, pat_arg, count, self.msrv);
2729 ("splitn_mut" | "rsplitn_mut", [count_arg, _]) => {
2730 if let Some((Constant::Int(count), _)) = constant(cx, cx.typeck_results(), count_arg) {
2731 suspicious_splitn::check(cx, name, expr, recv, count);
2734 ("step_by", [arg]) => iterator_step_by_zero::check(cx, expr, arg),
2735 ("take", [_arg]) => {
2736 if let Some((name2, [recv2, args2 @ ..], _span2)) = method_call(recv) {
2737 if let ("cloned", []) = (name2, args2) {
2738 iter_overeager_cloned::check(cx, expr, recv, recv2, false, false);
2742 ("take", []) => needless_option_take::check(cx, expr, recv),
2743 ("to_os_string" | "to_owned" | "to_path_buf" | "to_vec", []) => {
2744 implicit_clone::check(cx, name, expr, recv);
2747 match method_call(recv) {
2748 Some(("get", [recv, get_arg], _)) => {
2749 get_unwrap::check(cx, expr, recv, get_arg, false);
2751 Some(("get_mut", [recv, get_arg], _)) => {
2752 get_unwrap::check(cx, expr, recv, get_arg, true);
2754 Some(("or", [recv, or_arg], or_span)) => {
2755 or_then_unwrap::check(cx, expr, recv, or_arg, or_span);
2759 unwrap_used::check(cx, expr, recv, self.allow_unwrap_in_tests);
2761 ("unwrap_or", [u_arg]) => match method_call(recv) {
2762 Some((arith @ ("checked_add" | "checked_sub" | "checked_mul"), [lhs, rhs], _)) => {
2763 manual_saturating_arithmetic::check(cx, expr, lhs, rhs, u_arg, &arith["checked_".len()..]);
2765 Some(("map", [m_recv, m_arg], span)) => {
2766 option_map_unwrap_or::check(cx, expr, m_recv, m_arg, recv, u_arg, span);
2770 ("unwrap_or_else", [u_arg]) => match method_call(recv) {
2771 Some(("map", [recv, map_arg], _))
2772 if map_unwrap_or::check(cx, expr, recv, map_arg, u_arg, self.msrv) => {},
2774 unwrap_or_else_default::check(cx, expr, recv, u_arg);
2775 unnecessary_lazy_eval::check(cx, expr, recv, u_arg, "unwrap_or");
2778 ("replace" | "replacen", [arg1, arg2] | [arg1, arg2, _]) => {
2779 no_effect_replace::check(cx, expr, arg1, arg2);
2787 fn check_is_some_is_none(cx: &LateContext<'_>, expr: &Expr<'_>, recv: &Expr<'_>, is_some: bool) {
2788 if let Some((name @ ("find" | "position" | "rposition"), [f_recv, arg], span)) = method_call(recv) {
2789 search_is_some::check(cx, expr, name, is_some, f_recv, arg, recv, span);
2793 /// Used for `lint_binary_expr_with_method_call`.
2794 #[derive(Copy, Clone)]
2795 struct BinaryExprInfo<'a> {
2796 expr: &'a hir::Expr<'a>,
2797 chain: &'a hir::Expr<'a>,
2798 other: &'a hir::Expr<'a>,
2802 /// Checks for the `CHARS_NEXT_CMP` and `CHARS_LAST_CMP` lints.
2803 fn lint_binary_expr_with_method_call(cx: &LateContext<'_>, info: &mut BinaryExprInfo<'_>) {
2804 macro_rules! lint_with_both_lhs_and_rhs {
2805 ($func:expr, $cx:expr, $info:ident) => {
2806 if !$func($cx, $info) {
2807 ::std::mem::swap(&mut $info.chain, &mut $info.other);
2808 if $func($cx, $info) {
2815 lint_with_both_lhs_and_rhs!(chars_next_cmp::check, cx, info);
2816 lint_with_both_lhs_and_rhs!(chars_last_cmp::check, cx, info);
2817 lint_with_both_lhs_and_rhs!(chars_next_cmp_with_unwrap::check, cx, info);
2818 lint_with_both_lhs_and_rhs!(chars_last_cmp_with_unwrap::check, cx, info);
2821 const FN_HEADER: hir::FnHeader = hir::FnHeader {
2822 unsafety: hir::Unsafety::Normal,
2823 constness: hir::Constness::NotConst,
2824 asyncness: hir::IsAsync::NotAsync,
2825 abi: rustc_target::spec::abi::Abi::Rust,
2828 struct ShouldImplTraitCase {
2829 trait_name: &'static str,
2830 method_name: &'static str,
2832 fn_header: hir::FnHeader,
2833 // implicit self kind expected (none, self, &self, ...)
2834 self_kind: SelfKind,
2835 // checks against the output type
2836 output_type: OutType,
2837 // certain methods with explicit lifetimes can't implement the equivalent trait method
2838 lint_explicit_lifetime: bool,
2840 impl ShouldImplTraitCase {
2842 trait_name: &'static str,
2843 method_name: &'static str,
2845 fn_header: hir::FnHeader,
2846 self_kind: SelfKind,
2847 output_type: OutType,
2848 lint_explicit_lifetime: bool,
2849 ) -> ShouldImplTraitCase {
2850 ShouldImplTraitCase {
2857 lint_explicit_lifetime,
2861 fn lifetime_param_cond(&self, impl_item: &hir::ImplItem<'_>) -> bool {
2862 self.lint_explicit_lifetime
2863 || !impl_item.generics.params.iter().any(|p| {
2866 hir::GenericParamKind::Lifetime {
2867 kind: hir::LifetimeParamKind::Explicit
2875 const TRAIT_METHODS: [ShouldImplTraitCase; 30] = [
2876 ShouldImplTraitCase::new("std::ops::Add", "add", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
2877 ShouldImplTraitCase::new("std::convert::AsMut", "as_mut", 1, FN_HEADER, SelfKind::RefMut, OutType::Ref, true),
2878 ShouldImplTraitCase::new("std::convert::AsRef", "as_ref", 1, FN_HEADER, SelfKind::Ref, OutType::Ref, true),
2879 ShouldImplTraitCase::new("std::ops::BitAnd", "bitand", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
2880 ShouldImplTraitCase::new("std::ops::BitOr", "bitor", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
2881 ShouldImplTraitCase::new("std::ops::BitXor", "bitxor", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
2882 ShouldImplTraitCase::new("std::borrow::Borrow", "borrow", 1, FN_HEADER, SelfKind::Ref, OutType::Ref, true),
2883 ShouldImplTraitCase::new("std::borrow::BorrowMut", "borrow_mut", 1, FN_HEADER, SelfKind::RefMut, OutType::Ref, true),
2884 ShouldImplTraitCase::new("std::clone::Clone", "clone", 1, FN_HEADER, SelfKind::Ref, OutType::Any, true),
2885 ShouldImplTraitCase::new("std::cmp::Ord", "cmp", 2, FN_HEADER, SelfKind::Ref, OutType::Any, true),
2886 // FIXME: default doesn't work
2887 ShouldImplTraitCase::new("std::default::Default", "default", 0, FN_HEADER, SelfKind::No, OutType::Any, true),
2888 ShouldImplTraitCase::new("std::ops::Deref", "deref", 1, FN_HEADER, SelfKind::Ref, OutType::Ref, true),
2889 ShouldImplTraitCase::new("std::ops::DerefMut", "deref_mut", 1, FN_HEADER, SelfKind::RefMut, OutType::Ref, true),
2890 ShouldImplTraitCase::new("std::ops::Div", "div", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
2891 ShouldImplTraitCase::new("std::ops::Drop", "drop", 1, FN_HEADER, SelfKind::RefMut, OutType::Unit, true),
2892 ShouldImplTraitCase::new("std::cmp::PartialEq", "eq", 2, FN_HEADER, SelfKind::Ref, OutType::Bool, true),
2893 ShouldImplTraitCase::new("std::iter::FromIterator", "from_iter", 1, FN_HEADER, SelfKind::No, OutType::Any, true),
2894 ShouldImplTraitCase::new("std::str::FromStr", "from_str", 1, FN_HEADER, SelfKind::No, OutType::Any, true),
2895 ShouldImplTraitCase::new("std::hash::Hash", "hash", 2, FN_HEADER, SelfKind::Ref, OutType::Unit, true),
2896 ShouldImplTraitCase::new("std::ops::Index", "index", 2, FN_HEADER, SelfKind::Ref, OutType::Ref, true),
2897 ShouldImplTraitCase::new("std::ops::IndexMut", "index_mut", 2, FN_HEADER, SelfKind::RefMut, OutType::Ref, true),
2898 ShouldImplTraitCase::new("std::iter::IntoIterator", "into_iter", 1, FN_HEADER, SelfKind::Value, OutType::Any, true),
2899 ShouldImplTraitCase::new("std::ops::Mul", "mul", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
2900 ShouldImplTraitCase::new("std::ops::Neg", "neg", 1, FN_HEADER, SelfKind::Value, OutType::Any, true),
2901 ShouldImplTraitCase::new("std::iter::Iterator", "next", 1, FN_HEADER, SelfKind::RefMut, OutType::Any, false),
2902 ShouldImplTraitCase::new("std::ops::Not", "not", 1, FN_HEADER, SelfKind::Value, OutType::Any, true),
2903 ShouldImplTraitCase::new("std::ops::Rem", "rem", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
2904 ShouldImplTraitCase::new("std::ops::Shl", "shl", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
2905 ShouldImplTraitCase::new("std::ops::Shr", "shr", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
2906 ShouldImplTraitCase::new("std::ops::Sub", "sub", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
2909 #[derive(Clone, Copy, PartialEq, Eq, Debug)]
2918 fn matches<'a>(self, cx: &LateContext<'a>, parent_ty: Ty<'a>, ty: Ty<'a>) -> bool {
2919 fn matches_value<'a>(cx: &LateContext<'a>, parent_ty: Ty<'a>, ty: Ty<'a>) -> bool {
2920 if ty == parent_ty {
2922 } else if ty.is_box() {
2923 ty.boxed_ty() == parent_ty
2924 } else if is_type_diagnostic_item(cx, ty, sym::Rc) || is_type_diagnostic_item(cx, ty, sym::Arc) {
2925 if let ty::Adt(_, substs) = ty.kind() {
2926 substs.types().next().map_or(false, |t| t == parent_ty)
2935 fn matches_ref<'a>(cx: &LateContext<'a>, mutability: hir::Mutability, parent_ty: Ty<'a>, ty: Ty<'a>) -> bool {
2936 if let ty::Ref(_, t, m) = *ty.kind() {
2937 return m == mutability && t == parent_ty;
2940 let trait_path = match mutability {
2941 hir::Mutability::Not => &paths::ASREF_TRAIT,
2942 hir::Mutability::Mut => &paths::ASMUT_TRAIT,
2945 let trait_def_id = match get_trait_def_id(cx, trait_path) {
2947 None => return false,
2949 implements_trait(cx, ty, trait_def_id, &[parent_ty.into()])
2952 fn matches_none<'a>(cx: &LateContext<'a>, parent_ty: Ty<'a>, ty: Ty<'a>) -> bool {
2953 !matches_value(cx, parent_ty, ty)
2954 && !matches_ref(cx, hir::Mutability::Not, parent_ty, ty)
2955 && !matches_ref(cx, hir::Mutability::Mut, parent_ty, ty)
2959 Self::Value => matches_value(cx, parent_ty, ty),
2960 Self::Ref => matches_ref(cx, hir::Mutability::Not, parent_ty, ty) || ty == parent_ty && is_copy(cx, ty),
2961 Self::RefMut => matches_ref(cx, hir::Mutability::Mut, parent_ty, ty),
2962 Self::No => matches_none(cx, parent_ty, ty),
2967 fn description(self) -> &'static str {
2969 Self::Value => "`self` by value",
2970 Self::Ref => "`self` by reference",
2971 Self::RefMut => "`self` by mutable reference",
2972 Self::No => "no `self`",
2977 #[derive(Clone, Copy)]
2986 fn matches(self, ty: &hir::FnRetTy<'_>) -> bool {
2987 let is_unit = |ty: &hir::Ty<'_>| matches!(ty.kind, hir::TyKind::Tup(&[]));
2989 (Self::Unit, &hir::FnRetTy::DefaultReturn(_)) => true,
2990 (Self::Unit, &hir::FnRetTy::Return(ty)) if is_unit(ty) => true,
2991 (Self::Bool, &hir::FnRetTy::Return(ty)) if is_bool(ty) => true,
2992 (Self::Any, &hir::FnRetTy::Return(ty)) if !is_unit(ty) => true,
2993 (Self::Ref, &hir::FnRetTy::Return(ty)) => matches!(ty.kind, hir::TyKind::Rptr(_, _)),
2999 fn is_bool(ty: &hir::Ty<'_>) -> bool {
3000 if let hir::TyKind::Path(QPath::Resolved(_, path)) = ty.kind {
3001 matches!(path.res, Res::PrimTy(PrimTy::Bool))
3007 fn fn_header_equals(expected: hir::FnHeader, actual: hir::FnHeader) -> bool {
3008 expected.constness == actual.constness
3009 && expected.unsafety == actual.unsafety
3010 && expected.asyncness == actual.asyncness