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_on_single_or_empty_collections;
37 mod iter_overeager_cloned;
40 mod iterator_step_by_zero;
41 mod manual_saturating_arithmetic;
42 mod manual_str_repeat;
43 mod map_collect_result_unit;
47 mod needless_option_as_deref;
48 mod needless_option_take;
49 mod no_effect_replace;
50 mod obfuscated_if_else;
52 mod option_as_ref_deref;
53 mod option_map_or_none;
54 mod option_map_unwrap_or;
58 mod single_char_add_str;
59 mod single_char_insert_string;
60 mod single_char_pattern;
61 mod single_char_push_string;
64 mod string_extend_chars;
66 mod suspicious_splitn;
67 mod uninit_assumed_init;
68 mod unnecessary_filter_map;
70 mod unnecessary_iter_cloned;
72 mod unnecessary_lazy_eval;
73 mod unnecessary_to_owned;
74 mod unwrap_or_else_default;
78 mod wrong_self_convention;
81 use bind_instead_of_map::BindInsteadOfMap;
82 use clippy_utils::consts::{constant, Constant};
83 use clippy_utils::diagnostics::{span_lint, span_lint_and_help};
84 use clippy_utils::ty::{contains_adt_constructor, contains_ty, implements_trait, is_copy, is_type_diagnostic_item};
85 use clippy_utils::{contains_return, get_trait_def_id, iter_input_pats, meets_msrv, msrvs, paths, return_ty};
86 use if_chain::if_chain;
88 use rustc_hir::def::Res;
89 use rustc_hir::{Expr, ExprKind, PrimTy, QPath, TraitItem, TraitItemKind};
90 use rustc_lint::{LateContext, LateLintPass, LintContext};
91 use rustc_middle::lint::in_external_macro;
92 use rustc_middle::ty::{self, TraitRef, Ty};
93 use rustc_semver::RustcVersion;
94 use rustc_session::{declare_tool_lint, impl_lint_pass};
95 use rustc_span::{sym, Span};
96 use rustc_typeck::hir_ty_to_ty;
98 declare_clippy_lint! {
100 /// Checks for usages of `cloned()` on an `Iterator` or `Option` where
101 /// `copied()` could be used instead.
103 /// ### Why is this bad?
104 /// `copied()` is better because it guarantees that the type being cloned
105 /// implements `Copy`.
109 /// [1, 2, 3].iter().cloned();
113 /// [1, 2, 3].iter().copied();
115 #[clippy::version = "1.53.0"]
116 pub CLONED_INSTEAD_OF_COPIED,
118 "used `cloned` where `copied` could be used instead"
121 declare_clippy_lint! {
123 /// Checks for usage of `_.cloned().<func>()` where call to `.cloned()` can be postponed.
125 /// ### Why is this bad?
126 /// It's often inefficient to clone all elements of an iterator, when eventually, only some
127 /// of them will be consumed.
129 /// ### Known Problems
130 /// This `lint` removes the side of effect of cloning items in the iterator.
131 /// A code that relies on that side-effect could fail.
135 /// # let vec = vec!["string".to_string()];
136 /// vec.iter().cloned().take(10);
137 /// vec.iter().cloned().last();
142 /// # let vec = vec!["string".to_string()];
143 /// vec.iter().take(10).cloned();
144 /// vec.iter().last().cloned();
146 #[clippy::version = "1.60.0"]
147 pub ITER_OVEREAGER_CLONED,
149 "using `cloned()` early with `Iterator::iter()` can lead to some performance inefficiencies"
152 declare_clippy_lint! {
154 /// Checks for usages of `Iterator::flat_map()` where `filter_map()` could be
157 /// ### Why is this bad?
158 /// When applicable, `filter_map()` is more clear since it shows that
159 /// `Option` is used to produce 0 or 1 items.
163 /// let nums: Vec<i32> = ["1", "2", "whee!"].iter().flat_map(|x| x.parse().ok()).collect();
167 /// let nums: Vec<i32> = ["1", "2", "whee!"].iter().filter_map(|x| x.parse().ok()).collect();
169 #[clippy::version = "1.53.0"]
172 "used `flat_map` where `filter_map` could be used instead"
175 declare_clippy_lint! {
177 /// Checks for `.unwrap()` calls on `Option`s and on `Result`s.
179 /// ### Why is this bad?
180 /// It is better to handle the `None` or `Err` case,
181 /// or at least call `.expect(_)` with a more helpful message. Still, for a lot of
182 /// quick-and-dirty code, `unwrap` is a good choice, which is why this lint is
183 /// `Allow` by default.
185 /// `result.unwrap()` will let the thread panic on `Err` values.
186 /// Normally, you want to implement more sophisticated error handling,
187 /// and propagate errors upwards with `?` operator.
189 /// Even if you want to panic on errors, not all `Error`s implement good
190 /// messages on display. Therefore, it may be beneficial to look at the places
191 /// where they may get displayed. Activate this lint to do just that.
195 /// # let option = Some(1);
196 /// # let result: Result<usize, ()> = Ok(1);
203 /// # let option = Some(1);
204 /// # let result: Result<usize, ()> = Ok(1);
205 /// option.expect("more helpful message");
206 /// result.expect("more helpful message");
209 /// If [expect_used](#expect_used) is enabled, instead:
211 /// # let option = Some(1);
212 /// # let result: Result<usize, ()> = Ok(1);
219 #[clippy::version = "1.45.0"]
222 "using `.unwrap()` on `Result` or `Option`, which should at least get a better message using `expect()`"
225 declare_clippy_lint! {
227 /// Checks for `.expect()` calls on `Option`s and `Result`s.
229 /// ### Why is this bad?
230 /// Usually it is better to handle the `None` or `Err` case.
231 /// Still, for a lot of quick-and-dirty code, `expect` is a good choice, which is why
232 /// this lint is `Allow` by default.
234 /// `result.expect()` will let the thread panic on `Err`
235 /// values. Normally, you want to implement more sophisticated error handling,
236 /// and propagate errors upwards with `?` operator.
240 /// # let option = Some(1);
241 /// # let result: Result<usize, ()> = Ok(1);
242 /// option.expect("one");
243 /// result.expect("one");
248 /// # let option = Some(1);
249 /// # let result: Result<usize, ()> = Ok(1);
256 #[clippy::version = "1.45.0"]
259 "using `.expect()` on `Result` or `Option`, which might be better handled"
262 declare_clippy_lint! {
264 /// Checks for methods that should live in a trait
265 /// implementation of a `std` trait (see [llogiq's blog
266 /// post](http://llogiq.github.io/2015/07/30/traits.html) for further
267 /// information) instead of an inherent implementation.
269 /// ### Why is this bad?
270 /// Implementing the traits improve ergonomics for users of
271 /// the code, often with very little cost. Also people seeing a `mul(...)`
273 /// may expect `*` to work equally, so you should have good reason to disappoint
280 /// fn add(&self, other: &X) -> X {
286 #[clippy::version = "pre 1.29.0"]
287 pub SHOULD_IMPLEMENT_TRAIT,
289 "defining a method that should be implementing a std trait"
292 declare_clippy_lint! {
294 /// Checks for methods with certain name prefixes and which
295 /// doesn't match how self is taken. The actual rules are:
297 /// |Prefix |Postfix |`self` taken | `self` type |
298 /// |-------|------------|-------------------------------|--------------|
299 /// |`as_` | none |`&self` or `&mut self` | any |
300 /// |`from_`| none | none | any |
301 /// |`into_`| none |`self` | any |
302 /// |`is_` | none |`&mut self` or `&self` or none | any |
303 /// |`to_` | `_mut` |`&mut self` | any |
304 /// |`to_` | not `_mut` |`self` | `Copy` |
305 /// |`to_` | not `_mut` |`&self` | not `Copy` |
307 /// Note: Clippy doesn't trigger methods with `to_` prefix in:
308 /// - Traits definition.
309 /// Clippy can not tell if a type that implements a trait is `Copy` or not.
310 /// - Traits implementation, when `&self` is taken.
311 /// The method signature is controlled by the trait and often `&self` is required for all types that implement the trait
312 /// (see e.g. the `std::string::ToString` trait).
314 /// Clippy allows `Pin<&Self>` and `Pin<&mut Self>` if `&self` and `&mut self` is required.
316 /// Please find more info here:
317 /// https://rust-lang.github.io/api-guidelines/naming.html#ad-hoc-conversions-follow-as_-to_-into_-conventions-c-conv
319 /// ### Why is this bad?
320 /// Consistency breeds readability. If you follow the
321 /// conventions, your users won't be surprised that they, e.g., need to supply a
322 /// mutable reference to a `as_..` function.
328 /// fn as_str(self) -> &'static str {
334 #[clippy::version = "pre 1.29.0"]
335 pub WRONG_SELF_CONVENTION,
337 "defining a method named with an established prefix (like \"into_\") that takes `self` with the wrong convention"
340 declare_clippy_lint! {
342 /// Checks for usage of `ok().expect(..)`.
344 /// ### Why is this bad?
345 /// Because you usually call `expect()` on the `Result`
346 /// directly to get a better error message.
348 /// ### Known problems
349 /// The error type needs to implement `Debug`
353 /// # let x = Ok::<_, ()>(());
354 /// x.ok().expect("why did I do this again?");
359 /// # let x = Ok::<_, ()>(());
360 /// x.expect("why did I do this again?");
362 #[clippy::version = "pre 1.29.0"]
365 "using `ok().expect()`, which gives worse error messages than calling `expect` directly on the Result"
368 declare_clippy_lint! {
370 /// Checks for `.err().expect()` calls on the `Result` type.
372 /// ### Why is this bad?
373 /// `.expect_err()` can be called directly to avoid the extra type conversion from `err()`.
377 /// let x: Result<u32, &str> = Ok(10);
378 /// x.err().expect("Testing err().expect()");
382 /// let x: Result<u32, &str> = Ok(10);
383 /// x.expect_err("Testing expect_err");
385 #[clippy::version = "1.62.0"]
388 r#"using `.err().expect("")` when `.expect_err("")` can be used"#
391 declare_clippy_lint! {
393 /// Checks for usages of `_.unwrap_or_else(Default::default)` on `Option` and
396 /// ### Why is this bad?
397 /// Readability, these can be written as `_.unwrap_or_default`, which is
398 /// simpler and more concise.
402 /// # let x = Some(1);
403 /// x.unwrap_or_else(Default::default);
404 /// x.unwrap_or_else(u32::default);
409 /// # let x = Some(1);
410 /// x.unwrap_or_default();
412 #[clippy::version = "1.56.0"]
413 pub UNWRAP_OR_ELSE_DEFAULT,
415 "using `.unwrap_or_else(Default::default)`, which is more succinctly expressed as `.unwrap_or_default()`"
418 declare_clippy_lint! {
420 /// Checks for usage of `option.map(_).unwrap_or(_)` or `option.map(_).unwrap_or_else(_)` or
421 /// `result.map(_).unwrap_or_else(_)`.
423 /// ### Why is this bad?
424 /// Readability, these can be written more concisely (resp.) as
425 /// `option.map_or(_, _)`, `option.map_or_else(_, _)` and `result.map_or_else(_, _)`.
427 /// ### Known problems
428 /// The order of the arguments is not in execution order
432 /// # let option = Some(1);
433 /// # let result: Result<usize, ()> = Ok(1);
434 /// # fn some_function(foo: ()) -> usize { 1 }
435 /// option.map(|a| a + 1).unwrap_or(0);
436 /// result.map(|a| a + 1).unwrap_or_else(some_function);
441 /// # let option = Some(1);
442 /// # let result: Result<usize, ()> = Ok(1);
443 /// # fn some_function(foo: ()) -> usize { 1 }
444 /// option.map_or(0, |a| a + 1);
445 /// result.map_or_else(some_function, |a| a + 1);
447 #[clippy::version = "1.45.0"]
450 "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)`"
453 declare_clippy_lint! {
455 /// Checks for usage of `_.map_or(None, _)`.
457 /// ### Why is this bad?
458 /// Readability, this can be written more concisely as
461 /// ### Known problems
462 /// The order of the arguments is not in execution order.
466 /// # let opt = Some(1);
467 /// opt.map_or(None, |a| Some(a + 1));
472 /// # let opt = Some(1);
473 /// opt.and_then(|a| Some(a + 1));
475 #[clippy::version = "pre 1.29.0"]
476 pub OPTION_MAP_OR_NONE,
478 "using `Option.map_or(None, f)`, which is more succinctly expressed as `and_then(f)`"
481 declare_clippy_lint! {
483 /// Checks for usage of `_.map_or(None, Some)`.
485 /// ### Why is this bad?
486 /// Readability, this can be written more concisely as
491 /// # let r: Result<u32, &str> = Ok(1);
492 /// assert_eq!(Some(1), r.map_or(None, Some));
497 /// # let r: Result<u32, &str> = Ok(1);
498 /// assert_eq!(Some(1), r.ok());
500 #[clippy::version = "1.44.0"]
501 pub RESULT_MAP_OR_INTO_OPTION,
503 "using `Result.map_or(None, Some)`, which is more succinctly expressed as `ok()`"
506 declare_clippy_lint! {
508 /// Checks for usage of `_.and_then(|x| Some(y))`, `_.and_then(|x| Ok(y))` or
509 /// `_.or_else(|x| Err(y))`.
511 /// ### Why is this bad?
512 /// Readability, this can be written more concisely as
513 /// `_.map(|x| y)` or `_.map_err(|x| y)`.
517 /// # fn opt() -> Option<&'static str> { Some("42") }
518 /// # fn res() -> Result<&'static str, &'static str> { Ok("42") }
519 /// let _ = opt().and_then(|s| Some(s.len()));
520 /// let _ = res().and_then(|s| if s.len() == 42 { Ok(10) } else { Ok(20) });
521 /// let _ = res().or_else(|s| if s.len() == 42 { Err(10) } else { Err(20) });
524 /// The correct use would be:
527 /// # fn opt() -> Option<&'static str> { Some("42") }
528 /// # fn res() -> Result<&'static str, &'static str> { Ok("42") }
529 /// let _ = opt().map(|s| s.len());
530 /// let _ = res().map(|s| if s.len() == 42 { 10 } else { 20 });
531 /// let _ = res().map_err(|s| if s.len() == 42 { 10 } else { 20 });
533 #[clippy::version = "1.45.0"]
534 pub BIND_INSTEAD_OF_MAP,
536 "using `Option.and_then(|x| Some(y))`, which is more succinctly expressed as `map(|x| y)`"
539 declare_clippy_lint! {
541 /// Checks for usage of `_.filter(_).next()`.
543 /// ### Why is this bad?
544 /// Readability, this can be written more concisely as
549 /// # let vec = vec![1];
550 /// vec.iter().filter(|x| **x == 0).next();
555 /// # let vec = vec![1];
556 /// vec.iter().find(|x| **x == 0);
558 #[clippy::version = "pre 1.29.0"]
561 "using `filter(p).next()`, which is more succinctly expressed as `.find(p)`"
564 declare_clippy_lint! {
566 /// Checks for usage of `_.skip_while(condition).next()`.
568 /// ### Why is this bad?
569 /// Readability, this can be written more concisely as
570 /// `_.find(!condition)`.
574 /// # let vec = vec![1];
575 /// vec.iter().skip_while(|x| **x == 0).next();
580 /// # let vec = vec![1];
581 /// vec.iter().find(|x| **x != 0);
583 #[clippy::version = "1.42.0"]
586 "using `skip_while(p).next()`, which is more succinctly expressed as `.find(!p)`"
589 declare_clippy_lint! {
591 /// Checks for usage of `_.map(_).flatten(_)` on `Iterator` and `Option`
593 /// ### Why is this bad?
594 /// Readability, this can be written more concisely as
595 /// `_.flat_map(_)` for `Iterator` or `_.and_then(_)` for `Option`
599 /// let vec = vec![vec![1]];
600 /// let opt = Some(5);
602 /// vec.iter().map(|x| x.iter()).flatten();
603 /// opt.map(|x| Some(x * 2)).flatten();
608 /// # let vec = vec![vec![1]];
609 /// # let opt = Some(5);
610 /// vec.iter().flat_map(|x| x.iter());
611 /// opt.and_then(|x| Some(x * 2));
613 #[clippy::version = "1.31.0"]
616 "using combinations of `flatten` and `map` which can usually be written as a single method call"
619 declare_clippy_lint! {
621 /// Checks for usage of `_.filter(_).map(_)` that can be written more simply
622 /// as `filter_map(_)`.
624 /// ### Why is this bad?
625 /// Redundant code in the `filter` and `map` operations is poor style and
630 /// # #![allow(unused)]
632 /// .filter(|n| n.checked_add(1).is_some())
633 /// .map(|n| n.checked_add(1).unwrap());
638 /// # #[allow(unused)]
639 /// (0_i32..10).filter_map(|n| n.checked_add(1));
641 #[clippy::version = "1.51.0"]
642 pub MANUAL_FILTER_MAP,
644 "using `_.filter(_).map(_)` in a way that can be written more simply as `filter_map(_)`"
647 declare_clippy_lint! {
649 /// Checks for usage of `_.find(_).map(_)` that can be written more simply
650 /// as `find_map(_)`.
652 /// ### Why is this bad?
653 /// Redundant code in the `find` and `map` operations is poor style and
659 /// .find(|n| n.checked_add(1).is_some())
660 /// .map(|n| n.checked_add(1).unwrap());
665 /// (0_i32..10).find_map(|n| n.checked_add(1));
667 #[clippy::version = "1.51.0"]
670 "using `_.find(_).map(_)` in a way that can be written more simply as `find_map(_)`"
673 declare_clippy_lint! {
675 /// Checks for usage of `_.filter_map(_).next()`.
677 /// ### Why is this bad?
678 /// Readability, this can be written more concisely as
683 /// (0..3).filter_map(|x| if x == 2 { Some(x) } else { None }).next();
685 /// Can be written as
688 /// (0..3).find_map(|x| if x == 2 { Some(x) } else { None });
690 #[clippy::version = "1.36.0"]
693 "using combination of `filter_map` and `next` which can usually be written as a single method call"
696 declare_clippy_lint! {
698 /// Checks for usage of `flat_map(|x| x)`.
700 /// ### Why is this bad?
701 /// Readability, this can be written more concisely by using `flatten`.
705 /// # let iter = vec![vec![0]].into_iter();
706 /// iter.flat_map(|x| x);
708 /// Can be written as
710 /// # let iter = vec![vec![0]].into_iter();
713 #[clippy::version = "1.39.0"]
714 pub FLAT_MAP_IDENTITY,
716 "call to `flat_map` where `flatten` is sufficient"
719 declare_clippy_lint! {
721 /// Checks for an iterator or string search (such as `find()`,
722 /// `position()`, or `rposition()`) followed by a call to `is_some()` or `is_none()`.
724 /// ### Why is this bad?
725 /// Readability, this can be written more concisely as:
726 /// * `_.any(_)`, or `_.contains(_)` for `is_some()`,
727 /// * `!_.any(_)`, or `!_.contains(_)` for `is_none()`.
731 /// # #![allow(unused)]
732 /// let vec = vec![1];
733 /// vec.iter().find(|x| **x == 0).is_some();
735 /// "hello world".find("world").is_none();
740 /// let vec = vec![1];
741 /// vec.iter().any(|x| *x == 0);
743 /// # #[allow(unused)]
744 /// !"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('_') {};
769 /// let name = "foo";
770 /// if name.starts_with('_') {};
772 #[clippy::version = "pre 1.29.0"]
775 "using `.chars().next()` to check if a string starts with a char"
778 declare_clippy_lint! {
780 /// Checks for calls to `.or(foo(..))`, `.unwrap_or(foo(..))`,
781 /// etc., and suggests to use `or_else`, `unwrap_or_else`, etc., or
782 /// `unwrap_or_default` instead.
784 /// ### Why is this bad?
785 /// The function will always be called and potentially
786 /// allocate an object acting as the default.
788 /// ### Known problems
789 /// If the function has side-effects, not calling it will
790 /// change the semantic of the program, but you shouldn't rely on that anyway.
794 /// # let foo = Some(String::new());
795 /// foo.unwrap_or(String::new());
800 /// # let foo = Some(String::new());
801 /// foo.unwrap_or_else(String::new);
805 /// # let foo = Some(String::new());
806 /// foo.unwrap_or_default();
808 #[clippy::version = "pre 1.29.0"]
811 "using any `*or` method with a function call, which suggests `*or_else`"
814 declare_clippy_lint! {
816 /// Checks for `.or(…).unwrap()` calls to Options and Results.
818 /// ### Why is this bad?
819 /// You should use `.unwrap_or(…)` instead for clarity.
823 /// # let fallback = "fallback";
825 /// # type Error = &'static str;
826 /// # let result: Result<&str, Error> = Err("error");
827 /// let value = result.or::<Error>(Ok(fallback)).unwrap();
830 /// # let option: Option<&str> = None;
831 /// let value = option.or(Some(fallback)).unwrap();
835 /// # let fallback = "fallback";
837 /// # let result: Result<&str, &str> = Err("error");
838 /// let value = result.unwrap_or(fallback);
841 /// # let option: Option<&str> = None;
842 /// let value = option.unwrap_or(fallback);
844 #[clippy::version = "1.61.0"]
847 "checks for `.or(…).unwrap()` calls to Options and Results."
850 declare_clippy_lint! {
852 /// Checks for calls to `.expect(&format!(...))`, `.expect(foo(..))`,
853 /// etc., and suggests to use `unwrap_or_else` instead
855 /// ### Why is this bad?
856 /// The function will always be called.
858 /// ### Known problems
859 /// If the function has side-effects, not calling it will
860 /// change the semantics of the program, but you shouldn't rely on that anyway.
864 /// # let foo = Some(String::new());
865 /// # let err_code = "418";
866 /// # let err_msg = "I'm a teapot";
867 /// foo.expect(&format!("Err {}: {}", err_code, err_msg));
871 /// # let foo = Some(String::new());
872 /// foo.expect(format!("Err {}: {}", err_code, err_msg).as_str());
877 /// # let foo = Some(String::new());
878 /// # let err_code = "418";
879 /// # let err_msg = "I'm a teapot";
880 /// foo.unwrap_or_else(|| panic!("Err {}: {}", err_code, err_msg));
882 #[clippy::version = "pre 1.29.0"]
885 "using any `expect` method with a function call"
888 declare_clippy_lint! {
890 /// Checks for usage of `.clone()` on a `Copy` type.
892 /// ### Why is this bad?
893 /// The only reason `Copy` types implement `Clone` is for
894 /// generics, not for using the `clone` method on a concrete type.
900 #[clippy::version = "pre 1.29.0"]
903 "using `clone` on a `Copy` type"
906 declare_clippy_lint! {
908 /// Checks for usage of `.clone()` on a ref-counted pointer,
909 /// (`Rc`, `Arc`, `rc::Weak`, or `sync::Weak`), and suggests calling Clone via unified
910 /// function syntax instead (e.g., `Rc::clone(foo)`).
912 /// ### Why is this bad?
913 /// Calling '.clone()' on an Rc, Arc, or Weak
914 /// can obscure the fact that only the pointer is being cloned, not the underlying
919 /// # use std::rc::Rc;
920 /// let x = Rc::new(1);
927 /// # use std::rc::Rc;
928 /// # let x = Rc::new(1);
931 #[clippy::version = "pre 1.29.0"]
932 pub CLONE_ON_REF_PTR,
934 "using 'clone' on a ref-counted pointer"
937 declare_clippy_lint! {
939 /// Checks for usage of `.clone()` on an `&&T`.
941 /// ### Why is this bad?
942 /// Cloning an `&&T` copies the inner `&T`, instead of
943 /// cloning the underlying `T`.
950 /// let z = y.clone();
951 /// println!("{:p} {:p}", *y, z); // prints out the same pointer
954 #[clippy::version = "pre 1.29.0"]
955 pub CLONE_DOUBLE_REF,
957 "using `clone` on `&&T`"
960 declare_clippy_lint! {
962 /// Checks for usage of `.to_string()` on an `&&T` where
963 /// `T` implements `ToString` directly (like `&&str` or `&&String`).
965 /// ### Why is this bad?
966 /// This bypasses the specialized implementation of
967 /// `ToString` and instead goes through the more expensive string formatting
972 /// // Generic implementation for `T: Display` is used (slow)
973 /// ["foo", "bar"].iter().map(|s| s.to_string());
975 /// // OK, the specialized impl is used
976 /// ["foo", "bar"].iter().map(|&s| s.to_string());
978 #[clippy::version = "1.40.0"]
979 pub INEFFICIENT_TO_STRING,
981 "using `to_string` on `&&T` where `T: ToString`"
984 declare_clippy_lint! {
986 /// Checks for `new` not returning a type that contains `Self`.
988 /// ### Why is this bad?
989 /// As a convention, `new` methods are used to make a new
990 /// instance of a type.
993 /// In an impl block:
996 /// # struct NotAFoo;
998 /// fn new() -> NotAFoo {
1006 /// struct Bar(Foo);
1008 /// // Bad. The type name must contain `Self`
1009 /// fn new() -> Bar {
1017 /// # struct FooError;
1019 /// // Good. Return type contains `Self`
1020 /// fn new() -> Result<Foo, FooError> {
1026 /// Or in a trait definition:
1028 /// pub trait Trait {
1029 /// // Bad. The type name must contain `Self`
1035 /// pub trait Trait {
1036 /// // Good. Return type contains `Self`
1037 /// fn new() -> Self;
1040 #[clippy::version = "pre 1.29.0"]
1041 pub NEW_RET_NO_SELF,
1043 "not returning type containing `Self` in a `new` method"
1046 declare_clippy_lint! {
1047 /// ### What it does
1048 /// Checks for string methods that receive a single-character
1049 /// `str` as an argument, e.g., `_.split("x")`.
1051 /// ### Why is this bad?
1052 /// Performing these methods using a `char` is faster than
1055 /// ### Known problems
1056 /// Does not catch multi-byte unicode characters.
1067 #[clippy::version = "pre 1.29.0"]
1068 pub SINGLE_CHAR_PATTERN,
1070 "using a single-character str where a char could be used, e.g., `_.split(\"x\")`"
1073 declare_clippy_lint! {
1074 /// ### What it does
1075 /// Checks for calling `.step_by(0)` on iterators which panics.
1077 /// ### Why is this bad?
1078 /// This very much looks like an oversight. Use `panic!()` instead if you
1079 /// actually intend to panic.
1082 /// ```rust,should_panic
1083 /// for x in (0..100).step_by(0) {
1087 #[clippy::version = "pre 1.29.0"]
1088 pub ITERATOR_STEP_BY_ZERO,
1090 "using `Iterator::step_by(0)`, which will panic at runtime"
1093 declare_clippy_lint! {
1094 /// ### What it does
1095 /// Checks for indirect collection of populated `Option`
1097 /// ### Why is this bad?
1098 /// `Option` is like a collection of 0-1 things, so `flatten`
1099 /// automatically does this without suspicious-looking `unwrap` calls.
1103 /// let _ = std::iter::empty::<Option<i32>>().filter(Option::is_some).map(Option::unwrap);
1107 /// let _ = std::iter::empty::<Option<i32>>().flatten();
1109 #[clippy::version = "1.53.0"]
1110 pub OPTION_FILTER_MAP,
1112 "filtering `Option` for `Some` then force-unwrapping, which can be one type-safe operation"
1115 declare_clippy_lint! {
1116 /// ### What it does
1117 /// Checks for the use of `iter.nth(0)`.
1119 /// ### Why is this bad?
1120 /// `iter.next()` is equivalent to
1121 /// `iter.nth(0)`, as they both consume the next element,
1122 /// but is more readable.
1126 /// # use std::collections::HashSet;
1127 /// # let mut s = HashSet::new();
1129 /// let x = s.iter().nth(0);
1134 /// # use std::collections::HashSet;
1135 /// # let mut s = HashSet::new();
1137 /// let x = s.iter().next();
1139 #[clippy::version = "1.42.0"]
1142 "replace `iter.nth(0)` with `iter.next()`"
1145 declare_clippy_lint! {
1146 /// ### What it does
1147 /// Checks for use of `.iter().nth()` (and the related
1148 /// `.iter_mut().nth()`) on standard library types with *O*(1) element access.
1150 /// ### Why is this bad?
1151 /// `.get()` and `.get_mut()` are more efficient and more
1156 /// let some_vec = vec![0, 1, 2, 3];
1157 /// let bad_vec = some_vec.iter().nth(3);
1158 /// let bad_slice = &some_vec[..].iter().nth(3);
1160 /// The correct use would be:
1162 /// let some_vec = vec![0, 1, 2, 3];
1163 /// let bad_vec = some_vec.get(3);
1164 /// let bad_slice = &some_vec[..].get(3);
1166 #[clippy::version = "pre 1.29.0"]
1169 "using `.iter().nth()` on a standard library type with O(1) element access"
1172 declare_clippy_lint! {
1173 /// ### What it does
1174 /// Checks for use of `.skip(x).next()` on iterators.
1176 /// ### Why is this bad?
1177 /// `.nth(x)` is cleaner
1181 /// let some_vec = vec![0, 1, 2, 3];
1182 /// let bad_vec = some_vec.iter().skip(3).next();
1183 /// let bad_slice = &some_vec[..].iter().skip(3).next();
1185 /// The correct use would be:
1187 /// let some_vec = vec![0, 1, 2, 3];
1188 /// let bad_vec = some_vec.iter().nth(3);
1189 /// let bad_slice = &some_vec[..].iter().nth(3);
1191 #[clippy::version = "pre 1.29.0"]
1194 "using `.skip(x).next()` on an iterator"
1197 declare_clippy_lint! {
1198 /// ### What it does
1199 /// Checks for use of `.drain(..)` on `Vec` and `VecDeque` for iteration.
1201 /// ### Why is this bad?
1202 /// `.into_iter()` is simpler with better performance.
1206 /// # use std::collections::HashSet;
1207 /// let mut foo = vec![0, 1, 2, 3];
1208 /// let bar: HashSet<usize> = foo.drain(..).collect();
1212 /// # use std::collections::HashSet;
1213 /// let foo = vec![0, 1, 2, 3];
1214 /// let bar: HashSet<usize> = foo.into_iter().collect();
1216 #[clippy::version = "1.61.0"]
1217 pub ITER_WITH_DRAIN,
1219 "replace `.drain(..)` with `.into_iter()`"
1222 declare_clippy_lint! {
1223 /// ### What it does
1224 /// Checks for using `x.get(x.len() - 1)` instead of
1227 /// ### Why is this bad?
1228 /// Using `x.last()` is easier to read and has the same
1231 /// Note that using `x[x.len() - 1]` is semantically different from
1232 /// `x.last()`. Indexing into the array will panic on out-of-bounds
1233 /// accesses, while `x.get()` and `x.last()` will return `None`.
1235 /// There is another lint (get_unwrap) that covers the case of using
1236 /// `x.get(index).unwrap()` instead of `x[index]`.
1240 /// let x = vec![2, 3, 5];
1241 /// let last_element = x.get(x.len() - 1);
1246 /// let x = vec![2, 3, 5];
1247 /// let last_element = x.last();
1249 #[clippy::version = "1.37.0"]
1250 pub GET_LAST_WITH_LEN,
1252 "Using `x.get(x.len() - 1)` when `x.last()` is correct and simpler"
1255 declare_clippy_lint! {
1256 /// ### What it does
1257 /// Checks for use of `.get().unwrap()` (or
1258 /// `.get_mut().unwrap`) on a standard library type which implements `Index`
1260 /// ### Why is this bad?
1261 /// Using the Index trait (`[]`) is more clear and more
1264 /// ### Known problems
1265 /// Not a replacement for error handling: Using either
1266 /// `.unwrap()` or the Index trait (`[]`) carries the risk of causing a `panic`
1267 /// if the value being accessed is `None`. If the use of `.get().unwrap()` is a
1268 /// temporary placeholder for dealing with the `Option` type, then this does
1269 /// not mitigate the need for error handling. If there is a chance that `.get()`
1270 /// will be `None` in your program, then it is advisable that the `None` case
1271 /// is handled in a future refactor instead of using `.unwrap()` or the Index
1276 /// let mut some_vec = vec![0, 1, 2, 3];
1277 /// let last = some_vec.get(3).unwrap();
1278 /// *some_vec.get_mut(0).unwrap() = 1;
1280 /// The correct use would be:
1282 /// let mut some_vec = vec![0, 1, 2, 3];
1283 /// let last = some_vec[3];
1284 /// some_vec[0] = 1;
1286 #[clippy::version = "pre 1.29.0"]
1289 "using `.get().unwrap()` or `.get_mut().unwrap()` when using `[]` would work instead"
1292 declare_clippy_lint! {
1293 /// ### What it does
1294 /// Checks for occurrences where one vector gets extended instead of append
1296 /// ### Why is this bad?
1297 /// Using `append` instead of `extend` is more concise and faster
1301 /// let mut a = vec![1, 2, 3];
1302 /// let mut b = vec![4, 5, 6];
1304 /// a.extend(b.drain(..));
1309 /// let mut a = vec![1, 2, 3];
1310 /// let mut b = vec![4, 5, 6];
1312 /// a.append(&mut b);
1314 #[clippy::version = "1.55.0"]
1315 pub EXTEND_WITH_DRAIN,
1317 "using vec.append(&mut vec) to move the full range of a vector to another"
1320 declare_clippy_lint! {
1321 /// ### What it does
1322 /// Checks for the use of `.extend(s.chars())` where s is a
1323 /// `&str` or `String`.
1325 /// ### Why is this bad?
1326 /// `.push_str(s)` is clearer
1330 /// let abc = "abc";
1331 /// let def = String::from("def");
1332 /// let mut s = String::new();
1333 /// s.extend(abc.chars());
1334 /// s.extend(def.chars());
1336 /// The correct use would be:
1338 /// let abc = "abc";
1339 /// let def = String::from("def");
1340 /// let mut s = String::new();
1341 /// s.push_str(abc);
1342 /// s.push_str(&def);
1344 #[clippy::version = "pre 1.29.0"]
1345 pub STRING_EXTEND_CHARS,
1347 "using `x.extend(s.chars())` where s is a `&str` or `String`"
1350 declare_clippy_lint! {
1351 /// ### What it does
1352 /// Checks for the use of `.cloned().collect()` on slice to
1355 /// ### Why is this bad?
1356 /// `.to_vec()` is clearer
1360 /// let s = [1, 2, 3, 4, 5];
1361 /// let s2: Vec<isize> = s[..].iter().cloned().collect();
1363 /// The better use would be:
1365 /// let s = [1, 2, 3, 4, 5];
1366 /// let s2: Vec<isize> = s.to_vec();
1368 #[clippy::version = "pre 1.29.0"]
1369 pub ITER_CLONED_COLLECT,
1371 "using `.cloned().collect()` on slice to create a `Vec`"
1374 declare_clippy_lint! {
1375 /// ### What it does
1376 /// Checks for usage of `_.chars().last()` or
1377 /// `_.chars().next_back()` on a `str` to check if it ends with a given char.
1379 /// ### Why is this bad?
1380 /// Readability, this can be written more concisely as
1381 /// `_.ends_with(_)`.
1385 /// # let name = "_";
1386 /// name.chars().last() == Some('_') || name.chars().next_back() == Some('-');
1391 /// # let name = "_";
1392 /// name.ends_with('_') || name.ends_with('-');
1394 #[clippy::version = "pre 1.29.0"]
1397 "using `.chars().last()` or `.chars().next_back()` to check if a string ends with a char"
1400 declare_clippy_lint! {
1401 /// ### What it does
1402 /// Checks for usage of `.as_ref()` or `.as_mut()` where the
1403 /// types before and after the call are the same.
1405 /// ### Why is this bad?
1406 /// The call is unnecessary.
1410 /// # fn do_stuff(x: &[i32]) {}
1411 /// let x: &[i32] = &[1, 2, 3, 4, 5];
1412 /// do_stuff(x.as_ref());
1414 /// The correct use would be:
1416 /// # fn do_stuff(x: &[i32]) {}
1417 /// let x: &[i32] = &[1, 2, 3, 4, 5];
1420 #[clippy::version = "pre 1.29.0"]
1423 "using `as_ref` where the types before and after the call are the same"
1426 declare_clippy_lint! {
1427 /// ### What it does
1428 /// Checks for using `fold` when a more succinct alternative exists.
1429 /// Specifically, this checks for `fold`s which could be replaced by `any`, `all`,
1430 /// `sum` or `product`.
1432 /// ### Why is this bad?
1437 /// # #[allow(unused)]
1438 /// (0..3).fold(false, |acc, x| acc || x > 2);
1443 /// (0..3).any(|x| x > 2);
1445 #[clippy::version = "pre 1.29.0"]
1446 pub UNNECESSARY_FOLD,
1448 "using `fold` when a more succinct alternative exists"
1451 declare_clippy_lint! {
1452 /// ### What it does
1453 /// Checks for `filter_map` calls that could be replaced by `filter` or `map`.
1454 /// More specifically it checks if the closure provided is only performing one of the
1455 /// filter or map operations and suggests the appropriate option.
1457 /// ### Why is this bad?
1458 /// Complexity. The intent is also clearer if only a single
1459 /// operation is being performed.
1463 /// let _ = (0..3).filter_map(|x| if x > 2 { Some(x) } else { None });
1465 /// // As there is no transformation of the argument this could be written as:
1466 /// let _ = (0..3).filter(|&x| x > 2);
1470 /// let _ = (0..4).filter_map(|x| Some(x + 1));
1472 /// // As there is no conditional check on the argument this could be written as:
1473 /// let _ = (0..4).map(|x| x + 1);
1475 #[clippy::version = "1.31.0"]
1476 pub UNNECESSARY_FILTER_MAP,
1478 "using `filter_map` when a more succinct alternative exists"
1481 declare_clippy_lint! {
1482 /// ### What it does
1483 /// Checks for `find_map` calls that could be replaced by `find` or `map`. More
1484 /// specifically it checks if the closure provided is only performing one of the
1485 /// find or map operations and suggests the appropriate option.
1487 /// ### Why is this bad?
1488 /// Complexity. The intent is also clearer if only a single
1489 /// operation is being performed.
1493 /// let _ = (0..3).find_map(|x| if x > 2 { Some(x) } else { None });
1495 /// // As there is no transformation of the argument this could be written as:
1496 /// let _ = (0..3).find(|&x| x > 2);
1500 /// let _ = (0..4).find_map(|x| Some(x + 1));
1502 /// // As there is no conditional check on the argument this could be written as:
1503 /// let _ = (0..4).map(|x| x + 1).next();
1505 #[clippy::version = "1.61.0"]
1506 pub UNNECESSARY_FIND_MAP,
1508 "using `find_map` when a more succinct alternative exists"
1511 declare_clippy_lint! {
1512 /// ### What it does
1513 /// Checks for `into_iter` calls on references which should be replaced by `iter`
1516 /// ### Why is this bad?
1517 /// Readability. Calling `into_iter` on a reference will not move out its
1518 /// content into the resulting iterator, which is confusing. It is better just call `iter` or
1519 /// `iter_mut` directly.
1523 /// # let vec = vec![3, 4, 5];
1524 /// (&vec).into_iter();
1529 /// # let vec = vec![3, 4, 5];
1532 #[clippy::version = "1.32.0"]
1533 pub INTO_ITER_ON_REF,
1535 "using `.into_iter()` on a reference"
1538 declare_clippy_lint! {
1539 /// ### What it does
1540 /// Checks for calls to `map` followed by a `count`.
1542 /// ### Why is this bad?
1543 /// It looks suspicious. Maybe `map` was confused with `filter`.
1544 /// If the `map` call is intentional, this should be rewritten
1545 /// using `inspect`. Or, if you intend to drive the iterator to
1546 /// completion, you can just use `for_each` instead.
1550 /// let _ = (0..3).map(|x| x + 2).count();
1552 #[clippy::version = "1.39.0"]
1555 "suspicious usage of map"
1558 declare_clippy_lint! {
1559 /// ### What it does
1560 /// Checks for `MaybeUninit::uninit().assume_init()`.
1562 /// ### Why is this bad?
1563 /// For most types, this is undefined behavior.
1565 /// ### Known problems
1566 /// For now, we accept empty tuples and tuples / arrays
1567 /// of `MaybeUninit`. There may be other types that allow uninitialized
1568 /// data, but those are not yet rigorously defined.
1572 /// // Beware the UB
1573 /// use std::mem::MaybeUninit;
1575 /// let _: usize = unsafe { MaybeUninit::uninit().assume_init() };
1578 /// Note that the following is OK:
1581 /// use std::mem::MaybeUninit;
1583 /// let _: [MaybeUninit<bool>; 5] = unsafe {
1584 /// MaybeUninit::uninit().assume_init()
1587 #[clippy::version = "1.39.0"]
1588 pub UNINIT_ASSUMED_INIT,
1590 "`MaybeUninit::uninit().assume_init()`"
1593 declare_clippy_lint! {
1594 /// ### What it does
1595 /// Checks for `.checked_add/sub(x).unwrap_or(MAX/MIN)`.
1597 /// ### Why is this bad?
1598 /// These can be written simply with `saturating_add/sub` methods.
1602 /// # let y: u32 = 0;
1603 /// # let x: u32 = 100;
1604 /// let add = x.checked_add(y).unwrap_or(u32::MAX);
1605 /// let sub = x.checked_sub(y).unwrap_or(u32::MIN);
1608 /// can be written using dedicated methods for saturating addition/subtraction as:
1611 /// # let y: u32 = 0;
1612 /// # let x: u32 = 100;
1613 /// let add = x.saturating_add(y);
1614 /// let sub = x.saturating_sub(y);
1616 #[clippy::version = "1.39.0"]
1617 pub MANUAL_SATURATING_ARITHMETIC,
1619 "`.checked_add/sub(x).unwrap_or(MAX/MIN)`"
1622 declare_clippy_lint! {
1623 /// ### What it does
1624 /// Checks for `offset(_)`, `wrapping_`{`add`, `sub`}, etc. on raw pointers to
1625 /// zero-sized types
1627 /// ### Why is this bad?
1628 /// This is a no-op, and likely unintended
1632 /// unsafe { (&() as *const ()).offset(1) };
1634 #[clippy::version = "1.41.0"]
1637 "Check for offset calculations on raw pointers to zero-sized types"
1640 declare_clippy_lint! {
1641 /// ### What it does
1642 /// Checks for `FileType::is_file()`.
1644 /// ### Why is this bad?
1645 /// When people testing a file type with `FileType::is_file`
1646 /// they are testing whether a path is something they can get bytes from. But
1647 /// `is_file` doesn't cover special file types in unix-like systems, and doesn't cover
1648 /// symlink in windows. Using `!FileType::is_dir()` is a better way to that intention.
1653 /// let metadata = std::fs::metadata("foo.txt")?;
1654 /// let filetype = metadata.file_type();
1656 /// if filetype.is_file() {
1659 /// # Ok::<_, std::io::Error>(())
1663 /// should be written as:
1667 /// let metadata = std::fs::metadata("foo.txt")?;
1668 /// let filetype = metadata.file_type();
1670 /// if !filetype.is_dir() {
1673 /// # Ok::<_, std::io::Error>(())
1676 #[clippy::version = "1.42.0"]
1677 pub FILETYPE_IS_FILE,
1679 "`FileType::is_file` is not recommended to test for readable file type"
1682 declare_clippy_lint! {
1683 /// ### What it does
1684 /// Checks for usage of `_.as_ref().map(Deref::deref)` or it's aliases (such as String::as_str).
1686 /// ### Why is this bad?
1687 /// Readability, this can be written more concisely as
1692 /// # let opt = Some("".to_string());
1693 /// opt.as_ref().map(String::as_str)
1696 /// Can be written as
1698 /// # let opt = Some("".to_string());
1702 #[clippy::version = "1.42.0"]
1703 pub OPTION_AS_REF_DEREF,
1705 "using `as_ref().map(Deref::deref)`, which is more succinctly expressed as `as_deref()`"
1708 declare_clippy_lint! {
1709 /// ### What it does
1710 /// Checks for usage of `iter().next()` on a Slice or an Array
1712 /// ### Why is this bad?
1713 /// These can be shortened into `.get()`
1717 /// # let a = [1, 2, 3];
1718 /// # let b = vec![1, 2, 3];
1719 /// a[2..].iter().next();
1720 /// b.iter().next();
1722 /// should be written as:
1724 /// # let a = [1, 2, 3];
1725 /// # let b = vec![1, 2, 3];
1729 #[clippy::version = "1.46.0"]
1730 pub ITER_NEXT_SLICE,
1732 "using `.iter().next()` on a sliced array, which can be shortened to just `.get()`"
1735 declare_clippy_lint! {
1736 /// ### What it does
1737 /// Warns when using `push_str`/`insert_str` with a single-character string literal
1738 /// where `push`/`insert` with a `char` would work fine.
1740 /// ### Why is this bad?
1741 /// It's less clear that we are pushing a single character.
1745 /// # let mut string = String::new();
1746 /// string.insert_str(0, "R");
1747 /// string.push_str("R");
1752 /// # let mut string = String::new();
1753 /// string.insert(0, 'R');
1754 /// string.push('R');
1756 #[clippy::version = "1.49.0"]
1757 pub SINGLE_CHAR_ADD_STR,
1759 "`push_str()` or `insert_str()` used with a single-character string literal as parameter"
1762 declare_clippy_lint! {
1763 /// ### What it does
1764 /// As the counterpart to `or_fun_call`, this lint looks for unnecessary
1765 /// lazily evaluated closures on `Option` and `Result`.
1767 /// This lint suggests changing the following functions, when eager evaluation results in
1769 /// - `unwrap_or_else` to `unwrap_or`
1770 /// - `and_then` to `and`
1771 /// - `or_else` to `or`
1772 /// - `get_or_insert_with` to `get_or_insert`
1773 /// - `ok_or_else` to `ok_or`
1775 /// ### Why is this bad?
1776 /// Using eager evaluation is shorter and simpler in some cases.
1778 /// ### Known problems
1779 /// It is possible, but not recommended for `Deref` and `Index` to have
1780 /// side effects. Eagerly evaluating them can change the semantics of the program.
1784 /// // example code where clippy issues a warning
1785 /// let opt: Option<u32> = None;
1787 /// opt.unwrap_or_else(|| 42);
1791 /// let opt: Option<u32> = None;
1793 /// opt.unwrap_or(42);
1795 #[clippy::version = "1.48.0"]
1796 pub UNNECESSARY_LAZY_EVALUATIONS,
1798 "using unnecessary lazy evaluation, which can be replaced with simpler eager evaluation"
1801 declare_clippy_lint! {
1802 /// ### What it does
1803 /// Checks for usage of `_.map(_).collect::<Result<(), _>()`.
1805 /// ### Why is this bad?
1806 /// Using `try_for_each` instead is more readable and idiomatic.
1810 /// (0..3).map(|t| Err(t)).collect::<Result<(), _>>();
1814 /// (0..3).try_for_each(|t| Err(t));
1816 #[clippy::version = "1.49.0"]
1817 pub MAP_COLLECT_RESULT_UNIT,
1819 "using `.map(_).collect::<Result<(),_>()`, which can be replaced with `try_for_each`"
1822 declare_clippy_lint! {
1823 /// ### What it does
1824 /// Checks for `from_iter()` function calls on types that implement the `FromIterator`
1827 /// ### Why is this bad?
1828 /// It is recommended style to use collect. See
1829 /// [FromIterator documentation](https://doc.rust-lang.org/std/iter/trait.FromIterator.html)
1833 /// let five_fives = std::iter::repeat(5).take(5);
1835 /// let v = Vec::from_iter(five_fives);
1837 /// assert_eq!(v, vec![5, 5, 5, 5, 5]);
1841 /// let five_fives = std::iter::repeat(5).take(5);
1843 /// let v: Vec<i32> = five_fives.collect();
1845 /// assert_eq!(v, vec![5, 5, 5, 5, 5]);
1847 #[clippy::version = "1.49.0"]
1848 pub FROM_ITER_INSTEAD_OF_COLLECT,
1850 "use `.collect()` instead of `::from_iter()`"
1853 declare_clippy_lint! {
1854 /// ### What it does
1855 /// Checks for usage of `inspect().for_each()`.
1857 /// ### Why is this bad?
1858 /// It is the same as performing the computation
1859 /// inside `inspect` at the beginning of the closure in `for_each`.
1863 /// [1,2,3,4,5].iter()
1864 /// .inspect(|&x| println!("inspect the number: {}", x))
1865 /// .for_each(|&x| {
1866 /// assert!(x >= 0);
1869 /// Can be written as
1871 /// [1,2,3,4,5].iter()
1872 /// .for_each(|&x| {
1873 /// println!("inspect the number: {}", x);
1874 /// assert!(x >= 0);
1877 #[clippy::version = "1.51.0"]
1878 pub INSPECT_FOR_EACH,
1880 "using `.inspect().for_each()`, which can be replaced with `.for_each()`"
1883 declare_clippy_lint! {
1884 /// ### What it does
1885 /// Checks for usage of `filter_map(|x| x)`.
1887 /// ### Why is this bad?
1888 /// Readability, this can be written more concisely by using `flatten`.
1892 /// # let iter = vec![Some(1)].into_iter();
1893 /// iter.filter_map(|x| x);
1897 /// # let iter = vec![Some(1)].into_iter();
1900 #[clippy::version = "1.52.0"]
1901 pub FILTER_MAP_IDENTITY,
1903 "call to `filter_map` where `flatten` is sufficient"
1906 declare_clippy_lint! {
1907 /// ### What it does
1908 /// Checks for instances of `map(f)` where `f` is the identity function.
1910 /// ### Why is this bad?
1911 /// It can be written more concisely without the call to `map`.
1915 /// let x = [1, 2, 3];
1916 /// let y: Vec<_> = x.iter().map(|x| x).map(|x| 2*x).collect();
1920 /// let x = [1, 2, 3];
1921 /// let y: Vec<_> = x.iter().map(|x| 2*x).collect();
1923 #[clippy::version = "1.47.0"]
1926 "using iterator.map(|x| x)"
1929 declare_clippy_lint! {
1930 /// ### What it does
1931 /// Checks for the use of `.bytes().nth()`.
1933 /// ### Why is this bad?
1934 /// `.as_bytes().get()` is more efficient and more
1939 /// # #[allow(unused)]
1940 /// "Hello".bytes().nth(3);
1945 /// # #[allow(unused)]
1946 /// "Hello".as_bytes().get(3);
1948 #[clippy::version = "1.52.0"]
1951 "replace `.bytes().nth()` with `.as_bytes().get()`"
1954 declare_clippy_lint! {
1955 /// ### What it does
1956 /// Checks for the usage of `_.to_owned()`, `vec.to_vec()`, or similar when calling `_.clone()` would be clearer.
1958 /// ### Why is this bad?
1959 /// These methods do the same thing as `_.clone()` but may be confusing as
1960 /// to why we are calling `to_vec` on something that is already a `Vec` or calling `to_owned` on something that is already owned.
1964 /// let a = vec![1, 2, 3];
1965 /// let b = a.to_vec();
1966 /// let c = a.to_owned();
1970 /// let a = vec![1, 2, 3];
1971 /// let b = a.clone();
1972 /// let c = a.clone();
1974 #[clippy::version = "1.52.0"]
1977 "implicitly cloning a value by invoking a function on its dereferenced type"
1980 declare_clippy_lint! {
1981 /// ### What it does
1982 /// Checks for the use of `.iter().count()`.
1984 /// ### Why is this bad?
1985 /// `.len()` is more efficient and more
1990 /// # #![allow(unused)]
1991 /// let some_vec = vec![0, 1, 2, 3];
1993 /// some_vec.iter().count();
1994 /// &some_vec[..].iter().count();
1999 /// let some_vec = vec![0, 1, 2, 3];
2002 /// &some_vec[..].len();
2004 #[clippy::version = "1.52.0"]
2007 "replace `.iter().count()` with `.len()`"
2010 declare_clippy_lint! {
2011 /// ### What it does
2012 /// Checks for calls to [`splitn`]
2013 /// (https://doc.rust-lang.org/std/primitive.str.html#method.splitn) and
2014 /// related functions with either zero or one splits.
2016 /// ### Why is this bad?
2017 /// These calls don't actually split the value and are
2018 /// likely to be intended as a different number.
2023 /// for x in s.splitn(1, ":") {
2031 /// for x in s.splitn(2, ":") {
2035 #[clippy::version = "1.54.0"]
2036 pub SUSPICIOUS_SPLITN,
2038 "checks for `.splitn(0, ..)` and `.splitn(1, ..)`"
2041 declare_clippy_lint! {
2042 /// ### What it does
2043 /// Checks for manual implementations of `str::repeat`
2045 /// ### Why is this bad?
2046 /// These are both harder to read, as well as less performant.
2050 /// let x: String = std::iter::repeat('x').take(10).collect();
2055 /// let x: String = "x".repeat(10);
2057 #[clippy::version = "1.54.0"]
2058 pub MANUAL_STR_REPEAT,
2060 "manual implementation of `str::repeat`"
2063 declare_clippy_lint! {
2064 /// ### What it does
2065 /// Checks for usages of `str::splitn(2, _)`
2067 /// ### Why is this bad?
2068 /// `split_once` is both clearer in intent and slightly more efficient.
2072 /// let s = "key=value=add";
2073 /// let (key, value) = s.splitn(2, '=').next_tuple()?;
2074 /// let value = s.splitn(2, '=').nth(1)?;
2076 /// let mut parts = s.splitn(2, '=');
2077 /// let key = parts.next()?;
2078 /// let value = parts.next()?;
2083 /// let s = "key=value=add";
2084 /// let (key, value) = s.split_once('=')?;
2085 /// let value = s.split_once('=')?.1;
2087 /// let (key, value) = s.split_once('=')?;
2091 /// The multiple statement variant currently only detects `iter.next()?`/`iter.next().unwrap()`
2092 /// in two separate `let` statements that immediately follow the `splitn()`
2093 #[clippy::version = "1.57.0"]
2094 pub MANUAL_SPLIT_ONCE,
2096 "replace `.splitn(2, pat)` with `.split_once(pat)`"
2099 declare_clippy_lint! {
2100 /// ### What it does
2101 /// Checks for usages of `str::splitn` (or `str::rsplitn`) where using `str::split` would be the same.
2102 /// ### Why is this bad?
2103 /// The function `split` is simpler and there is no performance difference in these cases, considering
2104 /// that both functions return a lazy iterator.
2107 /// let str = "key=value=add";
2108 /// let _ = str.splitn(3, '=').next().unwrap();
2113 /// let str = "key=value=add";
2114 /// let _ = str.split('=').next().unwrap();
2116 #[clippy::version = "1.59.0"]
2117 pub NEEDLESS_SPLITN,
2119 "usages of `str::splitn` that can be replaced with `str::split`"
2122 declare_clippy_lint! {
2123 /// ### What it does
2124 /// Checks for unnecessary calls to [`ToOwned::to_owned`](https://doc.rust-lang.org/std/borrow/trait.ToOwned.html#tymethod.to_owned)
2125 /// and other `to_owned`-like functions.
2127 /// ### Why is this bad?
2128 /// The unnecessary calls result in useless allocations.
2130 /// ### Known problems
2131 /// `unnecessary_to_owned` can falsely trigger if `IntoIterator::into_iter` is applied to an
2132 /// owned copy of a resource and the resource is later used mutably. See
2133 /// [#8148](https://github.com/rust-lang/rust-clippy/issues/8148).
2137 /// let path = std::path::Path::new("x");
2138 /// foo(&path.to_string_lossy().to_string());
2139 /// fn foo(s: &str) {}
2143 /// let path = std::path::Path::new("x");
2144 /// foo(&path.to_string_lossy());
2145 /// fn foo(s: &str) {}
2147 #[clippy::version = "1.59.0"]
2148 pub UNNECESSARY_TO_OWNED,
2150 "unnecessary calls to `to_owned`-like functions"
2153 declare_clippy_lint! {
2154 /// ### What it does
2155 /// Checks for use of `.collect::<Vec<String>>().join("")` on iterators.
2157 /// ### Why is this bad?
2158 /// `.collect::<String>()` is more concise and might be more performant
2162 /// let vector = vec!["hello", "world"];
2163 /// let output = vector.iter().map(|item| item.to_uppercase()).collect::<Vec<String>>().join("");
2164 /// println!("{}", output);
2166 /// The correct use would be:
2168 /// let vector = vec!["hello", "world"];
2169 /// let output = vector.iter().map(|item| item.to_uppercase()).collect::<String>();
2170 /// println!("{}", output);
2172 /// ### Known problems
2173 /// While `.collect::<String>()` is sometimes more performant, there are cases where
2174 /// using `.collect::<String>()` over `.collect::<Vec<String>>().join("")`
2175 /// will prevent loop unrolling and will result in a negative performance impact.
2177 /// Additionally, differences have been observed between aarch64 and x86_64 assembly output,
2178 /// with aarch64 tending to producing faster assembly in more cases when using `.collect::<String>()`
2179 #[clippy::version = "1.61.0"]
2180 pub UNNECESSARY_JOIN,
2182 "using `.collect::<Vec<String>>().join(\"\")` on an iterator"
2185 declare_clippy_lint! {
2186 /// ### What it does
2187 /// Checks for no-op uses of `Option::{as_deref, as_deref_mut}`,
2188 /// for example, `Option<&T>::as_deref()` returns the same type.
2190 /// ### Why is this bad?
2191 /// Redundant code and improving readability.
2195 /// let a = Some(&1);
2196 /// let b = a.as_deref(); // goes from Option<&i32> to Option<&i32>
2201 /// let a = Some(&1);
2204 #[clippy::version = "1.57.0"]
2205 pub NEEDLESS_OPTION_AS_DEREF,
2207 "no-op use of `deref` or `deref_mut` method to `Option`."
2210 declare_clippy_lint! {
2211 /// ### What it does
2212 /// Finds usages of [`char::is_digit`](https://doc.rust-lang.org/stable/std/primitive.char.html#method.is_digit) that
2213 /// can be replaced with [`is_ascii_digit`](https://doc.rust-lang.org/stable/std/primitive.char.html#method.is_ascii_digit) or
2214 /// [`is_ascii_hexdigit`](https://doc.rust-lang.org/stable/std/primitive.char.html#method.is_ascii_hexdigit).
2216 /// ### Why is this bad?
2217 /// `is_digit(..)` is slower and requires specifying the radix.
2221 /// let c: char = '6';
2227 /// let c: char = '6';
2228 /// c.is_ascii_digit();
2229 /// c.is_ascii_hexdigit();
2231 #[clippy::version = "1.62.0"]
2232 pub IS_DIGIT_ASCII_RADIX,
2234 "use of `char::is_digit(..)` with literal radix of 10 or 16"
2237 declare_clippy_lint! {
2238 /// ### What it does
2239 /// Checks for calling `take` function after `as_ref`.
2241 /// ### Why is this bad?
2242 /// Redundant code. `take` writes `None` to its argument.
2243 /// In this case the modification is useless as it's a temporary that cannot be read from afterwards.
2247 /// let x = Some(3);
2248 /// x.as_ref().take();
2252 /// let x = Some(3);
2255 #[clippy::version = "1.62.0"]
2256 pub NEEDLESS_OPTION_TAKE,
2258 "using `.as_ref().take()` on a temporary value"
2261 declare_clippy_lint! {
2262 /// ### What it does
2263 /// Checks for `replace` statements which have no effect.
2265 /// ### Why is this bad?
2266 /// It's either a mistake or confusing.
2270 /// "1234".replace("12", "12");
2271 /// "1234".replacen("12", "12", 1);
2273 #[clippy::version = "1.63.0"]
2274 pub NO_EFFECT_REPLACE,
2276 "replace with no effect"
2279 declare_clippy_lint! {
2280 /// ### What it does
2281 /// Checks for usages of `.then_some(..).unwrap_or(..)`
2283 /// ### Why is this bad?
2284 /// This can be written more clearly with `if .. else ..`
2287 /// This lint currently only looks for usages of
2288 /// `.then_some(..).unwrap_or(..)`, but will be expanded
2289 /// to account for similar patterns.
2294 /// x.then_some("a").unwrap_or("b");
2299 /// if x { "a" } else { "b" };
2301 #[clippy::version = "1.64.0"]
2302 pub OBFUSCATED_IF_ELSE,
2304 "use of `.then_some(..).unwrap_or(..)` can be written \
2305 more clearly with `if .. else ..`"
2308 declare_clippy_lint! {
2309 /// ### What it does
2311 /// Checks for calls to `iter`, `iter_mut` or `into_iter` on collections containing a single item
2313 /// ### Why is this bad?
2315 /// It is simpler to use the once function from the standard library:
2320 /// let a = [123].iter();
2321 /// let b = Some(123).into_iter();
2326 /// let a = iter::once(&123);
2327 /// let b = iter::once(123);
2330 /// ### Known problems
2332 /// The type of the resulting iterator might become incompatible with its usage
2333 #[clippy::version = "1.64.0"]
2334 pub ITER_ON_SINGLE_ITEMS,
2336 "Iterator for array of length 1"
2339 declare_clippy_lint! {
2340 /// ### What it does
2342 /// Checks for calls to `iter`, `iter_mut` or `into_iter` on empty collections
2344 /// ### Why is this bad?
2346 /// It is simpler to use the empty function from the standard library:
2351 /// use std::{slice, option};
2352 /// let a: slice::Iter<i32> = [].iter();
2353 /// let f: option::IntoIter<i32> = None.into_iter();
2358 /// let a: iter::Empty<i32> = iter::empty();
2359 /// let b: iter::Empty<i32> = iter::empty();
2362 /// ### Known problems
2364 /// The type of the resulting iterator might become incompatible with its usage
2365 #[clippy::version = "1.64.0"]
2366 pub ITER_ON_EMPTY_COLLECTIONS,
2368 "Iterator for empty array"
2371 pub struct Methods {
2372 avoid_breaking_exported_api: bool,
2373 msrv: Option<RustcVersion>,
2374 allow_expect_in_tests: bool,
2375 allow_unwrap_in_tests: bool,
2381 avoid_breaking_exported_api: bool,
2382 msrv: Option<RustcVersion>,
2383 allow_expect_in_tests: bool,
2384 allow_unwrap_in_tests: bool,
2387 avoid_breaking_exported_api,
2389 allow_expect_in_tests,
2390 allow_unwrap_in_tests,
2395 impl_lint_pass!(Methods => [
2398 SHOULD_IMPLEMENT_TRAIT,
2399 WRONG_SELF_CONVENTION,
2401 UNWRAP_OR_ELSE_DEFAULT,
2403 RESULT_MAP_OR_INTO_OPTION,
2405 BIND_INSTEAD_OF_MAP,
2414 ITER_OVEREAGER_CLONED,
2415 CLONED_INSTEAD_OF_COPIED,
2417 INEFFICIENT_TO_STRING,
2419 SINGLE_CHAR_PATTERN,
2420 SINGLE_CHAR_ADD_STR,
2424 FILTER_MAP_IDENTITY,
2432 ITERATOR_STEP_BY_ZERO,
2441 STRING_EXTEND_CHARS,
2442 ITER_CLONED_COLLECT,
2446 UNNECESSARY_FILTER_MAP,
2447 UNNECESSARY_FIND_MAP,
2450 UNINIT_ASSUMED_INIT,
2451 MANUAL_SATURATING_ARITHMETIC,
2454 OPTION_AS_REF_DEREF,
2455 UNNECESSARY_LAZY_EVALUATIONS,
2456 MAP_COLLECT_RESULT_UNIT,
2457 FROM_ITER_INSTEAD_OF_COLLECT,
2465 UNNECESSARY_TO_OWNED,
2468 NEEDLESS_OPTION_AS_DEREF,
2469 IS_DIGIT_ASCII_RADIX,
2470 NEEDLESS_OPTION_TAKE,
2473 ITER_ON_SINGLE_ITEMS,
2474 ITER_ON_EMPTY_COLLECTIONS
2477 /// Extracts a method call name, args, and `Span` of the method name.
2478 fn method_call<'tcx>(recv: &'tcx hir::Expr<'tcx>) -> Option<(&'tcx str, &'tcx [hir::Expr<'tcx>], Span)> {
2479 if let ExprKind::MethodCall(path, args, _) = recv.kind {
2480 if !args.iter().any(|e| e.span.from_expansion()) {
2481 let name = path.ident.name.as_str();
2482 return Some((name, args, path.ident.span));
2488 impl<'tcx> LateLintPass<'tcx> for Methods {
2489 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) {
2490 if expr.span.from_expansion() {
2494 self.check_methods(cx, expr);
2497 hir::ExprKind::Call(func, args) => {
2498 from_iter_instead_of_collect::check(cx, expr, args, func);
2500 hir::ExprKind::MethodCall(method_call, args, _) => {
2501 let method_span = method_call.ident.span;
2502 or_fun_call::check(cx, expr, method_span, method_call.ident.as_str(), args);
2503 expect_fun_call::check(cx, expr, method_span, method_call.ident.as_str(), args);
2504 clone_on_copy::check(cx, expr, method_call.ident.name, args);
2505 clone_on_ref_ptr::check(cx, expr, method_call.ident.name, args);
2506 inefficient_to_string::check(cx, expr, method_call.ident.name, args);
2507 single_char_add_str::check(cx, expr, args);
2508 into_iter_on_ref::check(cx, expr, method_span, method_call.ident.name, args);
2509 single_char_pattern::check(cx, expr, method_call.ident.name, args);
2510 unnecessary_to_owned::check(cx, expr, method_call.ident.name, args, self.msrv);
2512 hir::ExprKind::Binary(op, lhs, rhs) if op.node == hir::BinOpKind::Eq || op.node == hir::BinOpKind::Ne => {
2513 let mut info = BinaryExprInfo {
2517 eq: op.node == hir::BinOpKind::Eq,
2519 lint_binary_expr_with_method_call(cx, &mut info);
2525 #[allow(clippy::too_many_lines)]
2526 fn check_impl_item(&mut self, cx: &LateContext<'tcx>, impl_item: &'tcx hir::ImplItem<'_>) {
2527 if in_external_macro(cx.sess(), impl_item.span) {
2530 let name = impl_item.ident.name.as_str();
2531 let parent = cx.tcx.hir().get_parent_item(impl_item.hir_id());
2532 let item = cx.tcx.hir().expect_item(parent);
2533 let self_ty = cx.tcx.type_of(item.def_id);
2535 let implements_trait = matches!(item.kind, hir::ItemKind::Impl(hir::Impl { of_trait: Some(_), .. }));
2537 if let hir::ImplItemKind::Fn(ref sig, id) = impl_item.kind;
2538 if let Some(first_arg) = iter_input_pats(sig.decl, cx.tcx.hir().body(id)).next();
2540 let method_sig = cx.tcx.fn_sig(impl_item.def_id);
2541 let method_sig = cx.tcx.erase_late_bound_regions(method_sig);
2543 let first_arg_ty = method_sig.inputs().iter().next();
2545 // check conventions w.r.t. conversion method names and predicates
2546 if let Some(first_arg_ty) = first_arg_ty;
2549 // if this impl block implements a trait, lint in trait definition instead
2550 if !implements_trait && cx.access_levels.is_exported(impl_item.def_id) {
2551 // check missing trait implementations
2552 for method_config in &TRAIT_METHODS {
2553 if name == method_config.method_name &&
2554 sig.decl.inputs.len() == method_config.param_count &&
2555 method_config.output_type.matches(&sig.decl.output) &&
2556 method_config.self_kind.matches(cx, self_ty, *first_arg_ty) &&
2557 fn_header_equals(method_config.fn_header, sig.header) &&
2558 method_config.lifetime_param_cond(impl_item)
2562 SHOULD_IMPLEMENT_TRAIT,
2565 "method `{}` can be confused for the standard trait method `{}::{}`",
2566 method_config.method_name,
2567 method_config.trait_name,
2568 method_config.method_name
2572 "consider implementing the trait `{}` or choosing a less ambiguous method name",
2573 method_config.trait_name
2580 if sig.decl.implicit_self.has_implicit_self()
2581 && !(self.avoid_breaking_exported_api
2582 && cx.access_levels.is_exported(impl_item.def_id))
2584 wrong_self_convention::check(
2597 // if this impl block implements a trait, lint in trait definition instead
2598 if implements_trait {
2602 if let hir::ImplItemKind::Fn(_, _) = impl_item.kind {
2603 let ret_ty = return_ty(cx, impl_item.hir_id());
2605 // walk the return type and check for Self (this does not check associated types)
2606 if let Some(self_adt) = self_ty.ty_adt_def() {
2607 if contains_adt_constructor(ret_ty, self_adt) {
2610 } else if contains_ty(ret_ty, self_ty) {
2614 // if return type is impl trait, check the associated types
2615 if let ty::Opaque(def_id, _) = *ret_ty.kind() {
2616 // one of the associated types must be Self
2617 for &(predicate, _span) in cx.tcx.explicit_item_bounds(def_id) {
2618 if let ty::PredicateKind::Projection(projection_predicate) = predicate.kind().skip_binder() {
2619 let assoc_ty = match projection_predicate.term {
2620 ty::Term::Ty(ty) => ty,
2621 ty::Term::Const(_c) => continue,
2623 // walk the associated type and check for Self
2624 if let Some(self_adt) = self_ty.ty_adt_def() {
2625 if contains_adt_constructor(assoc_ty, self_adt) {
2628 } else if contains_ty(assoc_ty, self_ty) {
2635 if name == "new" && ret_ty != self_ty {
2640 "methods called `new` usually return `Self`",
2646 fn check_trait_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx TraitItem<'_>) {
2647 if in_external_macro(cx.tcx.sess, item.span) {
2652 if let TraitItemKind::Fn(ref sig, _) = item.kind;
2653 if sig.decl.implicit_self.has_implicit_self();
2654 if let Some(first_arg_ty) = sig.decl.inputs.iter().next();
2657 let first_arg_span = first_arg_ty.span;
2658 let first_arg_ty = hir_ty_to_ty(cx.tcx, first_arg_ty);
2659 let self_ty = TraitRef::identity(cx.tcx, item.def_id.to_def_id()).self_ty().skip_binder();
2660 wrong_self_convention::check(
2662 item.ident.name.as_str(),
2673 if item.ident.name == sym::new;
2674 if let TraitItemKind::Fn(_, _) = item.kind;
2675 let ret_ty = return_ty(cx, item.hir_id());
2676 let self_ty = TraitRef::identity(cx.tcx, item.def_id.to_def_id()).self_ty().skip_binder();
2677 if !contains_ty(ret_ty, self_ty);
2684 "methods called `new` usually return `Self`",
2690 extract_msrv_attr!(LateContext);
2694 #[allow(clippy::too_many_lines)]
2695 fn check_methods<'tcx>(&self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
2696 if let Some((name, [recv, args @ ..], span)) = method_call(expr) {
2697 match (name, args) {
2698 ("add" | "offset" | "sub" | "wrapping_offset" | "wrapping_add" | "wrapping_sub", [_arg]) => {
2699 zst_offset::check(cx, expr, recv);
2701 ("and_then", [arg]) => {
2702 let biom_option_linted = bind_instead_of_map::OptionAndThenSome::check(cx, expr, recv, arg);
2703 let biom_result_linted = bind_instead_of_map::ResultAndThenOk::check(cx, expr, recv, arg);
2704 if !biom_option_linted && !biom_result_linted {
2705 unnecessary_lazy_eval::check(cx, expr, recv, arg, "and");
2708 ("as_deref" | "as_deref_mut", []) => {
2709 needless_option_as_deref::check(cx, expr, recv, name);
2711 ("as_mut", []) => useless_asref::check(cx, expr, "as_mut", recv),
2712 ("as_ref", []) => useless_asref::check(cx, expr, "as_ref", recv),
2713 ("assume_init", []) => uninit_assumed_init::check(cx, expr, recv),
2714 ("cloned", []) => cloned_instead_of_copied::check(cx, expr, recv, span, self.msrv),
2715 ("collect", []) => match method_call(recv) {
2716 Some((name @ ("cloned" | "copied"), [recv2], _)) => {
2717 iter_cloned_collect::check(cx, name, expr, recv2);
2719 Some(("map", [m_recv, m_arg], _)) => {
2720 map_collect_result_unit::check(cx, expr, m_recv, m_arg, recv);
2722 Some(("take", [take_self_arg, take_arg], _)) => {
2723 if meets_msrv(self.msrv, msrvs::STR_REPEAT) {
2724 manual_str_repeat::check(cx, expr, recv, take_self_arg, take_arg);
2729 ("count", []) => match method_call(recv) {
2730 Some(("cloned", [recv2], _)) => iter_overeager_cloned::check(cx, expr, recv, recv2, true, false),
2731 Some((name2 @ ("into_iter" | "iter" | "iter_mut"), [recv2], _)) => {
2732 iter_count::check(cx, expr, recv2, name2);
2734 Some(("map", [_, arg], _)) => suspicious_map::check(cx, expr, recv, arg),
2737 ("drain", [arg]) => {
2738 iter_with_drain::check(cx, expr, recv, span, arg);
2740 ("expect", [_]) => match method_call(recv) {
2741 Some(("ok", [recv], _)) => ok_expect::check(cx, expr, recv),
2742 Some(("err", [recv], err_span)) => err_expect::check(cx, expr, recv, self.msrv, span, err_span),
2743 _ => expect_used::check(cx, expr, recv, self.allow_expect_in_tests),
2745 ("extend", [arg]) => {
2746 string_extend_chars::check(cx, expr, recv, arg);
2747 extend_with_drain::check(cx, expr, recv, arg);
2749 ("filter_map", [arg]) => {
2750 unnecessary_filter_map::check(cx, expr, arg, name);
2751 filter_map_identity::check(cx, expr, arg, span);
2753 ("find_map", [arg]) => {
2754 unnecessary_filter_map::check(cx, expr, arg, name);
2756 ("flat_map", [arg]) => {
2757 flat_map_identity::check(cx, expr, arg, span);
2758 flat_map_option::check(cx, expr, arg, span);
2760 ("flatten", []) => match method_call(recv) {
2761 Some(("map", [recv, map_arg], map_span)) => map_flatten::check(cx, expr, recv, map_arg, map_span),
2762 Some(("cloned", [recv2], _)) => iter_overeager_cloned::check(cx, expr, recv, recv2, false, true),
2765 ("fold", [init, acc]) => unnecessary_fold::check(cx, expr, init, acc, span),
2766 ("for_each", [_]) => {
2767 if let Some(("inspect", [_, _], span2)) = method_call(recv) {
2768 inspect_for_each::check(cx, expr, span2);
2771 ("get", [arg]) => get_last_with_len::check(cx, expr, recv, arg),
2772 ("get_or_insert_with", [arg]) => unnecessary_lazy_eval::check(cx, expr, recv, arg, "get_or_insert"),
2773 ("is_file", []) => filetype_is_file::check(cx, expr, recv),
2774 ("is_digit", [radix]) => is_digit_ascii_radix::check(cx, expr, recv, radix, self.msrv),
2775 ("is_none", []) => check_is_some_is_none(cx, expr, recv, false),
2776 ("is_some", []) => check_is_some_is_none(cx, expr, recv, true),
2777 ("iter" | "iter_mut" | "into_iter", []) => {
2778 iter_on_single_or_empty_collections::check(cx, expr, name, recv);
2780 ("join", [join_arg]) => {
2781 if let Some(("collect", _, span)) = method_call(recv) {
2782 unnecessary_join::check(cx, expr, recv, join_arg, span);
2785 ("last", []) | ("skip", [_]) => {
2786 if let Some((name2, [recv2, args2 @ ..], _span2)) = method_call(recv) {
2787 if let ("cloned", []) = (name2, args2) {
2788 iter_overeager_cloned::check(cx, expr, recv, recv2, false, false);
2792 (name @ ("map" | "map_err"), [m_arg]) => {
2793 if let Some((name, [recv2, args @ ..], span2)) = method_call(recv) {
2794 match (name, args) {
2795 ("as_mut", []) => option_as_ref_deref::check(cx, expr, recv2, m_arg, true, self.msrv),
2796 ("as_ref", []) => option_as_ref_deref::check(cx, expr, recv2, m_arg, false, self.msrv),
2797 ("filter", [f_arg]) => {
2798 filter_map::check(cx, expr, recv2, f_arg, span2, recv, m_arg, span, false);
2800 ("find", [f_arg]) => {
2801 filter_map::check(cx, expr, recv2, f_arg, span2, recv, m_arg, span, true);
2806 map_identity::check(cx, expr, recv, m_arg, name, span);
2808 ("map_or", [def, map]) => option_map_or_none::check(cx, expr, recv, def, map),
2810 if let Some((name2, [recv2, args2 @ ..], _)) = method_call(recv) {
2811 match (name2, args2) {
2812 ("cloned", []) => iter_overeager_cloned::check(cx, expr, recv, recv2, false, false),
2813 ("filter", [arg]) => filter_next::check(cx, expr, recv2, arg),
2814 ("filter_map", [arg]) => filter_map_next::check(cx, expr, recv2, arg, self.msrv),
2815 ("iter", []) => iter_next_slice::check(cx, expr, recv2),
2816 ("skip", [arg]) => iter_skip_next::check(cx, expr, recv2, arg),
2817 ("skip_while", [_]) => skip_while_next::check(cx, expr),
2822 ("nth", [n_arg]) => match method_call(recv) {
2823 Some(("bytes", [recv2], _)) => bytes_nth::check(cx, expr, recv2, n_arg),
2824 Some(("cloned", [recv2], _)) => iter_overeager_cloned::check(cx, expr, recv, recv2, false, false),
2825 Some(("iter", [recv2], _)) => iter_nth::check(cx, expr, recv2, recv, n_arg, false),
2826 Some(("iter_mut", [recv2], _)) => iter_nth::check(cx, expr, recv2, recv, n_arg, true),
2827 _ => iter_nth_zero::check(cx, expr, recv, n_arg),
2829 ("ok_or_else", [arg]) => unnecessary_lazy_eval::check(cx, expr, recv, arg, "ok_or"),
2830 ("or_else", [arg]) => {
2831 if !bind_instead_of_map::ResultOrElseErrInfo::check(cx, expr, recv, arg) {
2832 unnecessary_lazy_eval::check(cx, expr, recv, arg, "or");
2835 ("splitn" | "rsplitn", [count_arg, pat_arg]) => {
2836 if let Some((Constant::Int(count), _)) = constant(cx, cx.typeck_results(), count_arg) {
2837 suspicious_splitn::check(cx, name, expr, recv, count);
2838 str_splitn::check(cx, name, expr, recv, pat_arg, count, self.msrv);
2841 ("splitn_mut" | "rsplitn_mut", [count_arg, _]) => {
2842 if let Some((Constant::Int(count), _)) = constant(cx, cx.typeck_results(), count_arg) {
2843 suspicious_splitn::check(cx, name, expr, recv, count);
2846 ("step_by", [arg]) => iterator_step_by_zero::check(cx, expr, arg),
2847 ("take", [_arg]) => {
2848 if let Some((name2, [recv2, args2 @ ..], _span2)) = method_call(recv) {
2849 if let ("cloned", []) = (name2, args2) {
2850 iter_overeager_cloned::check(cx, expr, recv, recv2, false, false);
2854 ("take", []) => needless_option_take::check(cx, expr, recv),
2855 ("then", [arg]) => {
2856 if !meets_msrv(self.msrv, msrvs::BOOL_THEN_SOME) {
2859 unnecessary_lazy_eval::check(cx, expr, recv, arg, "then_some");
2861 ("to_os_string" | "to_owned" | "to_path_buf" | "to_vec", []) => {
2862 implicit_clone::check(cx, name, expr, recv);
2865 match method_call(recv) {
2866 Some(("get", [recv, get_arg], _)) => {
2867 get_unwrap::check(cx, expr, recv, get_arg, false);
2869 Some(("get_mut", [recv, get_arg], _)) => {
2870 get_unwrap::check(cx, expr, recv, get_arg, true);
2872 Some(("or", [recv, or_arg], or_span)) => {
2873 or_then_unwrap::check(cx, expr, recv, or_arg, or_span);
2877 unwrap_used::check(cx, expr, recv, self.allow_unwrap_in_tests);
2879 ("unwrap_or", [u_arg]) => match method_call(recv) {
2880 Some((arith @ ("checked_add" | "checked_sub" | "checked_mul"), [lhs, rhs], _)) => {
2881 manual_saturating_arithmetic::check(cx, expr, lhs, rhs, u_arg, &arith["checked_".len()..]);
2883 Some(("map", [m_recv, m_arg], span)) => {
2884 option_map_unwrap_or::check(cx, expr, m_recv, m_arg, recv, u_arg, span);
2886 Some(("then_some", [t_recv, t_arg], _)) => {
2887 obfuscated_if_else::check(cx, expr, t_recv, t_arg, u_arg);
2891 ("unwrap_or_else", [u_arg]) => match method_call(recv) {
2892 Some(("map", [recv, map_arg], _))
2893 if map_unwrap_or::check(cx, expr, recv, map_arg, u_arg, self.msrv) => {},
2895 unwrap_or_else_default::check(cx, expr, recv, u_arg);
2896 unnecessary_lazy_eval::check(cx, expr, recv, u_arg, "unwrap_or");
2899 ("replace" | "replacen", [arg1, arg2] | [arg1, arg2, _]) => {
2900 no_effect_replace::check(cx, expr, arg1, arg2);
2908 fn check_is_some_is_none(cx: &LateContext<'_>, expr: &Expr<'_>, recv: &Expr<'_>, is_some: bool) {
2909 if let Some((name @ ("find" | "position" | "rposition"), [f_recv, arg], span)) = method_call(recv) {
2910 search_is_some::check(cx, expr, name, is_some, f_recv, arg, recv, span);
2914 /// Used for `lint_binary_expr_with_method_call`.
2915 #[derive(Copy, Clone)]
2916 struct BinaryExprInfo<'a> {
2917 expr: &'a hir::Expr<'a>,
2918 chain: &'a hir::Expr<'a>,
2919 other: &'a hir::Expr<'a>,
2923 /// Checks for the `CHARS_NEXT_CMP` and `CHARS_LAST_CMP` lints.
2924 fn lint_binary_expr_with_method_call(cx: &LateContext<'_>, info: &mut BinaryExprInfo<'_>) {
2925 macro_rules! lint_with_both_lhs_and_rhs {
2926 ($func:expr, $cx:expr, $info:ident) => {
2927 if !$func($cx, $info) {
2928 ::std::mem::swap(&mut $info.chain, &mut $info.other);
2929 if $func($cx, $info) {
2936 lint_with_both_lhs_and_rhs!(chars_next_cmp::check, cx, info);
2937 lint_with_both_lhs_and_rhs!(chars_last_cmp::check, cx, info);
2938 lint_with_both_lhs_and_rhs!(chars_next_cmp_with_unwrap::check, cx, info);
2939 lint_with_both_lhs_and_rhs!(chars_last_cmp_with_unwrap::check, cx, info);
2942 const FN_HEADER: hir::FnHeader = hir::FnHeader {
2943 unsafety: hir::Unsafety::Normal,
2944 constness: hir::Constness::NotConst,
2945 asyncness: hir::IsAsync::NotAsync,
2946 abi: rustc_target::spec::abi::Abi::Rust,
2949 struct ShouldImplTraitCase {
2950 trait_name: &'static str,
2951 method_name: &'static str,
2953 fn_header: hir::FnHeader,
2954 // implicit self kind expected (none, self, &self, ...)
2955 self_kind: SelfKind,
2956 // checks against the output type
2957 output_type: OutType,
2958 // certain methods with explicit lifetimes can't implement the equivalent trait method
2959 lint_explicit_lifetime: bool,
2961 impl ShouldImplTraitCase {
2963 trait_name: &'static str,
2964 method_name: &'static str,
2966 fn_header: hir::FnHeader,
2967 self_kind: SelfKind,
2968 output_type: OutType,
2969 lint_explicit_lifetime: bool,
2970 ) -> ShouldImplTraitCase {
2971 ShouldImplTraitCase {
2978 lint_explicit_lifetime,
2982 fn lifetime_param_cond(&self, impl_item: &hir::ImplItem<'_>) -> bool {
2983 self.lint_explicit_lifetime
2984 || !impl_item.generics.params.iter().any(|p| {
2987 hir::GenericParamKind::Lifetime {
2988 kind: hir::LifetimeParamKind::Explicit
2996 const TRAIT_METHODS: [ShouldImplTraitCase; 30] = [
2997 ShouldImplTraitCase::new("std::ops::Add", "add", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
2998 ShouldImplTraitCase::new("std::convert::AsMut", "as_mut", 1, FN_HEADER, SelfKind::RefMut, OutType::Ref, true),
2999 ShouldImplTraitCase::new("std::convert::AsRef", "as_ref", 1, FN_HEADER, SelfKind::Ref, OutType::Ref, true),
3000 ShouldImplTraitCase::new("std::ops::BitAnd", "bitand", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3001 ShouldImplTraitCase::new("std::ops::BitOr", "bitor", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3002 ShouldImplTraitCase::new("std::ops::BitXor", "bitxor", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3003 ShouldImplTraitCase::new("std::borrow::Borrow", "borrow", 1, FN_HEADER, SelfKind::Ref, OutType::Ref, true),
3004 ShouldImplTraitCase::new("std::borrow::BorrowMut", "borrow_mut", 1, FN_HEADER, SelfKind::RefMut, OutType::Ref, true),
3005 ShouldImplTraitCase::new("std::clone::Clone", "clone", 1, FN_HEADER, SelfKind::Ref, OutType::Any, true),
3006 ShouldImplTraitCase::new("std::cmp::Ord", "cmp", 2, FN_HEADER, SelfKind::Ref, OutType::Any, true),
3007 // FIXME: default doesn't work
3008 ShouldImplTraitCase::new("std::default::Default", "default", 0, FN_HEADER, SelfKind::No, OutType::Any, true),
3009 ShouldImplTraitCase::new("std::ops::Deref", "deref", 1, FN_HEADER, SelfKind::Ref, OutType::Ref, true),
3010 ShouldImplTraitCase::new("std::ops::DerefMut", "deref_mut", 1, FN_HEADER, SelfKind::RefMut, OutType::Ref, true),
3011 ShouldImplTraitCase::new("std::ops::Div", "div", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3012 ShouldImplTraitCase::new("std::ops::Drop", "drop", 1, FN_HEADER, SelfKind::RefMut, OutType::Unit, true),
3013 ShouldImplTraitCase::new("std::cmp::PartialEq", "eq", 2, FN_HEADER, SelfKind::Ref, OutType::Bool, true),
3014 ShouldImplTraitCase::new("std::iter::FromIterator", "from_iter", 1, FN_HEADER, SelfKind::No, OutType::Any, true),
3015 ShouldImplTraitCase::new("std::str::FromStr", "from_str", 1, FN_HEADER, SelfKind::No, OutType::Any, true),
3016 ShouldImplTraitCase::new("std::hash::Hash", "hash", 2, FN_HEADER, SelfKind::Ref, OutType::Unit, true),
3017 ShouldImplTraitCase::new("std::ops::Index", "index", 2, FN_HEADER, SelfKind::Ref, OutType::Ref, true),
3018 ShouldImplTraitCase::new("std::ops::IndexMut", "index_mut", 2, FN_HEADER, SelfKind::RefMut, OutType::Ref, true),
3019 ShouldImplTraitCase::new("std::iter::IntoIterator", "into_iter", 1, FN_HEADER, SelfKind::Value, OutType::Any, true),
3020 ShouldImplTraitCase::new("std::ops::Mul", "mul", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3021 ShouldImplTraitCase::new("std::ops::Neg", "neg", 1, FN_HEADER, SelfKind::Value, OutType::Any, true),
3022 ShouldImplTraitCase::new("std::iter::Iterator", "next", 1, FN_HEADER, SelfKind::RefMut, OutType::Any, false),
3023 ShouldImplTraitCase::new("std::ops::Not", "not", 1, FN_HEADER, SelfKind::Value, OutType::Any, true),
3024 ShouldImplTraitCase::new("std::ops::Rem", "rem", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3025 ShouldImplTraitCase::new("std::ops::Shl", "shl", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3026 ShouldImplTraitCase::new("std::ops::Shr", "shr", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3027 ShouldImplTraitCase::new("std::ops::Sub", "sub", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3030 #[derive(Clone, Copy, PartialEq, Eq, Debug)]
3039 fn matches<'a>(self, cx: &LateContext<'a>, parent_ty: Ty<'a>, ty: Ty<'a>) -> bool {
3040 fn matches_value<'a>(cx: &LateContext<'a>, parent_ty: Ty<'a>, ty: Ty<'a>) -> bool {
3041 if ty == parent_ty {
3043 } else if ty.is_box() {
3044 ty.boxed_ty() == parent_ty
3045 } else if is_type_diagnostic_item(cx, ty, sym::Rc) || is_type_diagnostic_item(cx, ty, sym::Arc) {
3046 if let ty::Adt(_, substs) = ty.kind() {
3047 substs.types().next().map_or(false, |t| t == parent_ty)
3056 fn matches_ref<'a>(cx: &LateContext<'a>, mutability: hir::Mutability, parent_ty: Ty<'a>, ty: Ty<'a>) -> bool {
3057 if let ty::Ref(_, t, m) = *ty.kind() {
3058 return m == mutability && t == parent_ty;
3061 let trait_path = match mutability {
3062 hir::Mutability::Not => &paths::ASREF_TRAIT,
3063 hir::Mutability::Mut => &paths::ASMUT_TRAIT,
3066 let trait_def_id = match get_trait_def_id(cx, trait_path) {
3068 None => return false,
3070 implements_trait(cx, ty, trait_def_id, &[parent_ty.into()])
3073 fn matches_none<'a>(cx: &LateContext<'a>, parent_ty: Ty<'a>, ty: Ty<'a>) -> bool {
3074 !matches_value(cx, parent_ty, ty)
3075 && !matches_ref(cx, hir::Mutability::Not, parent_ty, ty)
3076 && !matches_ref(cx, hir::Mutability::Mut, parent_ty, ty)
3080 Self::Value => matches_value(cx, parent_ty, ty),
3081 Self::Ref => matches_ref(cx, hir::Mutability::Not, parent_ty, ty) || ty == parent_ty && is_copy(cx, ty),
3082 Self::RefMut => matches_ref(cx, hir::Mutability::Mut, parent_ty, ty),
3083 Self::No => matches_none(cx, parent_ty, ty),
3088 fn description(self) -> &'static str {
3090 Self::Value => "`self` by value",
3091 Self::Ref => "`self` by reference",
3092 Self::RefMut => "`self` by mutable reference",
3093 Self::No => "no `self`",
3098 #[derive(Clone, Copy)]
3107 fn matches(self, ty: &hir::FnRetTy<'_>) -> bool {
3108 let is_unit = |ty: &hir::Ty<'_>| matches!(ty.kind, hir::TyKind::Tup(&[]));
3110 (Self::Unit, &hir::FnRetTy::DefaultReturn(_)) => true,
3111 (Self::Unit, &hir::FnRetTy::Return(ty)) if is_unit(ty) => true,
3112 (Self::Bool, &hir::FnRetTy::Return(ty)) if is_bool(ty) => true,
3113 (Self::Any, &hir::FnRetTy::Return(ty)) if !is_unit(ty) => true,
3114 (Self::Ref, &hir::FnRetTy::Return(ty)) => matches!(ty.kind, hir::TyKind::Rptr(_, _)),
3120 fn is_bool(ty: &hir::Ty<'_>) -> bool {
3121 if let hir::TyKind::Path(QPath::Resolved(_, path)) = ty.kind {
3122 matches!(path.res, Res::PrimTy(PrimTy::Bool))
3128 fn fn_header_equals(expected: hir::FnHeader, actual: hir::FnHeader) -> bool {
3129 expected.constness == actual.constness
3130 && expected.unsafety == actual.unsafety
3131 && expected.asyncness == actual.asyncness