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;
26 mod inefficient_to_string;
29 mod is_digit_ascii_radix;
30 mod iter_cloned_collect;
35 mod iter_overeager_cloned;
38 mod iterator_step_by_zero;
39 mod manual_saturating_arithmetic;
40 mod manual_str_repeat;
41 mod map_collect_result_unit;
45 mod needless_option_as_deref;
46 mod needless_option_take;
48 mod option_as_ref_deref;
49 mod option_map_or_none;
50 mod option_map_unwrap_or;
54 mod single_char_add_str;
55 mod single_char_insert_string;
56 mod single_char_pattern;
57 mod single_char_push_string;
60 mod string_extend_chars;
62 mod suspicious_splitn;
63 mod uninit_assumed_init;
64 mod unnecessary_filter_map;
66 mod unnecessary_iter_cloned;
68 mod unnecessary_lazy_eval;
69 mod unnecessary_to_owned;
70 mod unwrap_or_else_default;
74 mod wrong_self_convention;
77 use bind_instead_of_map::BindInsteadOfMap;
78 use clippy_utils::consts::{constant, Constant};
79 use clippy_utils::diagnostics::{span_lint, span_lint_and_help};
80 use clippy_utils::ty::{contains_adt_constructor, contains_ty, implements_trait, is_copy, is_type_diagnostic_item};
81 use clippy_utils::{contains_return, get_trait_def_id, iter_input_pats, meets_msrv, msrvs, paths, return_ty};
82 use if_chain::if_chain;
84 use rustc_hir::def::Res;
85 use rustc_hir::{Expr, ExprKind, PrimTy, QPath, TraitItem, TraitItemKind};
86 use rustc_lint::{LateContext, LateLintPass, LintContext};
87 use rustc_middle::lint::in_external_macro;
88 use rustc_middle::ty::{self, TraitRef, Ty};
89 use rustc_semver::RustcVersion;
90 use rustc_session::{declare_tool_lint, impl_lint_pass};
91 use rustc_span::{sym, Span};
92 use rustc_typeck::hir_ty_to_ty;
94 declare_clippy_lint! {
96 /// Checks for usages of `cloned()` on an `Iterator` or `Option` where
97 /// `copied()` could be used instead.
99 /// ### Why is this bad?
100 /// `copied()` is better because it guarantees that the type being cloned
101 /// implements `Copy`.
105 /// [1, 2, 3].iter().cloned();
109 /// [1, 2, 3].iter().copied();
111 #[clippy::version = "1.53.0"]
112 pub CLONED_INSTEAD_OF_COPIED,
114 "used `cloned` where `copied` could be used instead"
117 declare_clippy_lint! {
119 /// Checks for usage of `_.cloned().<func>()` where call to `.cloned()` can be postponed.
121 /// ### Why is this bad?
122 /// It's often inefficient to clone all elements of an iterator, when eventually, only some
123 /// of them will be consumed.
127 /// # let vec = vec!["string".to_string()];
130 /// vec.iter().cloned().take(10);
133 /// vec.iter().take(10).cloned();
136 /// vec.iter().cloned().last();
139 /// vec.iter().last().cloned();
142 /// ### Known Problems
143 /// This `lint` removes the side of effect of cloning items in the iterator.
144 /// A code that relies on that side-effect could fail.
146 #[clippy::version = "1.59.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 opt = Some(1);
201 /// opt.expect("more helpful message");
207 /// # let res: Result<usize, ()> = Ok(1);
213 /// res.expect("more helpful message");
215 #[clippy::version = "1.45.0"]
218 "using `.unwrap()` on `Result` or `Option`, which should at least get a better message using `expect()`"
221 declare_clippy_lint! {
223 /// Checks for `.expect()` calls on `Option`s and `Result`s.
225 /// ### Why is this bad?
226 /// Usually it is better to handle the `None` or `Err` case.
227 /// Still, for a lot of quick-and-dirty code, `expect` is a good choice, which is why
228 /// this lint is `Allow` by default.
230 /// `result.expect()` will let the thread panic on `Err`
231 /// values. Normally, you want to implement more sophisticated error handling,
232 /// and propagate errors upwards with `?` operator.
236 /// # let opt = Some(1);
239 /// opt.expect("one");
242 /// let opt = Some(1);
249 /// # let res: Result<usize, ()> = Ok(1);
252 /// res.expect("one");
256 /// # Ok::<(), ()>(())
258 #[clippy::version = "1.45.0"]
261 "using `.expect()` on `Result` or `Option`, which might be better handled"
264 declare_clippy_lint! {
266 /// Checks for methods that should live in a trait
267 /// implementation of a `std` trait (see [llogiq's blog
268 /// post](http://llogiq.github.io/2015/07/30/traits.html) for further
269 /// information) instead of an inherent implementation.
271 /// ### Why is this bad?
272 /// Implementing the traits improve ergonomics for users of
273 /// the code, often with very little cost. Also people seeing a `mul(...)`
275 /// may expect `*` to work equally, so you should have good reason to disappoint
282 /// fn add(&self, other: &X) -> X {
288 #[clippy::version = "pre 1.29.0"]
289 pub SHOULD_IMPLEMENT_TRAIT,
291 "defining a method that should be implementing a std trait"
294 declare_clippy_lint! {
296 /// Checks for methods with certain name prefixes and which
297 /// doesn't match how self is taken. The actual rules are:
299 /// |Prefix |Postfix |`self` taken | `self` type |
300 /// |-------|------------|-----------------------|--------------|
301 /// |`as_` | none |`&self` or `&mut self` | any |
302 /// |`from_`| none | none | any |
303 /// |`into_`| none |`self` | any |
304 /// |`is_` | none |`&self` or none | any |
305 /// |`to_` | `_mut` |`&mut self` | any |
306 /// |`to_` | not `_mut` |`self` | `Copy` |
307 /// |`to_` | not `_mut` |`&self` | not `Copy` |
309 /// Note: Clippy doesn't trigger methods with `to_` prefix in:
310 /// - Traits definition.
311 /// Clippy can not tell if a type that implements a trait is `Copy` or not.
312 /// - Traits implementation, when `&self` is taken.
313 /// The method signature is controlled by the trait and often `&self` is required for all types that implement the trait
314 /// (see e.g. the `std::string::ToString` trait).
316 /// Clippy allows `Pin<&Self>` and `Pin<&mut Self>` if `&self` and `&mut self` is required.
318 /// Please find more info here:
319 /// https://rust-lang.github.io/api-guidelines/naming.html#ad-hoc-conversions-follow-as_-to_-into_-conventions-c-conv
321 /// ### Why is this bad?
322 /// Consistency breeds readability. If you follow the
323 /// conventions, your users won't be surprised that they, e.g., need to supply a
324 /// mutable reference to a `as_..` function.
330 /// fn as_str(self) -> &'static str {
336 #[clippy::version = "pre 1.29.0"]
337 pub WRONG_SELF_CONVENTION,
339 "defining a method named with an established prefix (like \"into_\") that takes `self` with the wrong convention"
342 declare_clippy_lint! {
344 /// Checks for usage of `ok().expect(..)`.
346 /// ### Why is this bad?
347 /// Because you usually call `expect()` on the `Result`
348 /// directly to get a better error message.
350 /// ### Known problems
351 /// The error type needs to implement `Debug`
355 /// # let x = Ok::<_, ()>(());
358 /// x.ok().expect("why did I do this again?");
361 /// x.expect("why did I do this again?");
363 #[clippy::version = "pre 1.29.0"]
366 "using `ok().expect()`, which gives worse error messages than calling `expect` directly on the Result"
369 declare_clippy_lint! {
371 /// Checks for `.err().expect()` calls on the `Result` type.
373 /// ### Why is this bad?
374 /// `.expect_err()` can be called directly to avoid the extra type conversion from `err()`.
378 /// let x: Result<u32, &str> = Ok(10);
379 /// x.err().expect("Testing err().expect()");
383 /// let x: Result<u32, &str> = Ok(10);
384 /// x.expect_err("Testing expect_err");
386 #[clippy::version = "1.61.0"]
389 r#"using `.err().expect("")` when `.expect_err("")` can be used"#
392 declare_clippy_lint! {
394 /// Checks for usages of `_.unwrap_or_else(Default::default)` on `Option` and
397 /// ### Why is this bad?
398 /// Readability, these can be written as `_.unwrap_or_default`, which is
399 /// simpler and more concise.
403 /// # let x = Some(1);
406 /// x.unwrap_or_else(Default::default);
407 /// x.unwrap_or_else(u32::default);
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 x = Some(1);
435 /// x.map(|a| a + 1).unwrap_or(0);
438 /// x.map_or(0, |a| a + 1);
444 /// # let x: Result<usize, ()> = Ok(1);
445 /// # fn some_function(foo: ()) -> usize { 1 }
448 /// x.map(|a| a + 1).unwrap_or_else(some_function);
451 /// x.map_or_else(some_function, |a| a + 1);
453 #[clippy::version = "1.45.0"]
456 "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)`"
459 declare_clippy_lint! {
461 /// Checks for usage of `_.map_or(None, _)`.
463 /// ### Why is this bad?
464 /// Readability, this can be written more concisely as
467 /// ### Known problems
468 /// The order of the arguments is not in execution order.
472 /// # let opt = Some(1);
475 /// opt.map_or(None, |a| Some(a + 1));
478 /// opt.and_then(|a| Some(a + 1));
480 #[clippy::version = "pre 1.29.0"]
481 pub OPTION_MAP_OR_NONE,
483 "using `Option.map_or(None, f)`, which is more succinctly expressed as `and_then(f)`"
486 declare_clippy_lint! {
488 /// Checks for usage of `_.map_or(None, Some)`.
490 /// ### Why is this bad?
491 /// Readability, this can be written more concisely as
497 /// # let r: Result<u32, &str> = Ok(1);
498 /// assert_eq!(Some(1), r.map_or(None, Some));
503 /// # let r: Result<u32, &str> = Ok(1);
504 /// assert_eq!(Some(1), r.ok());
506 #[clippy::version = "1.44.0"]
507 pub RESULT_MAP_OR_INTO_OPTION,
509 "using `Result.map_or(None, Some)`, which is more succinctly expressed as `ok()`"
512 declare_clippy_lint! {
514 /// Checks for usage of `_.and_then(|x| Some(y))`, `_.and_then(|x| Ok(y))` or
515 /// `_.or_else(|x| Err(y))`.
517 /// ### Why is this bad?
518 /// Readability, this can be written more concisely as
519 /// `_.map(|x| y)` or `_.map_err(|x| y)`.
523 /// # fn opt() -> Option<&'static str> { Some("42") }
524 /// # fn res() -> Result<&'static str, &'static str> { Ok("42") }
525 /// let _ = opt().and_then(|s| Some(s.len()));
526 /// let _ = res().and_then(|s| if s.len() == 42 { Ok(10) } else { Ok(20) });
527 /// let _ = res().or_else(|s| if s.len() == 42 { Err(10) } else { Err(20) });
530 /// The correct use would be:
533 /// # fn opt() -> Option<&'static str> { Some("42") }
534 /// # fn res() -> Result<&'static str, &'static str> { Ok("42") }
535 /// let _ = opt().map(|s| s.len());
536 /// let _ = res().map(|s| if s.len() == 42 { 10 } else { 20 });
537 /// let _ = res().map_err(|s| if s.len() == 42 { 10 } else { 20 });
539 #[clippy::version = "1.45.0"]
540 pub BIND_INSTEAD_OF_MAP,
542 "using `Option.and_then(|x| Some(y))`, which is more succinctly expressed as `map(|x| y)`"
545 declare_clippy_lint! {
547 /// Checks for usage of `_.filter(_).next()`.
549 /// ### Why is this bad?
550 /// Readability, this can be written more concisely as
555 /// # let vec = vec![1];
556 /// vec.iter().filter(|x| **x == 0).next();
558 /// Could be written as
560 /// # let vec = vec![1];
561 /// vec.iter().find(|x| **x == 0);
563 #[clippy::version = "pre 1.29.0"]
566 "using `filter(p).next()`, which is more succinctly expressed as `.find(p)`"
569 declare_clippy_lint! {
571 /// Checks for usage of `_.skip_while(condition).next()`.
573 /// ### Why is this bad?
574 /// Readability, this can be written more concisely as
575 /// `_.find(!condition)`.
579 /// # let vec = vec![1];
580 /// vec.iter().skip_while(|x| **x == 0).next();
582 /// Could be written as
584 /// # let vec = vec![1];
585 /// vec.iter().find(|x| **x != 0);
587 #[clippy::version = "1.42.0"]
590 "using `skip_while(p).next()`, which is more succinctly expressed as `.find(!p)`"
593 declare_clippy_lint! {
595 /// Checks for usage of `_.map(_).flatten(_)` on `Iterator` and `Option`
597 /// ### Why is this bad?
598 /// Readability, this can be written more concisely as
599 /// `_.flat_map(_)` for `Iterator` or `_.and_then(_)` for `Option`
603 /// let vec = vec![vec![1]];
604 /// let opt = Some(5);
607 /// vec.iter().map(|x| x.iter()).flatten();
608 /// opt.map(|x| Some(x * 2)).flatten();
611 /// vec.iter().flat_map(|x| x.iter());
612 /// opt.and_then(|x| Some(x * 2));
614 #[clippy::version = "1.31.0"]
617 "using combinations of `flatten` and `map` which can usually be written as a single method call"
620 declare_clippy_lint! {
622 /// Checks for usage of `_.filter(_).map(_)` that can be written more simply
623 /// as `filter_map(_)`.
625 /// ### Why is this bad?
626 /// Redundant code in the `filter` and `map` operations is poor style and
633 /// .filter(|n| n.checked_add(1).is_some())
634 /// .map(|n| n.checked_add(1).unwrap());
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
660 /// .find(|n| n.checked_add(1).is_some())
661 /// .map(|n| n.checked_add(1).unwrap());
666 /// (0_i32..10).find_map(|n| n.checked_add(1));
668 #[clippy::version = "1.51.0"]
671 "using `_.find(_).map(_)` in a way that can be written more simply as `find_map(_)`"
674 declare_clippy_lint! {
676 /// Checks for usage of `_.filter_map(_).next()`.
678 /// ### Why is this bad?
679 /// Readability, this can be written more concisely as
684 /// (0..3).filter_map(|x| if x == 2 { Some(x) } else { None }).next();
686 /// Can be written as
689 /// (0..3).find_map(|x| if x == 2 { Some(x) } else { None });
691 #[clippy::version = "1.36.0"]
694 "using combination of `filter_map` and `next` which can usually be written as a single method call"
697 declare_clippy_lint! {
699 /// Checks for usage of `flat_map(|x| x)`.
701 /// ### Why is this bad?
702 /// Readability, this can be written more concisely by using `flatten`.
706 /// # let iter = vec![vec![0]].into_iter();
707 /// iter.flat_map(|x| x);
709 /// Can be written as
711 /// # let iter = vec![vec![0]].into_iter();
714 #[clippy::version = "1.39.0"]
715 pub FLAT_MAP_IDENTITY,
717 "call to `flat_map` where `flatten` is sufficient"
720 declare_clippy_lint! {
722 /// Checks for an iterator or string search (such as `find()`,
723 /// `position()`, or `rposition()`) followed by a call to `is_some()` or `is_none()`.
725 /// ### Why is this bad?
726 /// Readability, this can be written more concisely as:
727 /// * `_.any(_)`, or `_.contains(_)` for `is_some()`,
728 /// * `!_.any(_)`, or `!_.contains(_)` for `is_none()`.
732 /// let vec = vec![1];
733 /// vec.iter().find(|x| **x == 0).is_some();
735 /// let _ = "hello world".find("world").is_none();
737 /// Could be written as
739 /// let vec = vec![1];
740 /// vec.iter().any(|x| *x == 0);
742 /// let _ = !"hello world".contains("world");
744 #[clippy::version = "pre 1.29.0"]
747 "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()`)"
750 declare_clippy_lint! {
752 /// Checks for usage of `.chars().next()` on a `str` to check
753 /// if it starts with a given char.
755 /// ### Why is this bad?
756 /// Readability, this can be written more concisely as
757 /// `_.starts_with(_)`.
761 /// let name = "foo";
762 /// if name.chars().next() == Some('_') {};
764 /// Could be written as
766 /// let name = "foo";
767 /// if name.starts_with('_') {};
769 #[clippy::version = "pre 1.29.0"]
772 "using `.chars().next()` to check if a string starts with a char"
775 declare_clippy_lint! {
777 /// Checks for calls to `.or(foo(..))`, `.unwrap_or(foo(..))`,
778 /// etc., and suggests to use `or_else`, `unwrap_or_else`, etc., or
779 /// `unwrap_or_default` instead.
781 /// ### Why is this bad?
782 /// The function will always be called and potentially
783 /// allocate an object acting as the default.
785 /// ### Known problems
786 /// If the function has side-effects, not calling it will
787 /// change the semantic of the program, but you shouldn't rely on that anyway.
791 /// # let foo = Some(String::new());
792 /// foo.unwrap_or(String::new());
794 /// this can instead be written:
796 /// # let foo = Some(String::new());
797 /// foo.unwrap_or_else(String::new);
801 /// # let foo = Some(String::new());
802 /// foo.unwrap_or_default();
804 #[clippy::version = "pre 1.29.0"]
807 "using any `*or` method with a function call, which suggests `*or_else`"
810 declare_clippy_lint! {
812 /// Checks for `.or(…).unwrap()` calls to Options and Results.
814 /// ### Why is this bad?
815 /// You should use `.unwrap_or(…)` instead for clarity.
819 /// # let fallback = "fallback";
821 /// # type Error = &'static str;
822 /// # let result: Result<&str, Error> = Err("error");
823 /// let value = result.or::<Error>(Ok(fallback)).unwrap();
826 /// # let option: Option<&str> = None;
827 /// let value = option.or(Some(fallback)).unwrap();
831 /// # let fallback = "fallback";
833 /// # let result: Result<&str, &str> = Err("error");
834 /// let value = result.unwrap_or(fallback);
837 /// # let option: Option<&str> = None;
838 /// let value = option.unwrap_or(fallback);
840 #[clippy::version = "1.61.0"]
843 "checks for `.or(…).unwrap()` calls to Options and Results."
846 declare_clippy_lint! {
848 /// Checks for calls to `.expect(&format!(...))`, `.expect(foo(..))`,
849 /// etc., and suggests to use `unwrap_or_else` instead
851 /// ### Why is this bad?
852 /// The function will always be called.
854 /// ### Known problems
855 /// If the function has side-effects, not calling it will
856 /// change the semantics of the program, but you shouldn't rely on that anyway.
860 /// # let foo = Some(String::new());
861 /// # let err_code = "418";
862 /// # let err_msg = "I'm a teapot";
863 /// foo.expect(&format!("Err {}: {}", err_code, err_msg));
867 /// # let foo = Some(String::new());
868 /// # let err_code = "418";
869 /// # let err_msg = "I'm a teapot";
870 /// foo.expect(format!("Err {}: {}", err_code, err_msg).as_str());
872 /// this can instead be written:
874 /// # let foo = Some(String::new());
875 /// # let err_code = "418";
876 /// # let err_msg = "I'm a teapot";
877 /// foo.unwrap_or_else(|| panic!("Err {}: {}", err_code, err_msg));
879 #[clippy::version = "pre 1.29.0"]
882 "using any `expect` method with a function call"
885 declare_clippy_lint! {
887 /// Checks for usage of `.clone()` on a `Copy` type.
889 /// ### Why is this bad?
890 /// The only reason `Copy` types implement `Clone` is for
891 /// generics, not for using the `clone` method on a concrete type.
897 #[clippy::version = "pre 1.29.0"]
900 "using `clone` on a `Copy` type"
903 declare_clippy_lint! {
905 /// Checks for usage of `.clone()` on a ref-counted pointer,
906 /// (`Rc`, `Arc`, `rc::Weak`, or `sync::Weak`), and suggests calling Clone via unified
907 /// function syntax instead (e.g., `Rc::clone(foo)`).
909 /// ### Why is this bad?
910 /// Calling '.clone()' on an Rc, Arc, or Weak
911 /// can obscure the fact that only the pointer is being cloned, not the underlying
916 /// # use std::rc::Rc;
917 /// let x = Rc::new(1);
925 #[clippy::version = "pre 1.29.0"]
926 pub CLONE_ON_REF_PTR,
928 "using 'clone' on a ref-counted pointer"
931 declare_clippy_lint! {
933 /// Checks for usage of `.clone()` on an `&&T`.
935 /// ### Why is this bad?
936 /// Cloning an `&&T` copies the inner `&T`, instead of
937 /// cloning the underlying `T`.
944 /// let z = y.clone();
945 /// println!("{:p} {:p}", *y, z); // prints out the same pointer
948 #[clippy::version = "pre 1.29.0"]
949 pub CLONE_DOUBLE_REF,
951 "using `clone` on `&&T`"
954 declare_clippy_lint! {
956 /// Checks for usage of `.to_string()` on an `&&T` where
957 /// `T` implements `ToString` directly (like `&&str` or `&&String`).
959 /// ### Why is this bad?
960 /// This bypasses the specialized implementation of
961 /// `ToString` and instead goes through the more expensive string formatting
966 /// // Generic implementation for `T: Display` is used (slow)
967 /// ["foo", "bar"].iter().map(|s| s.to_string());
969 /// // OK, the specialized impl is used
970 /// ["foo", "bar"].iter().map(|&s| s.to_string());
972 #[clippy::version = "1.40.0"]
973 pub INEFFICIENT_TO_STRING,
975 "using `to_string` on `&&T` where `T: ToString`"
978 declare_clippy_lint! {
980 /// Checks for `new` not returning a type that contains `Self`.
982 /// ### Why is this bad?
983 /// As a convention, `new` methods are used to make a new
984 /// instance of a type.
987 /// In an impl block:
990 /// # struct NotAFoo;
992 /// fn new() -> NotAFoo {
1000 /// struct Bar(Foo);
1002 /// // Bad. The type name must contain `Self`
1003 /// fn new() -> Bar {
1011 /// # struct FooError;
1013 /// // Good. Return type contains `Self`
1014 /// fn new() -> Result<Foo, FooError> {
1020 /// Or in a trait definition:
1022 /// pub trait Trait {
1023 /// // Bad. The type name must contain `Self`
1029 /// pub trait Trait {
1030 /// // Good. Return type contains `Self`
1031 /// fn new() -> Self;
1034 #[clippy::version = "pre 1.29.0"]
1035 pub NEW_RET_NO_SELF,
1037 "not returning type containing `Self` in a `new` method"
1040 declare_clippy_lint! {
1041 /// ### What it does
1042 /// Checks for string methods that receive a single-character
1043 /// `str` as an argument, e.g., `_.split("x")`.
1045 /// ### Why is this bad?
1046 /// Performing these methods using a `char` is faster than
1049 /// ### Known problems
1050 /// Does not catch multi-byte unicode characters.
1059 #[clippy::version = "pre 1.29.0"]
1060 pub SINGLE_CHAR_PATTERN,
1062 "using a single-character str where a char could be used, e.g., `_.split(\"x\")`"
1065 declare_clippy_lint! {
1066 /// ### What it does
1067 /// Checks for calling `.step_by(0)` on iterators which panics.
1069 /// ### Why is this bad?
1070 /// This very much looks like an oversight. Use `panic!()` instead if you
1071 /// actually intend to panic.
1074 /// ```rust,should_panic
1075 /// for x in (0..100).step_by(0) {
1079 #[clippy::version = "pre 1.29.0"]
1080 pub ITERATOR_STEP_BY_ZERO,
1082 "using `Iterator::step_by(0)`, which will panic at runtime"
1085 declare_clippy_lint! {
1086 /// ### What it does
1087 /// Checks for indirect collection of populated `Option`
1089 /// ### Why is this bad?
1090 /// `Option` is like a collection of 0-1 things, so `flatten`
1091 /// automatically does this without suspicious-looking `unwrap` calls.
1095 /// let _ = std::iter::empty::<Option<i32>>().filter(Option::is_some).map(Option::unwrap);
1099 /// let _ = std::iter::empty::<Option<i32>>().flatten();
1101 #[clippy::version = "1.53.0"]
1102 pub OPTION_FILTER_MAP,
1104 "filtering `Option` for `Some` then force-unwrapping, which can be one type-safe operation"
1107 declare_clippy_lint! {
1108 /// ### What it does
1109 /// Checks for the use of `iter.nth(0)`.
1111 /// ### Why is this bad?
1112 /// `iter.next()` is equivalent to
1113 /// `iter.nth(0)`, as they both consume the next element,
1114 /// but is more readable.
1118 /// # use std::collections::HashSet;
1120 /// # let mut s = HashSet::new();
1122 /// let x = s.iter().nth(0);
1125 /// # let mut s = HashSet::new();
1127 /// let x = s.iter().next();
1129 #[clippy::version = "1.42.0"]
1132 "replace `iter.nth(0)` with `iter.next()`"
1135 declare_clippy_lint! {
1136 /// ### What it does
1137 /// Checks for use of `.iter().nth()` (and the related
1138 /// `.iter_mut().nth()`) on standard library types with *O*(1) element access.
1140 /// ### Why is this bad?
1141 /// `.get()` and `.get_mut()` are more efficient and more
1146 /// let some_vec = vec![0, 1, 2, 3];
1147 /// let bad_vec = some_vec.iter().nth(3);
1148 /// let bad_slice = &some_vec[..].iter().nth(3);
1150 /// The correct use would be:
1152 /// let some_vec = vec![0, 1, 2, 3];
1153 /// let bad_vec = some_vec.get(3);
1154 /// let bad_slice = &some_vec[..].get(3);
1156 #[clippy::version = "pre 1.29.0"]
1159 "using `.iter().nth()` on a standard library type with O(1) element access"
1162 declare_clippy_lint! {
1163 /// ### What it does
1164 /// Checks for use of `.skip(x).next()` on iterators.
1166 /// ### Why is this bad?
1167 /// `.nth(x)` is cleaner
1171 /// let some_vec = vec![0, 1, 2, 3];
1172 /// let bad_vec = some_vec.iter().skip(3).next();
1173 /// let bad_slice = &some_vec[..].iter().skip(3).next();
1175 /// The correct use would be:
1177 /// let some_vec = vec![0, 1, 2, 3];
1178 /// let bad_vec = some_vec.iter().nth(3);
1179 /// let bad_slice = &some_vec[..].iter().nth(3);
1181 #[clippy::version = "pre 1.29.0"]
1184 "using `.skip(x).next()` on an iterator"
1187 declare_clippy_lint! {
1188 /// ### What it does
1189 /// Checks for use of `.drain(..)` on `Vec` and `VecDeque` for iteration.
1191 /// ### Why is this bad?
1192 /// `.into_iter()` is simpler with better performance.
1196 /// # use std::collections::HashSet;
1197 /// let mut foo = vec![0, 1, 2, 3];
1198 /// let bar: HashSet<usize> = foo.drain(..).collect();
1202 /// # use std::collections::HashSet;
1203 /// let foo = vec![0, 1, 2, 3];
1204 /// let bar: HashSet<usize> = foo.into_iter().collect();
1206 #[clippy::version = "1.61.0"]
1207 pub ITER_WITH_DRAIN,
1209 "replace `.drain(..)` with `.into_iter()`"
1212 declare_clippy_lint! {
1213 /// ### What it does
1214 /// Checks for use of `.get().unwrap()` (or
1215 /// `.get_mut().unwrap`) on a standard library type which implements `Index`
1217 /// ### Why is this bad?
1218 /// Using the Index trait (`[]`) is more clear and more
1221 /// ### Known problems
1222 /// Not a replacement for error handling: Using either
1223 /// `.unwrap()` or the Index trait (`[]`) carries the risk of causing a `panic`
1224 /// if the value being accessed is `None`. If the use of `.get().unwrap()` is a
1225 /// temporary placeholder for dealing with the `Option` type, then this does
1226 /// not mitigate the need for error handling. If there is a chance that `.get()`
1227 /// will be `None` in your program, then it is advisable that the `None` case
1228 /// is handled in a future refactor instead of using `.unwrap()` or the Index
1233 /// let mut some_vec = vec![0, 1, 2, 3];
1234 /// let last = some_vec.get(3).unwrap();
1235 /// *some_vec.get_mut(0).unwrap() = 1;
1237 /// The correct use would be:
1239 /// let mut some_vec = vec![0, 1, 2, 3];
1240 /// let last = some_vec[3];
1241 /// some_vec[0] = 1;
1243 #[clippy::version = "pre 1.29.0"]
1246 "using `.get().unwrap()` or `.get_mut().unwrap()` when using `[]` would work instead"
1249 declare_clippy_lint! {
1250 /// ### What it does
1251 /// Checks for occurrences where one vector gets extended instead of append
1253 /// ### Why is this bad?
1254 /// Using `append` instead of `extend` is more concise and faster
1258 /// let mut a = vec![1, 2, 3];
1259 /// let mut b = vec![4, 5, 6];
1262 /// a.extend(b.drain(..));
1265 /// a.append(&mut b);
1267 #[clippy::version = "1.55.0"]
1268 pub EXTEND_WITH_DRAIN,
1270 "using vec.append(&mut vec) to move the full range of a vector to another"
1273 declare_clippy_lint! {
1274 /// ### What it does
1275 /// Checks for the use of `.extend(s.chars())` where s is a
1276 /// `&str` or `String`.
1278 /// ### Why is this bad?
1279 /// `.push_str(s)` is clearer
1283 /// let abc = "abc";
1284 /// let def = String::from("def");
1285 /// let mut s = String::new();
1286 /// s.extend(abc.chars());
1287 /// s.extend(def.chars());
1289 /// The correct use would be:
1291 /// let abc = "abc";
1292 /// let def = String::from("def");
1293 /// let mut s = String::new();
1294 /// s.push_str(abc);
1295 /// s.push_str(&def);
1297 #[clippy::version = "pre 1.29.0"]
1298 pub STRING_EXTEND_CHARS,
1300 "using `x.extend(s.chars())` where s is a `&str` or `String`"
1303 declare_clippy_lint! {
1304 /// ### What it does
1305 /// Checks for the use of `.cloned().collect()` on slice to
1308 /// ### Why is this bad?
1309 /// `.to_vec()` is clearer
1313 /// let s = [1, 2, 3, 4, 5];
1314 /// let s2: Vec<isize> = s[..].iter().cloned().collect();
1316 /// The better use would be:
1318 /// let s = [1, 2, 3, 4, 5];
1319 /// let s2: Vec<isize> = s.to_vec();
1321 #[clippy::version = "pre 1.29.0"]
1322 pub ITER_CLONED_COLLECT,
1324 "using `.cloned().collect()` on slice to create a `Vec`"
1327 declare_clippy_lint! {
1328 /// ### What it does
1329 /// Checks for usage of `_.chars().last()` or
1330 /// `_.chars().next_back()` on a `str` to check if it ends with a given char.
1332 /// ### Why is this bad?
1333 /// Readability, this can be written more concisely as
1334 /// `_.ends_with(_)`.
1338 /// # let name = "_";
1341 /// name.chars().last() == Some('_') || name.chars().next_back() == Some('-');
1344 /// name.ends_with('_') || name.ends_with('-');
1346 #[clippy::version = "pre 1.29.0"]
1349 "using `.chars().last()` or `.chars().next_back()` to check if a string ends with a char"
1352 declare_clippy_lint! {
1353 /// ### What it does
1354 /// Checks for usage of `.as_ref()` or `.as_mut()` where the
1355 /// types before and after the call are the same.
1357 /// ### Why is this bad?
1358 /// The call is unnecessary.
1362 /// # fn do_stuff(x: &[i32]) {}
1363 /// let x: &[i32] = &[1, 2, 3, 4, 5];
1364 /// do_stuff(x.as_ref());
1366 /// The correct use would be:
1368 /// # fn do_stuff(x: &[i32]) {}
1369 /// let x: &[i32] = &[1, 2, 3, 4, 5];
1372 #[clippy::version = "pre 1.29.0"]
1375 "using `as_ref` where the types before and after the call are the same"
1378 declare_clippy_lint! {
1379 /// ### What it does
1380 /// Checks for using `fold` when a more succinct alternative exists.
1381 /// Specifically, this checks for `fold`s which could be replaced by `any`, `all`,
1382 /// `sum` or `product`.
1384 /// ### Why is this bad?
1389 /// let _ = (0..3).fold(false, |acc, x| acc || x > 2);
1391 /// This could be written as:
1393 /// let _ = (0..3).any(|x| x > 2);
1395 #[clippy::version = "pre 1.29.0"]
1396 pub UNNECESSARY_FOLD,
1398 "using `fold` when a more succinct alternative exists"
1401 declare_clippy_lint! {
1402 /// ### What it does
1403 /// Checks for `filter_map` calls that could be replaced by `filter` or `map`.
1404 /// More specifically it checks if the closure provided is only performing one of the
1405 /// filter or map operations and suggests the appropriate option.
1407 /// ### Why is this bad?
1408 /// Complexity. The intent is also clearer if only a single
1409 /// operation is being performed.
1413 /// let _ = (0..3).filter_map(|x| if x > 2 { Some(x) } else { None });
1415 /// // As there is no transformation of the argument this could be written as:
1416 /// let _ = (0..3).filter(|&x| x > 2);
1420 /// let _ = (0..4).filter_map(|x| Some(x + 1));
1422 /// // As there is no conditional check on the argument this could be written as:
1423 /// let _ = (0..4).map(|x| x + 1);
1425 #[clippy::version = "1.31.0"]
1426 pub UNNECESSARY_FILTER_MAP,
1428 "using `filter_map` when a more succinct alternative exists"
1431 declare_clippy_lint! {
1432 /// ### What it does
1433 /// Checks for `find_map` calls that could be replaced by `find` or `map`. More
1434 /// specifically it checks if the closure provided is only performing one of the
1435 /// find or map operations and suggests the appropriate option.
1437 /// ### Why is this bad?
1438 /// Complexity. The intent is also clearer if only a single
1439 /// operation is being performed.
1443 /// let _ = (0..3).find_map(|x| if x > 2 { Some(x) } else { None });
1445 /// // As there is no transformation of the argument this could be written as:
1446 /// let _ = (0..3).find(|&x| x > 2);
1450 /// let _ = (0..4).find_map(|x| Some(x + 1));
1452 /// // As there is no conditional check on the argument this could be written as:
1453 /// let _ = (0..4).map(|x| x + 1).next();
1455 #[clippy::version = "1.61.0"]
1456 pub UNNECESSARY_FIND_MAP,
1458 "using `find_map` when a more succinct alternative exists"
1461 declare_clippy_lint! {
1462 /// ### What it does
1463 /// Checks for `into_iter` calls on references which should be replaced by `iter`
1466 /// ### Why is this bad?
1467 /// Readability. Calling `into_iter` on a reference will not move out its
1468 /// content into the resulting iterator, which is confusing. It is better just call `iter` or
1469 /// `iter_mut` directly.
1474 /// let _ = (&vec![3, 4, 5]).into_iter();
1477 /// let _ = (&vec![3, 4, 5]).iter();
1479 #[clippy::version = "1.32.0"]
1480 pub INTO_ITER_ON_REF,
1482 "using `.into_iter()` on a reference"
1485 declare_clippy_lint! {
1486 /// ### What it does
1487 /// Checks for calls to `map` followed by a `count`.
1489 /// ### Why is this bad?
1490 /// It looks suspicious. Maybe `map` was confused with `filter`.
1491 /// If the `map` call is intentional, this should be rewritten
1492 /// using `inspect`. Or, if you intend to drive the iterator to
1493 /// completion, you can just use `for_each` instead.
1497 /// let _ = (0..3).map(|x| x + 2).count();
1499 #[clippy::version = "1.39.0"]
1502 "suspicious usage of map"
1505 declare_clippy_lint! {
1506 /// ### What it does
1507 /// Checks for `MaybeUninit::uninit().assume_init()`.
1509 /// ### Why is this bad?
1510 /// For most types, this is undefined behavior.
1512 /// ### Known problems
1513 /// For now, we accept empty tuples and tuples / arrays
1514 /// of `MaybeUninit`. There may be other types that allow uninitialized
1515 /// data, but those are not yet rigorously defined.
1519 /// // Beware the UB
1520 /// use std::mem::MaybeUninit;
1522 /// let _: usize = unsafe { MaybeUninit::uninit().assume_init() };
1525 /// Note that the following is OK:
1528 /// use std::mem::MaybeUninit;
1530 /// let _: [MaybeUninit<bool>; 5] = unsafe {
1531 /// MaybeUninit::uninit().assume_init()
1534 #[clippy::version = "1.39.0"]
1535 pub UNINIT_ASSUMED_INIT,
1537 "`MaybeUninit::uninit().assume_init()`"
1540 declare_clippy_lint! {
1541 /// ### What it does
1542 /// Checks for `.checked_add/sub(x).unwrap_or(MAX/MIN)`.
1544 /// ### Why is this bad?
1545 /// These can be written simply with `saturating_add/sub` methods.
1549 /// # let y: u32 = 0;
1550 /// # let x: u32 = 100;
1551 /// let add = x.checked_add(y).unwrap_or(u32::MAX);
1552 /// let sub = x.checked_sub(y).unwrap_or(u32::MIN);
1555 /// can be written using dedicated methods for saturating addition/subtraction as:
1558 /// # let y: u32 = 0;
1559 /// # let x: u32 = 100;
1560 /// let add = x.saturating_add(y);
1561 /// let sub = x.saturating_sub(y);
1563 #[clippy::version = "1.39.0"]
1564 pub MANUAL_SATURATING_ARITHMETIC,
1566 "`.chcked_add/sub(x).unwrap_or(MAX/MIN)`"
1569 declare_clippy_lint! {
1570 /// ### What it does
1571 /// Checks for `offset(_)`, `wrapping_`{`add`, `sub`}, etc. on raw pointers to
1572 /// zero-sized types
1574 /// ### Why is this bad?
1575 /// This is a no-op, and likely unintended
1579 /// unsafe { (&() as *const ()).offset(1) };
1581 #[clippy::version = "1.41.0"]
1584 "Check for offset calculations on raw pointers to zero-sized types"
1587 declare_clippy_lint! {
1588 /// ### What it does
1589 /// Checks for `FileType::is_file()`.
1591 /// ### Why is this bad?
1592 /// When people testing a file type with `FileType::is_file`
1593 /// they are testing whether a path is something they can get bytes from. But
1594 /// `is_file` doesn't cover special file types in unix-like systems, and doesn't cover
1595 /// symlink in windows. Using `!FileType::is_dir()` is a better way to that intention.
1600 /// let metadata = std::fs::metadata("foo.txt")?;
1601 /// let filetype = metadata.file_type();
1603 /// if filetype.is_file() {
1606 /// # Ok::<_, std::io::Error>(())
1610 /// should be written as:
1614 /// let metadata = std::fs::metadata("foo.txt")?;
1615 /// let filetype = metadata.file_type();
1617 /// if !filetype.is_dir() {
1620 /// # Ok::<_, std::io::Error>(())
1623 #[clippy::version = "1.42.0"]
1624 pub FILETYPE_IS_FILE,
1626 "`FileType::is_file` is not recommended to test for readable file type"
1629 declare_clippy_lint! {
1630 /// ### What it does
1631 /// Checks for usage of `_.as_ref().map(Deref::deref)` or it's aliases (such as String::as_str).
1633 /// ### Why is this bad?
1634 /// Readability, this can be written more concisely as
1639 /// # let opt = Some("".to_string());
1640 /// opt.as_ref().map(String::as_str)
1643 /// Can be written as
1645 /// # let opt = Some("".to_string());
1649 #[clippy::version = "1.42.0"]
1650 pub OPTION_AS_REF_DEREF,
1652 "using `as_ref().map(Deref::deref)`, which is more succinctly expressed as `as_deref()`"
1655 declare_clippy_lint! {
1656 /// ### What it does
1657 /// Checks for usage of `iter().next()` on a Slice or an Array
1659 /// ### Why is this bad?
1660 /// These can be shortened into `.get()`
1664 /// # let a = [1, 2, 3];
1665 /// # let b = vec![1, 2, 3];
1666 /// a[2..].iter().next();
1667 /// b.iter().next();
1669 /// should be written as:
1671 /// # let a = [1, 2, 3];
1672 /// # let b = vec![1, 2, 3];
1676 #[clippy::version = "1.46.0"]
1677 pub ITER_NEXT_SLICE,
1679 "using `.iter().next()` on a sliced array, which can be shortened to just `.get()`"
1682 declare_clippy_lint! {
1683 /// ### What it does
1684 /// Warns when using `push_str`/`insert_str` with a single-character string literal
1685 /// where `push`/`insert` with a `char` would work fine.
1687 /// ### Why is this bad?
1688 /// It's less clear that we are pushing a single character.
1692 /// let mut string = String::new();
1693 /// string.insert_str(0, "R");
1694 /// string.push_str("R");
1696 /// Could be written as
1698 /// let mut string = String::new();
1699 /// string.insert(0, 'R');
1700 /// string.push('R');
1702 #[clippy::version = "1.49.0"]
1703 pub SINGLE_CHAR_ADD_STR,
1705 "`push_str()` or `insert_str()` used with a single-character string literal as parameter"
1708 declare_clippy_lint! {
1709 /// ### What it does
1710 /// As the counterpart to `or_fun_call`, this lint looks for unnecessary
1711 /// lazily evaluated closures on `Option` and `Result`.
1713 /// This lint suggests changing the following functions, when eager evaluation results in
1715 /// - `unwrap_or_else` to `unwrap_or`
1716 /// - `and_then` to `and`
1717 /// - `or_else` to `or`
1718 /// - `get_or_insert_with` to `get_or_insert`
1719 /// - `ok_or_else` to `ok_or`
1721 /// ### Why is this bad?
1722 /// Using eager evaluation is shorter and simpler in some cases.
1724 /// ### Known problems
1725 /// It is possible, but not recommended for `Deref` and `Index` to have
1726 /// side effects. Eagerly evaluating them can change the semantics of the program.
1730 /// // example code where clippy issues a warning
1731 /// let opt: Option<u32> = None;
1733 /// opt.unwrap_or_else(|| 42);
1737 /// let opt: Option<u32> = None;
1739 /// opt.unwrap_or(42);
1741 #[clippy::version = "1.48.0"]
1742 pub UNNECESSARY_LAZY_EVALUATIONS,
1744 "using unnecessary lazy evaluation, which can be replaced with simpler eager evaluation"
1747 declare_clippy_lint! {
1748 /// ### What it does
1749 /// Checks for usage of `_.map(_).collect::<Result<(), _>()`.
1751 /// ### Why is this bad?
1752 /// Using `try_for_each` instead is more readable and idiomatic.
1756 /// (0..3).map(|t| Err(t)).collect::<Result<(), _>>();
1760 /// (0..3).try_for_each(|t| Err(t));
1762 #[clippy::version = "1.49.0"]
1763 pub MAP_COLLECT_RESULT_UNIT,
1765 "using `.map(_).collect::<Result<(),_>()`, which can be replaced with `try_for_each`"
1768 declare_clippy_lint! {
1769 /// ### What it does
1770 /// Checks for `from_iter()` function calls on types that implement the `FromIterator`
1773 /// ### Why is this bad?
1774 /// It is recommended style to use collect. See
1775 /// [FromIterator documentation](https://doc.rust-lang.org/std/iter/trait.FromIterator.html)
1779 /// use std::iter::FromIterator;
1781 /// let five_fives = std::iter::repeat(5).take(5);
1783 /// let v = Vec::from_iter(five_fives);
1785 /// assert_eq!(v, vec![5, 5, 5, 5, 5]);
1789 /// let five_fives = std::iter::repeat(5).take(5);
1791 /// let v: Vec<i32> = five_fives.collect();
1793 /// assert_eq!(v, vec![5, 5, 5, 5, 5]);
1795 #[clippy::version = "1.49.0"]
1796 pub FROM_ITER_INSTEAD_OF_COLLECT,
1798 "use `.collect()` instead of `::from_iter()`"
1801 declare_clippy_lint! {
1802 /// ### What it does
1803 /// Checks for usage of `inspect().for_each()`.
1805 /// ### Why is this bad?
1806 /// It is the same as performing the computation
1807 /// inside `inspect` at the beginning of the closure in `for_each`.
1811 /// [1,2,3,4,5].iter()
1812 /// .inspect(|&x| println!("inspect the number: {}", x))
1813 /// .for_each(|&x| {
1814 /// assert!(x >= 0);
1817 /// Can be written as
1819 /// [1,2,3,4,5].iter()
1820 /// .for_each(|&x| {
1821 /// println!("inspect the number: {}", x);
1822 /// assert!(x >= 0);
1825 #[clippy::version = "1.51.0"]
1826 pub INSPECT_FOR_EACH,
1828 "using `.inspect().for_each()`, which can be replaced with `.for_each()`"
1831 declare_clippy_lint! {
1832 /// ### What it does
1833 /// Checks for usage of `filter_map(|x| x)`.
1835 /// ### Why is this bad?
1836 /// Readability, this can be written more concisely by using `flatten`.
1840 /// # let iter = vec![Some(1)].into_iter();
1841 /// iter.filter_map(|x| x);
1845 /// # let iter = vec![Some(1)].into_iter();
1848 #[clippy::version = "1.52.0"]
1849 pub FILTER_MAP_IDENTITY,
1851 "call to `filter_map` where `flatten` is sufficient"
1854 declare_clippy_lint! {
1855 /// ### What it does
1856 /// Checks for instances of `map(f)` where `f` is the identity function.
1858 /// ### Why is this bad?
1859 /// It can be written more concisely without the call to `map`.
1863 /// let x = [1, 2, 3];
1864 /// let y: Vec<_> = x.iter().map(|x| x).map(|x| 2*x).collect();
1868 /// let x = [1, 2, 3];
1869 /// let y: Vec<_> = x.iter().map(|x| 2*x).collect();
1871 #[clippy::version = "1.52.0"]
1874 "using iterator.map(|x| x)"
1877 declare_clippy_lint! {
1878 /// ### What it does
1879 /// Checks for the use of `.bytes().nth()`.
1881 /// ### Why is this bad?
1882 /// `.as_bytes().get()` is more efficient and more
1888 /// let _ = "Hello".bytes().nth(3);
1891 /// let _ = "Hello".as_bytes().get(3);
1893 #[clippy::version = "1.52.0"]
1896 "replace `.bytes().nth()` with `.as_bytes().get()`"
1899 declare_clippy_lint! {
1900 /// ### What it does
1901 /// Checks for the usage of `_.to_owned()`, `vec.to_vec()`, or similar when calling `_.clone()` would be clearer.
1903 /// ### Why is this bad?
1904 /// These methods do the same thing as `_.clone()` but may be confusing as
1905 /// to why we are calling `to_vec` on something that is already a `Vec` or calling `to_owned` on something that is already owned.
1909 /// let a = vec![1, 2, 3];
1910 /// let b = a.to_vec();
1911 /// let c = a.to_owned();
1915 /// let a = vec![1, 2, 3];
1916 /// let b = a.clone();
1917 /// let c = a.clone();
1919 #[clippy::version = "1.52.0"]
1922 "implicitly cloning a value by invoking a function on its dereferenced type"
1925 declare_clippy_lint! {
1926 /// ### What it does
1927 /// Checks for the use of `.iter().count()`.
1929 /// ### Why is this bad?
1930 /// `.len()` is more efficient and more
1936 /// let some_vec = vec![0, 1, 2, 3];
1937 /// let _ = some_vec.iter().count();
1938 /// let _ = &some_vec[..].iter().count();
1941 /// let some_vec = vec![0, 1, 2, 3];
1942 /// let _ = some_vec.len();
1943 /// let _ = &some_vec[..].len();
1945 #[clippy::version = "1.52.0"]
1948 "replace `.iter().count()` with `.len()`"
1951 declare_clippy_lint! {
1952 /// ### What it does
1953 /// Checks for calls to [`splitn`]
1954 /// (https://doc.rust-lang.org/std/primitive.str.html#method.splitn) and
1955 /// related functions with either zero or one splits.
1957 /// ### Why is this bad?
1958 /// These calls don't actually split the value and are
1959 /// likely to be intended as a different number.
1965 /// for x in s.splitn(1, ":") {
1971 /// for x in s.splitn(2, ":") {
1975 #[clippy::version = "1.54.0"]
1976 pub SUSPICIOUS_SPLITN,
1978 "checks for `.splitn(0, ..)` and `.splitn(1, ..)`"
1981 declare_clippy_lint! {
1982 /// ### What it does
1983 /// Checks for manual implementations of `str::repeat`
1985 /// ### Why is this bad?
1986 /// These are both harder to read, as well as less performant.
1991 /// let x: String = std::iter::repeat('x').take(10).collect();
1994 /// let x: String = "x".repeat(10);
1996 #[clippy::version = "1.54.0"]
1997 pub MANUAL_STR_REPEAT,
1999 "manual implementation of `str::repeat`"
2002 declare_clippy_lint! {
2003 /// ### What it does
2004 /// Checks for usages of `str::splitn(2, _)`
2006 /// ### Why is this bad?
2007 /// `split_once` is both clearer in intent and slightly more efficient.
2012 /// let s = "key=value=add";
2013 /// let (key, value) = s.splitn(2, '=').next_tuple()?;
2014 /// let value = s.splitn(2, '=').nth(1)?;
2016 /// let mut parts = s.splitn(2, '=');
2017 /// let key = parts.next()?;
2018 /// let value = parts.next()?;
2023 /// let s = "key=value=add";
2024 /// let (key, value) = s.split_once('=')?;
2025 /// let value = s.split_once('=')?.1;
2027 /// let (key, value) = s.split_once('=')?;
2031 /// The multiple statement variant currently only detects `iter.next()?`/`iter.next().unwrap()`
2032 /// in two separate `let` statements that immediately follow the `splitn()`
2033 #[clippy::version = "1.57.0"]
2034 pub MANUAL_SPLIT_ONCE,
2036 "replace `.splitn(2, pat)` with `.split_once(pat)`"
2039 declare_clippy_lint! {
2040 /// ### What it does
2041 /// Checks for usages of `str::splitn` (or `str::rsplitn`) where using `str::split` would be the same.
2042 /// ### Why is this bad?
2043 /// The function `split` is simpler and there is no performance difference in these cases, considering
2044 /// that both functions return a lazy iterator.
2048 /// let str = "key=value=add";
2049 /// let _ = str.splitn(3, '=').next().unwrap();
2054 /// let str = "key=value=add";
2055 /// let _ = str.split('=').next().unwrap();
2057 #[clippy::version = "1.58.0"]
2058 pub NEEDLESS_SPLITN,
2060 "usages of `str::splitn` that can be replaced with `str::split`"
2063 declare_clippy_lint! {
2064 /// ### What it does
2065 /// Checks for unnecessary calls to [`ToOwned::to_owned`](https://doc.rust-lang.org/std/borrow/trait.ToOwned.html#tymethod.to_owned)
2066 /// and other `to_owned`-like functions.
2068 /// ### Why is this bad?
2069 /// The unnecessary calls result in useless allocations.
2071 /// ### Known problems
2072 /// `unnecessary_to_owned` can falsely trigger if `IntoIterator::into_iter` is applied to an
2073 /// owned copy of a resource and the resource is later used mutably. See
2074 /// [#8148](https://github.com/rust-lang/rust-clippy/issues/8148).
2078 /// let path = std::path::Path::new("x");
2079 /// foo(&path.to_string_lossy().to_string());
2080 /// fn foo(s: &str) {}
2084 /// let path = std::path::Path::new("x");
2085 /// foo(&path.to_string_lossy());
2086 /// fn foo(s: &str) {}
2088 #[clippy::version = "1.58.0"]
2089 pub UNNECESSARY_TO_OWNED,
2091 "unnecessary calls to `to_owned`-like functions"
2094 declare_clippy_lint! {
2095 /// ### What it does
2096 /// Checks for use of `.collect::<Vec<String>>().join("")` on iterators.
2098 /// ### Why is this bad?
2099 /// `.collect::<String>()` is more concise and might be more performant
2103 /// let vector = vec!["hello", "world"];
2104 /// let output = vector.iter().map(|item| item.to_uppercase()).collect::<Vec<String>>().join("");
2105 /// println!("{}", output);
2107 /// The correct use would be:
2109 /// let vector = vec!["hello", "world"];
2110 /// let output = vector.iter().map(|item| item.to_uppercase()).collect::<String>();
2111 /// println!("{}", output);
2113 /// ### Known problems
2114 /// While `.collect::<String>()` is sometimes more performant, there are cases where
2115 /// using `.collect::<String>()` over `.collect::<Vec<String>>().join("")`
2116 /// will prevent loop unrolling and will result in a negative performance impact.
2118 /// Additionally, differences have been observed between aarch64 and x86_64 assembly output,
2119 /// with aarch64 tending to producing faster assembly in more cases when using `.collect::<String>()`
2120 #[clippy::version = "1.61.0"]
2121 pub UNNECESSARY_JOIN,
2123 "using `.collect::<Vec<String>>().join(\"\")` on an iterator"
2126 declare_clippy_lint! {
2127 /// ### What it does
2128 /// Checks for no-op uses of `Option::{as_deref, as_deref_mut}`,
2129 /// for example, `Option<&T>::as_deref()` returns the same type.
2131 /// ### Why is this bad?
2132 /// Redundant code and improving readability.
2136 /// let a = Some(&1);
2137 /// let b = a.as_deref(); // goes from Option<&i32> to Option<&i32>
2139 /// Could be written as:
2141 /// let a = Some(&1);
2144 #[clippy::version = "1.57.0"]
2145 pub NEEDLESS_OPTION_AS_DEREF,
2147 "no-op use of `deref` or `deref_mut` method to `Option`."
2150 declare_clippy_lint! {
2151 /// ### What it does
2152 /// Finds usages of [`char::is_digit`]
2153 /// (https://doc.rust-lang.org/stable/std/primitive.char.html#method.is_digit) that
2154 /// can be replaced with [`is_ascii_digit`]
2155 /// (https://doc.rust-lang.org/stable/std/primitive.char.html#method.is_ascii_digit) or
2156 /// [`is_ascii_hexdigit`]
2157 /// (https://doc.rust-lang.org/stable/std/primitive.char.html#method.is_ascii_hexdigit).
2159 /// ### Why is this bad?
2160 /// `is_digit(..)` is slower and requires specifying the radix.
2164 /// let c: char = '6';
2170 /// let c: char = '6';
2171 /// c.is_ascii_digit();
2172 /// c.is_ascii_hexdigit();
2174 #[clippy::version = "1.61.0"]
2175 pub IS_DIGIT_ASCII_RADIX,
2177 "use of `char::is_digit(..)` with literal radix of 10 or 16"
2180 declare_clippy_lint! {
2182 /// ### Why is this bad?
2186 /// let x = Some(3);
2187 /// x.as_ref().take();
2191 /// let x = Some(3);
2194 #[clippy::version = "1.61.0"]
2195 pub NEEDLESS_OPTION_TAKE,
2197 "using `.as_ref().take()` on a temporary value"
2200 pub struct Methods {
2201 avoid_breaking_exported_api: bool,
2202 msrv: Option<RustcVersion>,
2207 pub fn new(avoid_breaking_exported_api: bool, msrv: Option<RustcVersion>) -> Self {
2209 avoid_breaking_exported_api,
2215 impl_lint_pass!(Methods => [
2218 SHOULD_IMPLEMENT_TRAIT,
2219 WRONG_SELF_CONVENTION,
2221 UNWRAP_OR_ELSE_DEFAULT,
2223 RESULT_MAP_OR_INTO_OPTION,
2225 BIND_INSTEAD_OF_MAP,
2234 ITER_OVEREAGER_CLONED,
2235 CLONED_INSTEAD_OF_COPIED,
2237 INEFFICIENT_TO_STRING,
2239 SINGLE_CHAR_PATTERN,
2240 SINGLE_CHAR_ADD_STR,
2244 FILTER_MAP_IDENTITY,
2252 ITERATOR_STEP_BY_ZERO,
2260 STRING_EXTEND_CHARS,
2261 ITER_CLONED_COLLECT,
2265 UNNECESSARY_FILTER_MAP,
2266 UNNECESSARY_FIND_MAP,
2269 UNINIT_ASSUMED_INIT,
2270 MANUAL_SATURATING_ARITHMETIC,
2273 OPTION_AS_REF_DEREF,
2274 UNNECESSARY_LAZY_EVALUATIONS,
2275 MAP_COLLECT_RESULT_UNIT,
2276 FROM_ITER_INSTEAD_OF_COLLECT,
2284 UNNECESSARY_TO_OWNED,
2287 NEEDLESS_OPTION_AS_DEREF,
2288 IS_DIGIT_ASCII_RADIX,
2289 NEEDLESS_OPTION_TAKE,
2292 /// Extracts a method call name, args, and `Span` of the method name.
2293 fn method_call<'tcx>(recv: &'tcx hir::Expr<'tcx>) -> Option<(&'tcx str, &'tcx [hir::Expr<'tcx>], Span)> {
2294 if let ExprKind::MethodCall(path, args, _) = recv.kind {
2295 if !args.iter().any(|e| e.span.from_expansion()) {
2296 let name = path.ident.name.as_str();
2297 return Some((name, args, path.ident.span));
2303 impl<'tcx> LateLintPass<'tcx> for Methods {
2304 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) {
2305 if expr.span.from_expansion() {
2309 check_methods(cx, expr, self.msrv.as_ref());
2312 hir::ExprKind::Call(func, args) => {
2313 from_iter_instead_of_collect::check(cx, expr, args, func);
2315 hir::ExprKind::MethodCall(method_call, args, _) => {
2316 let method_span = method_call.ident.span;
2317 or_fun_call::check(cx, expr, method_span, method_call.ident.as_str(), args);
2318 expect_fun_call::check(cx, expr, method_span, method_call.ident.as_str(), args);
2319 clone_on_copy::check(cx, expr, method_call.ident.name, args);
2320 clone_on_ref_ptr::check(cx, expr, method_call.ident.name, args);
2321 inefficient_to_string::check(cx, expr, method_call.ident.name, args);
2322 single_char_add_str::check(cx, expr, args);
2323 into_iter_on_ref::check(cx, expr, method_span, method_call.ident.name, args);
2324 single_char_pattern::check(cx, expr, method_call.ident.name, args);
2325 unnecessary_to_owned::check(cx, expr, method_call.ident.name, args, self.msrv.as_ref());
2327 hir::ExprKind::Binary(op, lhs, rhs) if op.node == hir::BinOpKind::Eq || op.node == hir::BinOpKind::Ne => {
2328 let mut info = BinaryExprInfo {
2332 eq: op.node == hir::BinOpKind::Eq,
2334 lint_binary_expr_with_method_call(cx, &mut info);
2340 #[allow(clippy::too_many_lines)]
2341 fn check_impl_item(&mut self, cx: &LateContext<'tcx>, impl_item: &'tcx hir::ImplItem<'_>) {
2342 if in_external_macro(cx.sess(), impl_item.span) {
2345 let name = impl_item.ident.name.as_str();
2346 let parent = cx.tcx.hir().get_parent_item(impl_item.hir_id());
2347 let item = cx.tcx.hir().expect_item(parent);
2348 let self_ty = cx.tcx.type_of(item.def_id);
2350 let implements_trait = matches!(item.kind, hir::ItemKind::Impl(hir::Impl { of_trait: Some(_), .. }));
2352 if let hir::ImplItemKind::Fn(ref sig, id) = impl_item.kind;
2353 if let Some(first_arg) = iter_input_pats(sig.decl, cx.tcx.hir().body(id)).next();
2355 let method_sig = cx.tcx.fn_sig(impl_item.def_id);
2356 let method_sig = cx.tcx.erase_late_bound_regions(method_sig);
2358 let first_arg_ty = method_sig.inputs().iter().next();
2360 // check conventions w.r.t. conversion method names and predicates
2361 if let Some(first_arg_ty) = first_arg_ty;
2364 // if this impl block implements a trait, lint in trait definition instead
2365 if !implements_trait && cx.access_levels.is_exported(impl_item.def_id) {
2366 // check missing trait implementations
2367 for method_config in &TRAIT_METHODS {
2368 if name == method_config.method_name &&
2369 sig.decl.inputs.len() == method_config.param_count &&
2370 method_config.output_type.matches(&sig.decl.output) &&
2371 method_config.self_kind.matches(cx, self_ty, *first_arg_ty) &&
2372 fn_header_equals(method_config.fn_header, sig.header) &&
2373 method_config.lifetime_param_cond(impl_item)
2377 SHOULD_IMPLEMENT_TRAIT,
2380 "method `{}` can be confused for the standard trait method `{}::{}`",
2381 method_config.method_name,
2382 method_config.trait_name,
2383 method_config.method_name
2387 "consider implementing the trait `{}` or choosing a less ambiguous method name",
2388 method_config.trait_name
2395 if sig.decl.implicit_self.has_implicit_self()
2396 && !(self.avoid_breaking_exported_api
2397 && cx.access_levels.is_exported(impl_item.def_id))
2399 wrong_self_convention::check(
2412 // if this impl block implements a trait, lint in trait definition instead
2413 if implements_trait {
2417 if let hir::ImplItemKind::Fn(_, _) = impl_item.kind {
2418 let ret_ty = return_ty(cx, impl_item.hir_id());
2420 // walk the return type and check for Self (this does not check associated types)
2421 if let Some(self_adt) = self_ty.ty_adt_def() {
2422 if contains_adt_constructor(ret_ty, self_adt) {
2425 } else if contains_ty(ret_ty, self_ty) {
2429 // if return type is impl trait, check the associated types
2430 if let ty::Opaque(def_id, _) = *ret_ty.kind() {
2431 // one of the associated types must be Self
2432 for &(predicate, _span) in cx.tcx.explicit_item_bounds(def_id) {
2433 if let ty::PredicateKind::Projection(projection_predicate) = predicate.kind().skip_binder() {
2434 let assoc_ty = match projection_predicate.term {
2435 ty::Term::Ty(ty) => ty,
2436 ty::Term::Const(_c) => continue,
2438 // walk the associated type and check for Self
2439 if let Some(self_adt) = self_ty.ty_adt_def() {
2440 if contains_adt_constructor(assoc_ty, self_adt) {
2443 } else if contains_ty(assoc_ty, self_ty) {
2450 if name == "new" && ret_ty != self_ty {
2455 "methods called `new` usually return `Self`",
2461 fn check_trait_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx TraitItem<'_>) {
2462 if in_external_macro(cx.tcx.sess, item.span) {
2467 if let TraitItemKind::Fn(ref sig, _) = item.kind;
2468 if sig.decl.implicit_self.has_implicit_self();
2469 if let Some(first_arg_ty) = sig.decl.inputs.iter().next();
2472 let first_arg_span = first_arg_ty.span;
2473 let first_arg_ty = hir_ty_to_ty(cx.tcx, first_arg_ty);
2474 let self_ty = TraitRef::identity(cx.tcx, item.def_id.to_def_id()).self_ty().skip_binder();
2475 wrong_self_convention::check(
2477 item.ident.name.as_str(),
2488 if item.ident.name == sym::new;
2489 if let TraitItemKind::Fn(_, _) = item.kind;
2490 let ret_ty = return_ty(cx, item.hir_id());
2491 let self_ty = TraitRef::identity(cx.tcx, item.def_id.to_def_id()).self_ty().skip_binder();
2492 if !contains_ty(ret_ty, self_ty);
2499 "methods called `new` usually return `Self`",
2505 extract_msrv_attr!(LateContext);
2508 #[allow(clippy::too_many_lines)]
2509 fn check_methods<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, msrv: Option<&RustcVersion>) {
2510 if let Some((name, [recv, args @ ..], span)) = method_call(expr) {
2511 match (name, args) {
2512 ("add" | "offset" | "sub" | "wrapping_offset" | "wrapping_add" | "wrapping_sub", [_arg]) => {
2513 zst_offset::check(cx, expr, recv);
2515 ("and_then", [arg]) => {
2516 let biom_option_linted = bind_instead_of_map::OptionAndThenSome::check(cx, expr, recv, arg);
2517 let biom_result_linted = bind_instead_of_map::ResultAndThenOk::check(cx, expr, recv, arg);
2518 if !biom_option_linted && !biom_result_linted {
2519 unnecessary_lazy_eval::check(cx, expr, recv, arg, "and");
2522 ("as_deref" | "as_deref_mut", []) => {
2523 needless_option_as_deref::check(cx, expr, recv, name);
2525 ("as_mut", []) => useless_asref::check(cx, expr, "as_mut", recv),
2526 ("as_ref", []) => useless_asref::check(cx, expr, "as_ref", recv),
2527 ("assume_init", []) => uninit_assumed_init::check(cx, expr, recv),
2528 ("cloned", []) => cloned_instead_of_copied::check(cx, expr, recv, span, msrv),
2529 ("collect", []) => match method_call(recv) {
2530 Some((name @ ("cloned" | "copied"), [recv2], _)) => {
2531 iter_cloned_collect::check(cx, name, expr, recv2);
2533 Some(("map", [m_recv, m_arg], _)) => {
2534 map_collect_result_unit::check(cx, expr, m_recv, m_arg, recv);
2536 Some(("take", [take_self_arg, take_arg], _)) => {
2537 if meets_msrv(msrv, &msrvs::STR_REPEAT) {
2538 manual_str_repeat::check(cx, expr, recv, take_self_arg, take_arg);
2543 (name @ "count", args @ []) => match method_call(recv) {
2544 Some(("cloned", [recv2], _)) => iter_overeager_cloned::check(cx, expr, recv2, name, args),
2545 Some((name2 @ ("into_iter" | "iter" | "iter_mut"), [recv2], _)) => {
2546 iter_count::check(cx, expr, recv2, name2);
2548 Some(("map", [_, arg], _)) => suspicious_map::check(cx, expr, recv, arg),
2551 ("drain", [arg]) => {
2552 iter_with_drain::check(cx, expr, recv, span, arg);
2554 ("expect", [_]) => match method_call(recv) {
2555 Some(("ok", [recv], _)) => ok_expect::check(cx, expr, recv),
2556 Some(("err", [recv], err_span)) => err_expect::check(cx, expr, recv, msrv, span, err_span),
2557 _ => expect_used::check(cx, expr, recv),
2559 ("extend", [arg]) => {
2560 string_extend_chars::check(cx, expr, recv, arg);
2561 extend_with_drain::check(cx, expr, recv, arg);
2563 ("filter_map", [arg]) => {
2564 unnecessary_filter_map::check(cx, expr, arg, name);
2565 filter_map_identity::check(cx, expr, arg, span);
2567 ("find_map", [arg]) => {
2568 unnecessary_filter_map::check(cx, expr, arg, name);
2570 ("flat_map", [arg]) => {
2571 flat_map_identity::check(cx, expr, arg, span);
2572 flat_map_option::check(cx, expr, arg, span);
2574 (name @ "flatten", args @ []) => match method_call(recv) {
2575 Some(("map", [recv, map_arg], map_span)) => map_flatten::check(cx, expr, recv, map_arg, map_span),
2576 Some(("cloned", [recv2], _)) => iter_overeager_cloned::check(cx, expr, recv2, name, args),
2579 ("fold", [init, acc]) => unnecessary_fold::check(cx, expr, init, acc, span),
2580 ("for_each", [_]) => {
2581 if let Some(("inspect", [_, _], span2)) = method_call(recv) {
2582 inspect_for_each::check(cx, expr, span2);
2585 ("get_or_insert_with", [arg]) => unnecessary_lazy_eval::check(cx, expr, recv, arg, "get_or_insert"),
2586 ("is_file", []) => filetype_is_file::check(cx, expr, recv),
2587 ("is_digit", [radix]) => is_digit_ascii_radix::check(cx, expr, recv, radix, msrv),
2588 ("is_none", []) => check_is_some_is_none(cx, expr, recv, false),
2589 ("is_some", []) => check_is_some_is_none(cx, expr, recv, true),
2590 ("join", [join_arg]) => {
2591 if let Some(("collect", _, span)) = method_call(recv) {
2592 unnecessary_join::check(cx, expr, recv, join_arg, span);
2595 ("last", args @ []) | ("skip", args @ [_]) => {
2596 if let Some((name2, [recv2, args2 @ ..], _span2)) = method_call(recv) {
2597 if let ("cloned", []) = (name2, args2) {
2598 iter_overeager_cloned::check(cx, expr, recv2, name, args);
2602 (name @ ("map" | "map_err"), [m_arg]) => {
2603 if let Some((name, [recv2, args @ ..], span2)) = method_call(recv) {
2604 match (name, args) {
2605 ("as_mut", []) => option_as_ref_deref::check(cx, expr, recv2, m_arg, true, msrv),
2606 ("as_ref", []) => option_as_ref_deref::check(cx, expr, recv2, m_arg, false, msrv),
2607 ("filter", [f_arg]) => {
2608 filter_map::check(cx, expr, recv2, f_arg, span2, recv, m_arg, span, false);
2610 ("find", [f_arg]) => filter_map::check(cx, expr, recv2, f_arg, span2, recv, m_arg, span, true),
2614 map_identity::check(cx, expr, recv, m_arg, name, span);
2616 ("map_or", [def, map]) => option_map_or_none::check(cx, expr, recv, def, map),
2617 (name @ "next", args @ []) => {
2618 if let Some((name2, [recv2, args2 @ ..], _)) = method_call(recv) {
2619 match (name2, args2) {
2620 ("cloned", []) => iter_overeager_cloned::check(cx, expr, recv2, name, args),
2621 ("filter", [arg]) => filter_next::check(cx, expr, recv2, arg),
2622 ("filter_map", [arg]) => filter_map_next::check(cx, expr, recv2, arg, msrv),
2623 ("iter", []) => iter_next_slice::check(cx, expr, recv2),
2624 ("skip", [arg]) => iter_skip_next::check(cx, expr, recv2, arg),
2625 ("skip_while", [_]) => skip_while_next::check(cx, expr),
2630 ("nth", args @ [n_arg]) => match method_call(recv) {
2631 Some(("bytes", [recv2], _)) => bytes_nth::check(cx, expr, recv2, n_arg),
2632 Some(("cloned", [recv2], _)) => iter_overeager_cloned::check(cx, expr, recv2, name, args),
2633 Some(("iter", [recv2], _)) => iter_nth::check(cx, expr, recv2, recv, n_arg, false),
2634 Some(("iter_mut", [recv2], _)) => iter_nth::check(cx, expr, recv2, recv, n_arg, true),
2635 _ => iter_nth_zero::check(cx, expr, recv, n_arg),
2637 ("ok_or_else", [arg]) => unnecessary_lazy_eval::check(cx, expr, recv, arg, "ok_or"),
2638 ("or_else", [arg]) => {
2639 if !bind_instead_of_map::ResultOrElseErrInfo::check(cx, expr, recv, arg) {
2640 unnecessary_lazy_eval::check(cx, expr, recv, arg, "or");
2643 ("splitn" | "rsplitn", [count_arg, pat_arg]) => {
2644 if let Some((Constant::Int(count), _)) = constant(cx, cx.typeck_results(), count_arg) {
2645 suspicious_splitn::check(cx, name, expr, recv, count);
2646 str_splitn::check(cx, name, expr, recv, pat_arg, count, msrv);
2649 ("splitn_mut" | "rsplitn_mut", [count_arg, _]) => {
2650 if let Some((Constant::Int(count), _)) = constant(cx, cx.typeck_results(), count_arg) {
2651 suspicious_splitn::check(cx, name, expr, recv, count);
2654 ("step_by", [arg]) => iterator_step_by_zero::check(cx, expr, arg),
2655 ("take", args @ [_arg]) => {
2656 if let Some((name2, [recv2, args2 @ ..], _span2)) = method_call(recv) {
2657 if let ("cloned", []) = (name2, args2) {
2658 iter_overeager_cloned::check(cx, expr, recv2, name, args);
2662 ("take", []) => needless_option_take::check(cx, expr, recv),
2663 ("to_os_string" | "to_owned" | "to_path_buf" | "to_vec", []) => {
2664 implicit_clone::check(cx, name, expr, recv);
2667 match method_call(recv) {
2668 Some(("get", [recv, get_arg], _)) => {
2669 get_unwrap::check(cx, expr, recv, get_arg, false);
2671 Some(("get_mut", [recv, get_arg], _)) => {
2672 get_unwrap::check(cx, expr, recv, get_arg, true);
2674 Some(("or", [recv, or_arg], or_span)) => {
2675 or_then_unwrap::check(cx, expr, recv, or_arg, or_span);
2679 unwrap_used::check(cx, expr, recv);
2681 ("unwrap_or", [u_arg]) => match method_call(recv) {
2682 Some((arith @ ("checked_add" | "checked_sub" | "checked_mul"), [lhs, rhs], _)) => {
2683 manual_saturating_arithmetic::check(cx, expr, lhs, rhs, u_arg, &arith["checked_".len()..]);
2685 Some(("map", [m_recv, m_arg], span)) => {
2686 option_map_unwrap_or::check(cx, expr, m_recv, m_arg, recv, u_arg, span);
2690 ("unwrap_or_else", [u_arg]) => match method_call(recv) {
2691 Some(("map", [recv, map_arg], _)) if map_unwrap_or::check(cx, expr, recv, map_arg, u_arg, msrv) => {},
2693 unwrap_or_else_default::check(cx, expr, recv, u_arg);
2694 unnecessary_lazy_eval::check(cx, expr, recv, u_arg, "unwrap_or");
2702 fn check_is_some_is_none(cx: &LateContext<'_>, expr: &Expr<'_>, recv: &Expr<'_>, is_some: bool) {
2703 if let Some((name @ ("find" | "position" | "rposition"), [f_recv, arg], span)) = method_call(recv) {
2704 search_is_some::check(cx, expr, name, is_some, f_recv, arg, recv, span);
2708 /// Used for `lint_binary_expr_with_method_call`.
2709 #[derive(Copy, Clone)]
2710 struct BinaryExprInfo<'a> {
2711 expr: &'a hir::Expr<'a>,
2712 chain: &'a hir::Expr<'a>,
2713 other: &'a hir::Expr<'a>,
2717 /// Checks for the `CHARS_NEXT_CMP` and `CHARS_LAST_CMP` lints.
2718 fn lint_binary_expr_with_method_call(cx: &LateContext<'_>, info: &mut BinaryExprInfo<'_>) {
2719 macro_rules! lint_with_both_lhs_and_rhs {
2720 ($func:expr, $cx:expr, $info:ident) => {
2721 if !$func($cx, $info) {
2722 ::std::mem::swap(&mut $info.chain, &mut $info.other);
2723 if $func($cx, $info) {
2730 lint_with_both_lhs_and_rhs!(chars_next_cmp::check, cx, info);
2731 lint_with_both_lhs_and_rhs!(chars_last_cmp::check, cx, info);
2732 lint_with_both_lhs_and_rhs!(chars_next_cmp_with_unwrap::check, cx, info);
2733 lint_with_both_lhs_and_rhs!(chars_last_cmp_with_unwrap::check, cx, info);
2736 const FN_HEADER: hir::FnHeader = hir::FnHeader {
2737 unsafety: hir::Unsafety::Normal,
2738 constness: hir::Constness::NotConst,
2739 asyncness: hir::IsAsync::NotAsync,
2740 abi: rustc_target::spec::abi::Abi::Rust,
2743 struct ShouldImplTraitCase {
2744 trait_name: &'static str,
2745 method_name: &'static str,
2747 fn_header: hir::FnHeader,
2748 // implicit self kind expected (none, self, &self, ...)
2749 self_kind: SelfKind,
2750 // checks against the output type
2751 output_type: OutType,
2752 // certain methods with explicit lifetimes can't implement the equivalent trait method
2753 lint_explicit_lifetime: bool,
2755 impl ShouldImplTraitCase {
2757 trait_name: &'static str,
2758 method_name: &'static str,
2760 fn_header: hir::FnHeader,
2761 self_kind: SelfKind,
2762 output_type: OutType,
2763 lint_explicit_lifetime: bool,
2764 ) -> ShouldImplTraitCase {
2765 ShouldImplTraitCase {
2772 lint_explicit_lifetime,
2776 fn lifetime_param_cond(&self, impl_item: &hir::ImplItem<'_>) -> bool {
2777 self.lint_explicit_lifetime
2778 || !impl_item.generics.params.iter().any(|p| {
2781 hir::GenericParamKind::Lifetime {
2782 kind: hir::LifetimeParamKind::Explicit
2790 const TRAIT_METHODS: [ShouldImplTraitCase; 30] = [
2791 ShouldImplTraitCase::new("std::ops::Add", "add", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
2792 ShouldImplTraitCase::new("std::convert::AsMut", "as_mut", 1, FN_HEADER, SelfKind::RefMut, OutType::Ref, true),
2793 ShouldImplTraitCase::new("std::convert::AsRef", "as_ref", 1, FN_HEADER, SelfKind::Ref, OutType::Ref, true),
2794 ShouldImplTraitCase::new("std::ops::BitAnd", "bitand", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
2795 ShouldImplTraitCase::new("std::ops::BitOr", "bitor", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
2796 ShouldImplTraitCase::new("std::ops::BitXor", "bitxor", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
2797 ShouldImplTraitCase::new("std::borrow::Borrow", "borrow", 1, FN_HEADER, SelfKind::Ref, OutType::Ref, true),
2798 ShouldImplTraitCase::new("std::borrow::BorrowMut", "borrow_mut", 1, FN_HEADER, SelfKind::RefMut, OutType::Ref, true),
2799 ShouldImplTraitCase::new("std::clone::Clone", "clone", 1, FN_HEADER, SelfKind::Ref, OutType::Any, true),
2800 ShouldImplTraitCase::new("std::cmp::Ord", "cmp", 2, FN_HEADER, SelfKind::Ref, OutType::Any, true),
2801 // FIXME: default doesn't work
2802 ShouldImplTraitCase::new("std::default::Default", "default", 0, FN_HEADER, SelfKind::No, OutType::Any, true),
2803 ShouldImplTraitCase::new("std::ops::Deref", "deref", 1, FN_HEADER, SelfKind::Ref, OutType::Ref, true),
2804 ShouldImplTraitCase::new("std::ops::DerefMut", "deref_mut", 1, FN_HEADER, SelfKind::RefMut, OutType::Ref, true),
2805 ShouldImplTraitCase::new("std::ops::Div", "div", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
2806 ShouldImplTraitCase::new("std::ops::Drop", "drop", 1, FN_HEADER, SelfKind::RefMut, OutType::Unit, true),
2807 ShouldImplTraitCase::new("std::cmp::PartialEq", "eq", 2, FN_HEADER, SelfKind::Ref, OutType::Bool, true),
2808 ShouldImplTraitCase::new("std::iter::FromIterator", "from_iter", 1, FN_HEADER, SelfKind::No, OutType::Any, true),
2809 ShouldImplTraitCase::new("std::str::FromStr", "from_str", 1, FN_HEADER, SelfKind::No, OutType::Any, true),
2810 ShouldImplTraitCase::new("std::hash::Hash", "hash", 2, FN_HEADER, SelfKind::Ref, OutType::Unit, true),
2811 ShouldImplTraitCase::new("std::ops::Index", "index", 2, FN_HEADER, SelfKind::Ref, OutType::Ref, true),
2812 ShouldImplTraitCase::new("std::ops::IndexMut", "index_mut", 2, FN_HEADER, SelfKind::RefMut, OutType::Ref, true),
2813 ShouldImplTraitCase::new("std::iter::IntoIterator", "into_iter", 1, FN_HEADER, SelfKind::Value, OutType::Any, true),
2814 ShouldImplTraitCase::new("std::ops::Mul", "mul", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
2815 ShouldImplTraitCase::new("std::ops::Neg", "neg", 1, FN_HEADER, SelfKind::Value, OutType::Any, true),
2816 ShouldImplTraitCase::new("std::iter::Iterator", "next", 1, FN_HEADER, SelfKind::RefMut, OutType::Any, false),
2817 ShouldImplTraitCase::new("std::ops::Not", "not", 1, FN_HEADER, SelfKind::Value, OutType::Any, true),
2818 ShouldImplTraitCase::new("std::ops::Rem", "rem", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
2819 ShouldImplTraitCase::new("std::ops::Shl", "shl", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
2820 ShouldImplTraitCase::new("std::ops::Shr", "shr", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
2821 ShouldImplTraitCase::new("std::ops::Sub", "sub", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
2824 #[derive(Clone, Copy, PartialEq, Debug)]
2833 fn matches<'a>(self, cx: &LateContext<'a>, parent_ty: Ty<'a>, ty: Ty<'a>) -> bool {
2834 fn matches_value<'a>(cx: &LateContext<'a>, parent_ty: Ty<'_>, ty: Ty<'_>) -> bool {
2835 if ty == parent_ty {
2837 } else if ty.is_box() {
2838 ty.boxed_ty() == parent_ty
2839 } else if is_type_diagnostic_item(cx, ty, sym::Rc) || is_type_diagnostic_item(cx, ty, sym::Arc) {
2840 if let ty::Adt(_, substs) = ty.kind() {
2841 substs.types().next().map_or(false, |t| t == parent_ty)
2850 fn matches_ref<'a>(cx: &LateContext<'a>, mutability: hir::Mutability, parent_ty: Ty<'a>, ty: Ty<'a>) -> bool {
2851 if let ty::Ref(_, t, m) = *ty.kind() {
2852 return m == mutability && t == parent_ty;
2855 let trait_path = match mutability {
2856 hir::Mutability::Not => &paths::ASREF_TRAIT,
2857 hir::Mutability::Mut => &paths::ASMUT_TRAIT,
2860 let trait_def_id = match get_trait_def_id(cx, trait_path) {
2862 None => return false,
2864 implements_trait(cx, ty, trait_def_id, &[parent_ty.into()])
2867 fn matches_none<'a>(cx: &LateContext<'a>, parent_ty: Ty<'a>, ty: Ty<'a>) -> bool {
2868 !matches_value(cx, parent_ty, ty)
2869 && !matches_ref(cx, hir::Mutability::Not, parent_ty, ty)
2870 && !matches_ref(cx, hir::Mutability::Mut, parent_ty, ty)
2874 Self::Value => matches_value(cx, parent_ty, ty),
2875 Self::Ref => matches_ref(cx, hir::Mutability::Not, parent_ty, ty) || ty == parent_ty && is_copy(cx, ty),
2876 Self::RefMut => matches_ref(cx, hir::Mutability::Mut, parent_ty, ty),
2877 Self::No => matches_none(cx, parent_ty, ty),
2882 fn description(self) -> &'static str {
2884 Self::Value => "`self` by value",
2885 Self::Ref => "`self` by reference",
2886 Self::RefMut => "`self` by mutable reference",
2887 Self::No => "no `self`",
2892 #[derive(Clone, Copy)]
2901 fn matches(self, ty: &hir::FnRetTy<'_>) -> bool {
2902 let is_unit = |ty: &hir::Ty<'_>| matches!(ty.kind, hir::TyKind::Tup(&[]));
2904 (Self::Unit, &hir::FnRetTy::DefaultReturn(_)) => true,
2905 (Self::Unit, &hir::FnRetTy::Return(ty)) if is_unit(ty) => true,
2906 (Self::Bool, &hir::FnRetTy::Return(ty)) if is_bool(ty) => true,
2907 (Self::Any, &hir::FnRetTy::Return(ty)) if !is_unit(ty) => true,
2908 (Self::Ref, &hir::FnRetTy::Return(ty)) => matches!(ty.kind, hir::TyKind::Rptr(_, _)),
2914 fn is_bool(ty: &hir::Ty<'_>) -> bool {
2915 if let hir::TyKind::Path(QPath::Resolved(_, path)) = ty.kind {
2916 matches!(path.res, Res::PrimTy(PrimTy::Bool))
2922 fn fn_header_equals(expected: hir::FnHeader, actual: hir::FnHeader) -> bool {
2923 expected.constness == actual.constness
2924 && expected.unsafety == actual.unsafety
2925 && expected.asyncness == actual.asyncness