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 iter_cloned_collect;
34 mod iter_overeager_cloned;
37 mod iterator_step_by_zero;
38 mod manual_saturating_arithmetic;
39 mod manual_str_repeat;
40 mod map_collect_result_unit;
44 mod needless_option_as_deref;
46 mod option_as_ref_deref;
47 mod option_map_or_none;
48 mod option_map_unwrap_or;
52 mod single_char_add_str;
53 mod single_char_insert_string;
54 mod single_char_pattern;
55 mod single_char_push_string;
58 mod string_extend_chars;
60 mod suspicious_splitn;
61 mod uninit_assumed_init;
62 mod unnecessary_filter_map;
64 mod unnecessary_iter_cloned;
66 mod unnecessary_lazy_eval;
67 mod unnecessary_to_owned;
68 mod unwrap_or_else_default;
72 mod wrong_self_convention;
75 use bind_instead_of_map::BindInsteadOfMap;
76 use clippy_utils::consts::{constant, Constant};
77 use clippy_utils::diagnostics::{span_lint, span_lint_and_help};
78 use clippy_utils::ty::{contains_adt_constructor, contains_ty, implements_trait, is_copy, is_type_diagnostic_item};
79 use clippy_utils::{contains_return, get_trait_def_id, iter_input_pats, meets_msrv, msrvs, paths, return_ty};
80 use if_chain::if_chain;
82 use rustc_hir::def::Res;
83 use rustc_hir::{Expr, ExprKind, PrimTy, QPath, TraitItem, TraitItemKind};
84 use rustc_lint::{LateContext, LateLintPass, LintContext};
85 use rustc_middle::lint::in_external_macro;
86 use rustc_middle::ty::{self, TraitRef, Ty};
87 use rustc_semver::RustcVersion;
88 use rustc_session::{declare_tool_lint, impl_lint_pass};
89 use rustc_span::{sym, Span};
90 use rustc_typeck::hir_ty_to_ty;
92 declare_clippy_lint! {
94 /// Checks for usages of `cloned()` on an `Iterator` or `Option` where
95 /// `copied()` could be used instead.
97 /// ### Why is this bad?
98 /// `copied()` is better because it guarantees that the type being cloned
99 /// implements `Copy`.
103 /// [1, 2, 3].iter().cloned();
107 /// [1, 2, 3].iter().copied();
109 #[clippy::version = "1.53.0"]
110 pub CLONED_INSTEAD_OF_COPIED,
112 "used `cloned` where `copied` could be used instead"
115 declare_clippy_lint! {
117 /// Checks for usage of `_.cloned().<func>()` where call to `.cloned()` can be postponed.
119 /// ### Why is this bad?
120 /// It's often inefficient to clone all elements of an iterator, when eventually, only some
121 /// of them will be consumed.
125 /// # let vec = vec!["string".to_string()];
128 /// vec.iter().cloned().take(10);
131 /// vec.iter().take(10).cloned();
134 /// vec.iter().cloned().last();
137 /// vec.iter().last().cloned();
140 /// ### Known Problems
141 /// This `lint` removes the side of effect of cloning items in the iterator.
142 /// A code that relies on that side-effect could fail.
144 #[clippy::version = "1.59.0"]
145 pub ITER_OVEREAGER_CLONED,
147 "using `cloned()` early with `Iterator::iter()` can lead to some performance inefficiencies"
150 declare_clippy_lint! {
152 /// Checks for usages of `Iterator::flat_map()` where `filter_map()` could be
155 /// ### Why is this bad?
156 /// When applicable, `filter_map()` is more clear since it shows that
157 /// `Option` is used to produce 0 or 1 items.
161 /// let nums: Vec<i32> = ["1", "2", "whee!"].iter().flat_map(|x| x.parse().ok()).collect();
165 /// let nums: Vec<i32> = ["1", "2", "whee!"].iter().filter_map(|x| x.parse().ok()).collect();
167 #[clippy::version = "1.53.0"]
170 "used `flat_map` where `filter_map` could be used instead"
173 declare_clippy_lint! {
175 /// Checks for `.unwrap()` calls on `Option`s and on `Result`s.
177 /// ### Why is this bad?
178 /// It is better to handle the `None` or `Err` case,
179 /// or at least call `.expect(_)` with a more helpful message. Still, for a lot of
180 /// quick-and-dirty code, `unwrap` is a good choice, which is why this lint is
181 /// `Allow` by default.
183 /// `result.unwrap()` will let the thread panic on `Err` values.
184 /// Normally, you want to implement more sophisticated error handling,
185 /// and propagate errors upwards with `?` operator.
187 /// Even if you want to panic on errors, not all `Error`s implement good
188 /// messages on display. Therefore, it may be beneficial to look at the places
189 /// where they may get displayed. Activate this lint to do just that.
193 /// # let opt = Some(1);
199 /// opt.expect("more helpful message");
205 /// # let res: Result<usize, ()> = Ok(1);
211 /// res.expect("more helpful message");
213 #[clippy::version = "1.45.0"]
216 "using `.unwrap()` on `Result` or `Option`, which should at least get a better message using `expect()`"
219 declare_clippy_lint! {
221 /// Checks for `.expect()` calls on `Option`s and `Result`s.
223 /// ### Why is this bad?
224 /// Usually it is better to handle the `None` or `Err` case.
225 /// Still, for a lot of quick-and-dirty code, `expect` is a good choice, which is why
226 /// this lint is `Allow` by default.
228 /// `result.expect()` will let the thread panic on `Err`
229 /// values. Normally, you want to implement more sophisticated error handling,
230 /// and propagate errors upwards with `?` operator.
234 /// # let opt = Some(1);
237 /// opt.expect("one");
240 /// let opt = Some(1);
247 /// # let res: Result<usize, ()> = Ok(1);
250 /// res.expect("one");
254 /// # Ok::<(), ()>(())
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 |`&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::<_, ()>(());
356 /// x.ok().expect("why did I do this again?");
359 /// x.expect("why did I do this again?");
361 #[clippy::version = "pre 1.29.0"]
364 "using `ok().expect()`, which gives worse error messages than calling `expect` directly on the Result"
367 declare_clippy_lint! {
369 /// Checks for `.err().expect()` calls on the `Result` type.
371 /// ### Why is this bad?
372 /// `.expect_err()` can be called directly to avoid the extra type conversion from `err()`.
376 /// let x: Result<u32, &str> = Ok(10);
377 /// x.err().expect("Testing err().expect()");
381 /// let x: Result<u32, &str> = Ok(10);
382 /// x.expect_err("Testing expect_err");
384 #[clippy::version = "1.61.0"]
387 r#"using `.err().expect("")` when `.expect_err("")` can be used"#
390 declare_clippy_lint! {
392 /// Checks for usages of `_.unwrap_or_else(Default::default)` on `Option` and
395 /// ### Why is this bad?
396 /// Readability, these can be written as `_.unwrap_or_default`, which is
397 /// simpler and more concise.
401 /// # let x = Some(1);
404 /// x.unwrap_or_else(Default::default);
405 /// x.unwrap_or_else(u32::default);
408 /// x.unwrap_or_default();
410 #[clippy::version = "1.56.0"]
411 pub UNWRAP_OR_ELSE_DEFAULT,
413 "using `.unwrap_or_else(Default::default)`, which is more succinctly expressed as `.unwrap_or_default()`"
416 declare_clippy_lint! {
418 /// Checks for usage of `option.map(_).unwrap_or(_)` or `option.map(_).unwrap_or_else(_)` or
419 /// `result.map(_).unwrap_or_else(_)`.
421 /// ### Why is this bad?
422 /// Readability, these can be written more concisely (resp.) as
423 /// `option.map_or(_, _)`, `option.map_or_else(_, _)` and `result.map_or_else(_, _)`.
425 /// ### Known problems
426 /// The order of the arguments is not in execution order
430 /// # let x = Some(1);
433 /// x.map(|a| a + 1).unwrap_or(0);
436 /// x.map_or(0, |a| a + 1);
442 /// # let x: Result<usize, ()> = Ok(1);
443 /// # fn some_function(foo: ()) -> usize { 1 }
446 /// x.map(|a| a + 1).unwrap_or_else(some_function);
449 /// x.map_or_else(some_function, |a| a + 1);
451 #[clippy::version = "1.45.0"]
454 "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)`"
457 declare_clippy_lint! {
459 /// Checks for usage of `_.map_or(None, _)`.
461 /// ### Why is this bad?
462 /// Readability, this can be written more concisely as
465 /// ### Known problems
466 /// The order of the arguments is not in execution order.
470 /// # let opt = Some(1);
473 /// opt.map_or(None, |a| Some(a + 1));
476 /// opt.and_then(|a| Some(a + 1));
478 #[clippy::version = "pre 1.29.0"]
479 pub OPTION_MAP_OR_NONE,
481 "using `Option.map_or(None, f)`, which is more succinctly expressed as `and_then(f)`"
484 declare_clippy_lint! {
486 /// Checks for usage of `_.map_or(None, Some)`.
488 /// ### Why is this bad?
489 /// Readability, this can be written more concisely as
495 /// # let r: Result<u32, &str> = Ok(1);
496 /// assert_eq!(Some(1), r.map_or(None, Some));
501 /// # let r: Result<u32, &str> = Ok(1);
502 /// assert_eq!(Some(1), r.ok());
504 #[clippy::version = "1.44.0"]
505 pub RESULT_MAP_OR_INTO_OPTION,
507 "using `Result.map_or(None, Some)`, which is more succinctly expressed as `ok()`"
510 declare_clippy_lint! {
512 /// Checks for usage of `_.and_then(|x| Some(y))`, `_.and_then(|x| Ok(y))` or
513 /// `_.or_else(|x| Err(y))`.
515 /// ### Why is this bad?
516 /// Readability, this can be written more concisely as
517 /// `_.map(|x| y)` or `_.map_err(|x| y)`.
521 /// # fn opt() -> Option<&'static str> { Some("42") }
522 /// # fn res() -> Result<&'static str, &'static str> { Ok("42") }
523 /// let _ = opt().and_then(|s| Some(s.len()));
524 /// let _ = res().and_then(|s| if s.len() == 42 { Ok(10) } else { Ok(20) });
525 /// let _ = res().or_else(|s| if s.len() == 42 { Err(10) } else { Err(20) });
528 /// The correct use would be:
531 /// # fn opt() -> Option<&'static str> { Some("42") }
532 /// # fn res() -> Result<&'static str, &'static str> { Ok("42") }
533 /// let _ = opt().map(|s| s.len());
534 /// let _ = res().map(|s| if s.len() == 42 { 10 } else { 20 });
535 /// let _ = res().map_err(|s| if s.len() == 42 { 10 } else { 20 });
537 #[clippy::version = "1.45.0"]
538 pub BIND_INSTEAD_OF_MAP,
540 "using `Option.and_then(|x| Some(y))`, which is more succinctly expressed as `map(|x| y)`"
543 declare_clippy_lint! {
545 /// Checks for usage of `_.filter(_).next()`.
547 /// ### Why is this bad?
548 /// Readability, this can be written more concisely as
553 /// # let vec = vec![1];
554 /// vec.iter().filter(|x| **x == 0).next();
556 /// Could be written as
558 /// # let vec = vec![1];
559 /// vec.iter().find(|x| **x == 0);
561 #[clippy::version = "pre 1.29.0"]
564 "using `filter(p).next()`, which is more succinctly expressed as `.find(p)`"
567 declare_clippy_lint! {
569 /// Checks for usage of `_.skip_while(condition).next()`.
571 /// ### Why is this bad?
572 /// Readability, this can be written more concisely as
573 /// `_.find(!condition)`.
577 /// # let vec = vec![1];
578 /// vec.iter().skip_while(|x| **x == 0).next();
580 /// Could be written as
582 /// # let vec = vec![1];
583 /// vec.iter().find(|x| **x != 0);
585 #[clippy::version = "1.42.0"]
588 "using `skip_while(p).next()`, which is more succinctly expressed as `.find(!p)`"
591 declare_clippy_lint! {
593 /// Checks for usage of `_.map(_).flatten(_)` on `Iterator` and `Option`
595 /// ### Why is this bad?
596 /// Readability, this can be written more concisely as
597 /// `_.flat_map(_)` for `Iterator` or `_.and_then(_)` for `Option`
601 /// let vec = vec![vec![1]];
602 /// let opt = Some(5);
605 /// vec.iter().map(|x| x.iter()).flatten();
606 /// opt.map(|x| Some(x * 2)).flatten();
609 /// vec.iter().flat_map(|x| x.iter());
610 /// opt.and_then(|x| Some(x * 2));
612 #[clippy::version = "1.31.0"]
615 "using combinations of `flatten` and `map` which can usually be written as a single method call"
618 declare_clippy_lint! {
620 /// Checks for usage of `_.filter(_).map(_)` that can be written more simply
621 /// as `filter_map(_)`.
623 /// ### Why is this bad?
624 /// Redundant code in the `filter` and `map` operations is poor style and
631 /// .filter(|n| n.checked_add(1).is_some())
632 /// .map(|n| n.checked_add(1).unwrap());
637 /// (0_i32..10).filter_map(|n| n.checked_add(1));
639 #[clippy::version = "1.51.0"]
640 pub MANUAL_FILTER_MAP,
642 "using `_.filter(_).map(_)` in a way that can be written more simply as `filter_map(_)`"
645 declare_clippy_lint! {
647 /// Checks for usage of `_.find(_).map(_)` that can be written more simply
648 /// as `find_map(_)`.
650 /// ### Why is this bad?
651 /// Redundant code in the `find` and `map` operations is poor style and
658 /// .find(|n| n.checked_add(1).is_some())
659 /// .map(|n| n.checked_add(1).unwrap());
664 /// (0_i32..10).find_map(|n| n.checked_add(1));
666 #[clippy::version = "1.51.0"]
669 "using `_.find(_).map(_)` in a way that can be written more simply as `find_map(_)`"
672 declare_clippy_lint! {
674 /// Checks for usage of `_.filter_map(_).next()`.
676 /// ### Why is this bad?
677 /// Readability, this can be written more concisely as
682 /// (0..3).filter_map(|x| if x == 2 { Some(x) } else { None }).next();
684 /// Can be written as
687 /// (0..3).find_map(|x| if x == 2 { Some(x) } else { None });
689 #[clippy::version = "1.36.0"]
692 "using combination of `filter_map` and `next` which can usually be written as a single method call"
695 declare_clippy_lint! {
697 /// Checks for usage of `flat_map(|x| x)`.
699 /// ### Why is this bad?
700 /// Readability, this can be written more concisely by using `flatten`.
704 /// # let iter = vec![vec![0]].into_iter();
705 /// iter.flat_map(|x| x);
707 /// Can be written as
709 /// # let iter = vec![vec![0]].into_iter();
712 #[clippy::version = "1.39.0"]
713 pub FLAT_MAP_IDENTITY,
715 "call to `flat_map` where `flatten` is sufficient"
718 declare_clippy_lint! {
720 /// Checks for an iterator or string search (such as `find()`,
721 /// `position()`, or `rposition()`) followed by a call to `is_some()` or `is_none()`.
723 /// ### Why is this bad?
724 /// Readability, this can be written more concisely as:
725 /// * `_.any(_)`, or `_.contains(_)` for `is_some()`,
726 /// * `!_.any(_)`, or `!_.contains(_)` for `is_none()`.
730 /// let vec = vec![1];
731 /// vec.iter().find(|x| **x == 0).is_some();
733 /// let _ = "hello world".find("world").is_none();
735 /// Could be written as
737 /// let vec = vec![1];
738 /// vec.iter().any(|x| *x == 0);
740 /// let _ = !"hello world".contains("world");
742 #[clippy::version = "pre 1.29.0"]
745 "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()`)"
748 declare_clippy_lint! {
750 /// Checks for usage of `.chars().next()` on a `str` to check
751 /// if it starts with a given char.
753 /// ### Why is this bad?
754 /// Readability, this can be written more concisely as
755 /// `_.starts_with(_)`.
759 /// let name = "foo";
760 /// if name.chars().next() == Some('_') {};
762 /// Could be written as
764 /// let name = "foo";
765 /// if name.starts_with('_') {};
767 #[clippy::version = "pre 1.29.0"]
770 "using `.chars().next()` to check if a string starts with a char"
773 declare_clippy_lint! {
775 /// Checks for calls to `.or(foo(..))`, `.unwrap_or(foo(..))`,
776 /// etc., and suggests to use `or_else`, `unwrap_or_else`, etc., or
777 /// `unwrap_or_default` instead.
779 /// ### Why is this bad?
780 /// The function will always be called and potentially
781 /// allocate an object acting as the default.
783 /// ### Known problems
784 /// If the function has side-effects, not calling it will
785 /// change the semantic of the program, but you shouldn't rely on that anyway.
789 /// # let foo = Some(String::new());
790 /// foo.unwrap_or(String::new());
792 /// this can instead be written:
794 /// # let foo = Some(String::new());
795 /// foo.unwrap_or_else(String::new);
799 /// # let foo = Some(String::new());
800 /// foo.unwrap_or_default();
802 #[clippy::version = "pre 1.29.0"]
805 "using any `*or` method with a function call, which suggests `*or_else`"
808 declare_clippy_lint! {
810 /// Checks for `.or(…).unwrap()` calls to Options and Results.
812 /// ### Why is this bad?
813 /// You should use `.unwrap_or(…)` instead for clarity.
817 /// # let fallback = "fallback";
819 /// # type Error = &'static str;
820 /// # let result: Result<&str, Error> = Err("error");
821 /// let value = result.or::<Error>(Ok(fallback)).unwrap();
824 /// # let option: Option<&str> = None;
825 /// let value = option.or(Some(fallback)).unwrap();
829 /// # let fallback = "fallback";
831 /// # let result: Result<&str, &str> = Err("error");
832 /// let value = result.unwrap_or(fallback);
835 /// # let option: Option<&str> = None;
836 /// let value = option.unwrap_or(fallback);
838 #[clippy::version = "1.61.0"]
841 "checks for `.or(…).unwrap()` calls to Options and Results."
844 declare_clippy_lint! {
846 /// Checks for calls to `.expect(&format!(...))`, `.expect(foo(..))`,
847 /// etc., and suggests to use `unwrap_or_else` instead
849 /// ### Why is this bad?
850 /// The function will always be called.
852 /// ### Known problems
853 /// If the function has side-effects, not calling it will
854 /// change the semantics of the program, but you shouldn't rely on that anyway.
858 /// # let foo = Some(String::new());
859 /// # let err_code = "418";
860 /// # let err_msg = "I'm a teapot";
861 /// foo.expect(&format!("Err {}: {}", err_code, err_msg));
865 /// # let foo = Some(String::new());
866 /// # let err_code = "418";
867 /// # let err_msg = "I'm a teapot";
868 /// foo.expect(format!("Err {}: {}", err_code, err_msg).as_str());
870 /// this can instead be written:
872 /// # let foo = Some(String::new());
873 /// # let err_code = "418";
874 /// # let err_msg = "I'm a teapot";
875 /// foo.unwrap_or_else(|| panic!("Err {}: {}", err_code, err_msg));
877 #[clippy::version = "pre 1.29.0"]
880 "using any `expect` method with a function call"
883 declare_clippy_lint! {
885 /// Checks for usage of `.clone()` on a `Copy` type.
887 /// ### Why is this bad?
888 /// The only reason `Copy` types implement `Clone` is for
889 /// generics, not for using the `clone` method on a concrete type.
895 #[clippy::version = "pre 1.29.0"]
898 "using `clone` on a `Copy` type"
901 declare_clippy_lint! {
903 /// Checks for usage of `.clone()` on a ref-counted pointer,
904 /// (`Rc`, `Arc`, `rc::Weak`, or `sync::Weak`), and suggests calling Clone via unified
905 /// function syntax instead (e.g., `Rc::clone(foo)`).
907 /// ### Why is this bad?
908 /// Calling '.clone()' on an Rc, Arc, or Weak
909 /// can obscure the fact that only the pointer is being cloned, not the underlying
914 /// # use std::rc::Rc;
915 /// let x = Rc::new(1);
923 #[clippy::version = "pre 1.29.0"]
924 pub CLONE_ON_REF_PTR,
926 "using 'clone' on a ref-counted pointer"
929 declare_clippy_lint! {
931 /// Checks for usage of `.clone()` on an `&&T`.
933 /// ### Why is this bad?
934 /// Cloning an `&&T` copies the inner `&T`, instead of
935 /// cloning the underlying `T`.
942 /// let z = y.clone();
943 /// println!("{:p} {:p}", *y, z); // prints out the same pointer
946 #[clippy::version = "pre 1.29.0"]
947 pub CLONE_DOUBLE_REF,
949 "using `clone` on `&&T`"
952 declare_clippy_lint! {
954 /// Checks for usage of `.to_string()` on an `&&T` where
955 /// `T` implements `ToString` directly (like `&&str` or `&&String`).
957 /// ### Why is this bad?
958 /// This bypasses the specialized implementation of
959 /// `ToString` and instead goes through the more expensive string formatting
964 /// // Generic implementation for `T: Display` is used (slow)
965 /// ["foo", "bar"].iter().map(|s| s.to_string());
967 /// // OK, the specialized impl is used
968 /// ["foo", "bar"].iter().map(|&s| s.to_string());
970 #[clippy::version = "1.40.0"]
971 pub INEFFICIENT_TO_STRING,
973 "using `to_string` on `&&T` where `T: ToString`"
976 declare_clippy_lint! {
978 /// Checks for `new` not returning a type that contains `Self`.
980 /// ### Why is this bad?
981 /// As a convention, `new` methods are used to make a new
982 /// instance of a type.
985 /// In an impl block:
988 /// # struct NotAFoo;
990 /// fn new() -> NotAFoo {
1000 /// // Bad. The type name must contain `Self`
1001 /// fn new() -> Bar {
1009 /// # struct FooError;
1011 /// // Good. Return type contains `Self`
1012 /// fn new() -> Result<Foo, FooError> {
1018 /// Or in a trait definition:
1020 /// pub trait Trait {
1021 /// // Bad. The type name must contain `Self`
1027 /// pub trait Trait {
1028 /// // Good. Return type contains `Self`
1029 /// fn new() -> Self;
1032 #[clippy::version = "pre 1.29.0"]
1033 pub NEW_RET_NO_SELF,
1035 "not returning type containing `Self` in a `new` method"
1038 declare_clippy_lint! {
1039 /// ### What it does
1040 /// Checks for string methods that receive a single-character
1041 /// `str` as an argument, e.g., `_.split("x")`.
1043 /// ### Why is this bad?
1044 /// Performing these methods using a `char` is faster than
1047 /// ### Known problems
1048 /// Does not catch multi-byte unicode characters.
1057 #[clippy::version = "pre 1.29.0"]
1058 pub SINGLE_CHAR_PATTERN,
1060 "using a single-character str where a char could be used, e.g., `_.split(\"x\")`"
1063 declare_clippy_lint! {
1064 /// ### What it does
1065 /// Checks for calling `.step_by(0)` on iterators which panics.
1067 /// ### Why is this bad?
1068 /// This very much looks like an oversight. Use `panic!()` instead if you
1069 /// actually intend to panic.
1072 /// ```rust,should_panic
1073 /// for x in (0..100).step_by(0) {
1077 #[clippy::version = "pre 1.29.0"]
1078 pub ITERATOR_STEP_BY_ZERO,
1080 "using `Iterator::step_by(0)`, which will panic at runtime"
1083 declare_clippy_lint! {
1084 /// ### What it does
1085 /// Checks for indirect collection of populated `Option`
1087 /// ### Why is this bad?
1088 /// `Option` is like a collection of 0-1 things, so `flatten`
1089 /// automatically does this without suspicious-looking `unwrap` calls.
1093 /// let _ = std::iter::empty::<Option<i32>>().filter(Option::is_some).map(Option::unwrap);
1097 /// let _ = std::iter::empty::<Option<i32>>().flatten();
1099 #[clippy::version = "1.53.0"]
1100 pub OPTION_FILTER_MAP,
1102 "filtering `Option` for `Some` then force-unwrapping, which can be one type-safe operation"
1105 declare_clippy_lint! {
1106 /// ### What it does
1107 /// Checks for the use of `iter.nth(0)`.
1109 /// ### Why is this bad?
1110 /// `iter.next()` is equivalent to
1111 /// `iter.nth(0)`, as they both consume the next element,
1112 /// but is more readable.
1116 /// # use std::collections::HashSet;
1118 /// # let mut s = HashSet::new();
1120 /// let x = s.iter().nth(0);
1123 /// # let mut s = HashSet::new();
1125 /// let x = s.iter().next();
1127 #[clippy::version = "1.42.0"]
1130 "replace `iter.nth(0)` with `iter.next()`"
1133 declare_clippy_lint! {
1134 /// ### What it does
1135 /// Checks for use of `.iter().nth()` (and the related
1136 /// `.iter_mut().nth()`) on standard library types with *O*(1) element access.
1138 /// ### Why is this bad?
1139 /// `.get()` and `.get_mut()` are more efficient and more
1144 /// let some_vec = vec![0, 1, 2, 3];
1145 /// let bad_vec = some_vec.iter().nth(3);
1146 /// let bad_slice = &some_vec[..].iter().nth(3);
1148 /// The correct use would be:
1150 /// let some_vec = vec![0, 1, 2, 3];
1151 /// let bad_vec = some_vec.get(3);
1152 /// let bad_slice = &some_vec[..].get(3);
1154 #[clippy::version = "pre 1.29.0"]
1157 "using `.iter().nth()` on a standard library type with O(1) element access"
1160 declare_clippy_lint! {
1161 /// ### What it does
1162 /// Checks for use of `.skip(x).next()` on iterators.
1164 /// ### Why is this bad?
1165 /// `.nth(x)` is cleaner
1169 /// let some_vec = vec![0, 1, 2, 3];
1170 /// let bad_vec = some_vec.iter().skip(3).next();
1171 /// let bad_slice = &some_vec[..].iter().skip(3).next();
1173 /// The correct use would be:
1175 /// let some_vec = vec![0, 1, 2, 3];
1176 /// let bad_vec = some_vec.iter().nth(3);
1177 /// let bad_slice = &some_vec[..].iter().nth(3);
1179 #[clippy::version = "pre 1.29.0"]
1182 "using `.skip(x).next()` on an iterator"
1185 declare_clippy_lint! {
1186 /// ### What it does
1187 /// Checks for use of `.drain(..)` on `Vec` and `VecDeque` for iteration.
1189 /// ### Why is this bad?
1190 /// `.into_iter()` is simpler with better performance.
1194 /// # use std::collections::HashSet;
1195 /// let mut foo = vec![0, 1, 2, 3];
1196 /// let bar: HashSet<usize> = foo.drain(..).collect();
1200 /// # use std::collections::HashSet;
1201 /// let foo = vec![0, 1, 2, 3];
1202 /// let bar: HashSet<usize> = foo.into_iter().collect();
1204 #[clippy::version = "1.61.0"]
1205 pub ITER_WITH_DRAIN,
1207 "replace `.drain(..)` with `.into_iter()`"
1210 declare_clippy_lint! {
1211 /// ### What it does
1212 /// Checks for use of `.get().unwrap()` (or
1213 /// `.get_mut().unwrap`) on a standard library type which implements `Index`
1215 /// ### Why is this bad?
1216 /// Using the Index trait (`[]`) is more clear and more
1219 /// ### Known problems
1220 /// Not a replacement for error handling: Using either
1221 /// `.unwrap()` or the Index trait (`[]`) carries the risk of causing a `panic`
1222 /// if the value being accessed is `None`. If the use of `.get().unwrap()` is a
1223 /// temporary placeholder for dealing with the `Option` type, then this does
1224 /// not mitigate the need for error handling. If there is a chance that `.get()`
1225 /// will be `None` in your program, then it is advisable that the `None` case
1226 /// is handled in a future refactor instead of using `.unwrap()` or the Index
1231 /// let mut some_vec = vec![0, 1, 2, 3];
1232 /// let last = some_vec.get(3).unwrap();
1233 /// *some_vec.get_mut(0).unwrap() = 1;
1235 /// The correct use would be:
1237 /// let mut some_vec = vec![0, 1, 2, 3];
1238 /// let last = some_vec[3];
1239 /// some_vec[0] = 1;
1241 #[clippy::version = "pre 1.29.0"]
1244 "using `.get().unwrap()` or `.get_mut().unwrap()` when using `[]` would work instead"
1247 declare_clippy_lint! {
1248 /// ### What it does
1249 /// Checks for occurrences where one vector gets extended instead of append
1251 /// ### Why is this bad?
1252 /// Using `append` instead of `extend` is more concise and faster
1256 /// let mut a = vec![1, 2, 3];
1257 /// let mut b = vec![4, 5, 6];
1260 /// a.extend(b.drain(..));
1263 /// a.append(&mut b);
1265 #[clippy::version = "1.55.0"]
1266 pub EXTEND_WITH_DRAIN,
1268 "using vec.append(&mut vec) to move the full range of a vecor to another"
1271 declare_clippy_lint! {
1272 /// ### What it does
1273 /// Checks for the use of `.extend(s.chars())` where s is a
1274 /// `&str` or `String`.
1276 /// ### Why is this bad?
1277 /// `.push_str(s)` is clearer
1281 /// let abc = "abc";
1282 /// let def = String::from("def");
1283 /// let mut s = String::new();
1284 /// s.extend(abc.chars());
1285 /// s.extend(def.chars());
1287 /// The correct use would be:
1289 /// let abc = "abc";
1290 /// let def = String::from("def");
1291 /// let mut s = String::new();
1292 /// s.push_str(abc);
1293 /// s.push_str(&def);
1295 #[clippy::version = "pre 1.29.0"]
1296 pub STRING_EXTEND_CHARS,
1298 "using `x.extend(s.chars())` where s is a `&str` or `String`"
1301 declare_clippy_lint! {
1302 /// ### What it does
1303 /// Checks for the use of `.cloned().collect()` on slice to
1306 /// ### Why is this bad?
1307 /// `.to_vec()` is clearer
1311 /// let s = [1, 2, 3, 4, 5];
1312 /// let s2: Vec<isize> = s[..].iter().cloned().collect();
1314 /// The better use would be:
1316 /// let s = [1, 2, 3, 4, 5];
1317 /// let s2: Vec<isize> = s.to_vec();
1319 #[clippy::version = "pre 1.29.0"]
1320 pub ITER_CLONED_COLLECT,
1322 "using `.cloned().collect()` on slice to create a `Vec`"
1325 declare_clippy_lint! {
1326 /// ### What it does
1327 /// Checks for usage of `_.chars().last()` or
1328 /// `_.chars().next_back()` on a `str` to check if it ends with a given char.
1330 /// ### Why is this bad?
1331 /// Readability, this can be written more concisely as
1332 /// `_.ends_with(_)`.
1336 /// # let name = "_";
1339 /// name.chars().last() == Some('_') || name.chars().next_back() == Some('-');
1342 /// name.ends_with('_') || name.ends_with('-');
1344 #[clippy::version = "pre 1.29.0"]
1347 "using `.chars().last()` or `.chars().next_back()` to check if a string ends with a char"
1350 declare_clippy_lint! {
1351 /// ### What it does
1352 /// Checks for usage of `.as_ref()` or `.as_mut()` where the
1353 /// types before and after the call are the same.
1355 /// ### Why is this bad?
1356 /// The call is unnecessary.
1360 /// # fn do_stuff(x: &[i32]) {}
1361 /// let x: &[i32] = &[1, 2, 3, 4, 5];
1362 /// do_stuff(x.as_ref());
1364 /// The correct use would be:
1366 /// # fn do_stuff(x: &[i32]) {}
1367 /// let x: &[i32] = &[1, 2, 3, 4, 5];
1370 #[clippy::version = "pre 1.29.0"]
1373 "using `as_ref` where the types before and after the call are the same"
1376 declare_clippy_lint! {
1377 /// ### What it does
1378 /// Checks for using `fold` when a more succinct alternative exists.
1379 /// Specifically, this checks for `fold`s which could be replaced by `any`, `all`,
1380 /// `sum` or `product`.
1382 /// ### Why is this bad?
1387 /// let _ = (0..3).fold(false, |acc, x| acc || x > 2);
1389 /// This could be written as:
1391 /// let _ = (0..3).any(|x| x > 2);
1393 #[clippy::version = "pre 1.29.0"]
1394 pub UNNECESSARY_FOLD,
1396 "using `fold` when a more succinct alternative exists"
1399 declare_clippy_lint! {
1400 /// ### What it does
1401 /// Checks for `filter_map` calls that could be replaced by `filter` or `map`.
1402 /// More specifically it checks if the closure provided is only performing one of the
1403 /// filter or map operations and suggests the appropriate option.
1405 /// ### Why is this bad?
1406 /// Complexity. The intent is also clearer if only a single
1407 /// operation is being performed.
1411 /// let _ = (0..3).filter_map(|x| if x > 2 { Some(x) } else { None });
1413 /// // As there is no transformation of the argument this could be written as:
1414 /// let _ = (0..3).filter(|&x| x > 2);
1418 /// let _ = (0..4).filter_map(|x| Some(x + 1));
1420 /// // As there is no conditional check on the argument this could be written as:
1421 /// let _ = (0..4).map(|x| x + 1);
1423 #[clippy::version = "1.31.0"]
1424 pub UNNECESSARY_FILTER_MAP,
1426 "using `filter_map` when a more succinct alternative exists"
1429 declare_clippy_lint! {
1430 /// ### What it does
1431 /// Checks for `find_map` calls that could be replaced by `find` or `map`. More
1432 /// specifically it checks if the closure provided is only performing one of the
1433 /// find or map operations and suggests the appropriate option.
1435 /// ### Why is this bad?
1436 /// Complexity. The intent is also clearer if only a single
1437 /// operation is being performed.
1441 /// let _ = (0..3).find_map(|x| if x > 2 { Some(x) } else { None });
1443 /// // As there is no transformation of the argument this could be written as:
1444 /// let _ = (0..3).find(|&x| x > 2);
1448 /// let _ = (0..4).find_map(|x| Some(x + 1));
1450 /// // As there is no conditional check on the argument this could be written as:
1451 /// let _ = (0..4).map(|x| x + 1).next();
1453 #[clippy::version = "1.61.0"]
1454 pub UNNECESSARY_FIND_MAP,
1456 "using `find_map` when a more succinct alternative exists"
1459 declare_clippy_lint! {
1460 /// ### What it does
1461 /// Checks for `into_iter` calls on references which should be replaced by `iter`
1464 /// ### Why is this bad?
1465 /// Readability. Calling `into_iter` on a reference will not move out its
1466 /// content into the resulting iterator, which is confusing. It is better just call `iter` or
1467 /// `iter_mut` directly.
1472 /// let _ = (&vec![3, 4, 5]).into_iter();
1475 /// let _ = (&vec![3, 4, 5]).iter();
1477 #[clippy::version = "1.32.0"]
1478 pub INTO_ITER_ON_REF,
1480 "using `.into_iter()` on a reference"
1483 declare_clippy_lint! {
1484 /// ### What it does
1485 /// Checks for calls to `map` followed by a `count`.
1487 /// ### Why is this bad?
1488 /// It looks suspicious. Maybe `map` was confused with `filter`.
1489 /// If the `map` call is intentional, this should be rewritten
1490 /// using `inspect`. Or, if you intend to drive the iterator to
1491 /// completion, you can just use `for_each` instead.
1495 /// let _ = (0..3).map(|x| x + 2).count();
1497 #[clippy::version = "1.39.0"]
1500 "suspicious usage of map"
1503 declare_clippy_lint! {
1504 /// ### What it does
1505 /// Checks for `MaybeUninit::uninit().assume_init()`.
1507 /// ### Why is this bad?
1508 /// For most types, this is undefined behavior.
1510 /// ### Known problems
1511 /// For now, we accept empty tuples and tuples / arrays
1512 /// of `MaybeUninit`. There may be other types that allow uninitialized
1513 /// data, but those are not yet rigorously defined.
1517 /// // Beware the UB
1518 /// use std::mem::MaybeUninit;
1520 /// let _: usize = unsafe { MaybeUninit::uninit().assume_init() };
1523 /// Note that the following is OK:
1526 /// use std::mem::MaybeUninit;
1528 /// let _: [MaybeUninit<bool>; 5] = unsafe {
1529 /// MaybeUninit::uninit().assume_init()
1532 #[clippy::version = "1.39.0"]
1533 pub UNINIT_ASSUMED_INIT,
1535 "`MaybeUninit::uninit().assume_init()`"
1538 declare_clippy_lint! {
1539 /// ### What it does
1540 /// Checks for `.checked_add/sub(x).unwrap_or(MAX/MIN)`.
1542 /// ### Why is this bad?
1543 /// These can be written simply with `saturating_add/sub` methods.
1547 /// # let y: u32 = 0;
1548 /// # let x: u32 = 100;
1549 /// let add = x.checked_add(y).unwrap_or(u32::MAX);
1550 /// let sub = x.checked_sub(y).unwrap_or(u32::MIN);
1553 /// can be written using dedicated methods for saturating addition/subtraction as:
1556 /// # let y: u32 = 0;
1557 /// # let x: u32 = 100;
1558 /// let add = x.saturating_add(y);
1559 /// let sub = x.saturating_sub(y);
1561 #[clippy::version = "1.39.0"]
1562 pub MANUAL_SATURATING_ARITHMETIC,
1564 "`.chcked_add/sub(x).unwrap_or(MAX/MIN)`"
1567 declare_clippy_lint! {
1568 /// ### What it does
1569 /// Checks for `offset(_)`, `wrapping_`{`add`, `sub`}, etc. on raw pointers to
1570 /// zero-sized types
1572 /// ### Why is this bad?
1573 /// This is a no-op, and likely unintended
1577 /// unsafe { (&() as *const ()).offset(1) };
1579 #[clippy::version = "1.41.0"]
1582 "Check for offset calculations on raw pointers to zero-sized types"
1585 declare_clippy_lint! {
1586 /// ### What it does
1587 /// Checks for `FileType::is_file()`.
1589 /// ### Why is this bad?
1590 /// When people testing a file type with `FileType::is_file`
1591 /// they are testing whether a path is something they can get bytes from. But
1592 /// `is_file` doesn't cover special file types in unix-like systems, and doesn't cover
1593 /// symlink in windows. Using `!FileType::is_dir()` is a better way to that intention.
1598 /// let metadata = std::fs::metadata("foo.txt")?;
1599 /// let filetype = metadata.file_type();
1601 /// if filetype.is_file() {
1604 /// # Ok::<_, std::io::Error>(())
1608 /// should be written as:
1612 /// let metadata = std::fs::metadata("foo.txt")?;
1613 /// let filetype = metadata.file_type();
1615 /// if !filetype.is_dir() {
1618 /// # Ok::<_, std::io::Error>(())
1621 #[clippy::version = "1.42.0"]
1622 pub FILETYPE_IS_FILE,
1624 "`FileType::is_file` is not recommended to test for readable file type"
1627 declare_clippy_lint! {
1628 /// ### What it does
1629 /// Checks for usage of `_.as_ref().map(Deref::deref)` or it's aliases (such as String::as_str).
1631 /// ### Why is this bad?
1632 /// Readability, this can be written more concisely as
1637 /// # let opt = Some("".to_string());
1638 /// opt.as_ref().map(String::as_str)
1641 /// Can be written as
1643 /// # let opt = Some("".to_string());
1647 #[clippy::version = "1.42.0"]
1648 pub OPTION_AS_REF_DEREF,
1650 "using `as_ref().map(Deref::deref)`, which is more succinctly expressed as `as_deref()`"
1653 declare_clippy_lint! {
1654 /// ### What it does
1655 /// Checks for usage of `iter().next()` on a Slice or an Array
1657 /// ### Why is this bad?
1658 /// These can be shortened into `.get()`
1662 /// # let a = [1, 2, 3];
1663 /// # let b = vec![1, 2, 3];
1664 /// a[2..].iter().next();
1665 /// b.iter().next();
1667 /// should be written as:
1669 /// # let a = [1, 2, 3];
1670 /// # let b = vec![1, 2, 3];
1674 #[clippy::version = "1.46.0"]
1675 pub ITER_NEXT_SLICE,
1677 "using `.iter().next()` on a sliced array, which can be shortened to just `.get()`"
1680 declare_clippy_lint! {
1681 /// ### What it does
1682 /// Warns when using `push_str`/`insert_str` with a single-character string literal
1683 /// where `push`/`insert` with a `char` would work fine.
1685 /// ### Why is this bad?
1686 /// It's less clear that we are pushing a single character.
1690 /// let mut string = String::new();
1691 /// string.insert_str(0, "R");
1692 /// string.push_str("R");
1694 /// Could be written as
1696 /// let mut string = String::new();
1697 /// string.insert(0, 'R');
1698 /// string.push('R');
1700 #[clippy::version = "1.49.0"]
1701 pub SINGLE_CHAR_ADD_STR,
1703 "`push_str()` or `insert_str()` used with a single-character string literal as parameter"
1706 declare_clippy_lint! {
1707 /// ### What it does
1708 /// As the counterpart to `or_fun_call`, this lint looks for unnecessary
1709 /// lazily evaluated closures on `Option` and `Result`.
1711 /// This lint suggests changing the following functions, when eager evaluation results in
1713 /// - `unwrap_or_else` to `unwrap_or`
1714 /// - `and_then` to `and`
1715 /// - `or_else` to `or`
1716 /// - `get_or_insert_with` to `get_or_insert`
1717 /// - `ok_or_else` to `ok_or`
1719 /// ### Why is this bad?
1720 /// Using eager evaluation is shorter and simpler in some cases.
1722 /// ### Known problems
1723 /// It is possible, but not recommended for `Deref` and `Index` to have
1724 /// side effects. Eagerly evaluating them can change the semantics of the program.
1728 /// // example code where clippy issues a warning
1729 /// let opt: Option<u32> = None;
1731 /// opt.unwrap_or_else(|| 42);
1735 /// let opt: Option<u32> = None;
1737 /// opt.unwrap_or(42);
1739 #[clippy::version = "1.48.0"]
1740 pub UNNECESSARY_LAZY_EVALUATIONS,
1742 "using unnecessary lazy evaluation, which can be replaced with simpler eager evaluation"
1745 declare_clippy_lint! {
1746 /// ### What it does
1747 /// Checks for usage of `_.map(_).collect::<Result<(), _>()`.
1749 /// ### Why is this bad?
1750 /// Using `try_for_each` instead is more readable and idiomatic.
1754 /// (0..3).map(|t| Err(t)).collect::<Result<(), _>>();
1758 /// (0..3).try_for_each(|t| Err(t));
1760 #[clippy::version = "1.49.0"]
1761 pub MAP_COLLECT_RESULT_UNIT,
1763 "using `.map(_).collect::<Result<(),_>()`, which can be replaced with `try_for_each`"
1766 declare_clippy_lint! {
1767 /// ### What it does
1768 /// Checks for `from_iter()` function calls on types that implement the `FromIterator`
1771 /// ### Why is this bad?
1772 /// It is recommended style to use collect. See
1773 /// [FromIterator documentation](https://doc.rust-lang.org/std/iter/trait.FromIterator.html)
1777 /// use std::iter::FromIterator;
1779 /// let five_fives = std::iter::repeat(5).take(5);
1781 /// let v = Vec::from_iter(five_fives);
1783 /// assert_eq!(v, vec![5, 5, 5, 5, 5]);
1787 /// let five_fives = std::iter::repeat(5).take(5);
1789 /// let v: Vec<i32> = five_fives.collect();
1791 /// assert_eq!(v, vec![5, 5, 5, 5, 5]);
1793 #[clippy::version = "1.49.0"]
1794 pub FROM_ITER_INSTEAD_OF_COLLECT,
1796 "use `.collect()` instead of `::from_iter()`"
1799 declare_clippy_lint! {
1800 /// ### What it does
1801 /// Checks for usage of `inspect().for_each()`.
1803 /// ### Why is this bad?
1804 /// It is the same as performing the computation
1805 /// inside `inspect` at the beginning of the closure in `for_each`.
1809 /// [1,2,3,4,5].iter()
1810 /// .inspect(|&x| println!("inspect the number: {}", x))
1811 /// .for_each(|&x| {
1812 /// assert!(x >= 0);
1815 /// Can be written as
1817 /// [1,2,3,4,5].iter()
1818 /// .for_each(|&x| {
1819 /// println!("inspect the number: {}", x);
1820 /// assert!(x >= 0);
1823 #[clippy::version = "1.51.0"]
1824 pub INSPECT_FOR_EACH,
1826 "using `.inspect().for_each()`, which can be replaced with `.for_each()`"
1829 declare_clippy_lint! {
1830 /// ### What it does
1831 /// Checks for usage of `filter_map(|x| x)`.
1833 /// ### Why is this bad?
1834 /// Readability, this can be written more concisely by using `flatten`.
1838 /// # let iter = vec![Some(1)].into_iter();
1839 /// iter.filter_map(|x| x);
1843 /// # let iter = vec![Some(1)].into_iter();
1846 #[clippy::version = "1.52.0"]
1847 pub FILTER_MAP_IDENTITY,
1849 "call to `filter_map` where `flatten` is sufficient"
1852 declare_clippy_lint! {
1853 /// ### What it does
1854 /// Checks for instances of `map(f)` where `f` is the identity function.
1856 /// ### Why is this bad?
1857 /// It can be written more concisely without the call to `map`.
1861 /// let x = [1, 2, 3];
1862 /// let y: Vec<_> = x.iter().map(|x| x).map(|x| 2*x).collect();
1866 /// let x = [1, 2, 3];
1867 /// let y: Vec<_> = x.iter().map(|x| 2*x).collect();
1869 #[clippy::version = "1.52.0"]
1872 "using iterator.map(|x| x)"
1875 declare_clippy_lint! {
1876 /// ### What it does
1877 /// Checks for the use of `.bytes().nth()`.
1879 /// ### Why is this bad?
1880 /// `.as_bytes().get()` is more efficient and more
1886 /// let _ = "Hello".bytes().nth(3);
1889 /// let _ = "Hello".as_bytes().get(3);
1891 #[clippy::version = "1.52.0"]
1894 "replace `.bytes().nth()` with `.as_bytes().get()`"
1897 declare_clippy_lint! {
1898 /// ### What it does
1899 /// Checks for the usage of `_.to_owned()`, `vec.to_vec()`, or similar when calling `_.clone()` would be clearer.
1901 /// ### Why is this bad?
1902 /// These methods do the same thing as `_.clone()` but may be confusing as
1903 /// to why we are calling `to_vec` on something that is already a `Vec` or calling `to_owned` on something that is already owned.
1907 /// let a = vec![1, 2, 3];
1908 /// let b = a.to_vec();
1909 /// let c = a.to_owned();
1913 /// let a = vec![1, 2, 3];
1914 /// let b = a.clone();
1915 /// let c = a.clone();
1917 #[clippy::version = "1.52.0"]
1920 "implicitly cloning a value by invoking a function on its dereferenced type"
1923 declare_clippy_lint! {
1924 /// ### What it does
1925 /// Checks for the use of `.iter().count()`.
1927 /// ### Why is this bad?
1928 /// `.len()` is more efficient and more
1934 /// let some_vec = vec![0, 1, 2, 3];
1935 /// let _ = some_vec.iter().count();
1936 /// let _ = &some_vec[..].iter().count();
1939 /// let some_vec = vec![0, 1, 2, 3];
1940 /// let _ = some_vec.len();
1941 /// let _ = &some_vec[..].len();
1943 #[clippy::version = "1.52.0"]
1946 "replace `.iter().count()` with `.len()`"
1949 declare_clippy_lint! {
1950 /// ### What it does
1951 /// Checks for calls to [`splitn`]
1952 /// (https://doc.rust-lang.org/std/primitive.str.html#method.splitn) and
1953 /// related functions with either zero or one splits.
1955 /// ### Why is this bad?
1956 /// These calls don't actually split the value and are
1957 /// likely to be intended as a different number.
1963 /// for x in s.splitn(1, ":") {
1969 /// for x in s.splitn(2, ":") {
1973 #[clippy::version = "1.54.0"]
1974 pub SUSPICIOUS_SPLITN,
1976 "checks for `.splitn(0, ..)` and `.splitn(1, ..)`"
1979 declare_clippy_lint! {
1980 /// ### What it does
1981 /// Checks for manual implementations of `str::repeat`
1983 /// ### Why is this bad?
1984 /// These are both harder to read, as well as less performant.
1989 /// let x: String = std::iter::repeat('x').take(10).collect();
1992 /// let x: String = "x".repeat(10);
1994 #[clippy::version = "1.54.0"]
1995 pub MANUAL_STR_REPEAT,
1997 "manual implementation of `str::repeat`"
2000 declare_clippy_lint! {
2001 /// ### What it does
2002 /// Checks for usages of `str::splitn(2, _)`
2004 /// ### Why is this bad?
2005 /// `split_once` is both clearer in intent and slightly more efficient.
2010 /// let (key, value) = _.splitn(2, '=').next_tuple()?;
2011 /// let value = _.splitn(2, '=').nth(1)?;
2014 /// let (key, value) = _.split_once('=')?;
2015 /// let value = _.split_once('=')?.1;
2017 #[clippy::version = "1.57.0"]
2018 pub MANUAL_SPLIT_ONCE,
2020 "replace `.splitn(2, pat)` with `.split_once(pat)`"
2023 declare_clippy_lint! {
2024 /// ### What it does
2025 /// Checks for usages of `str::splitn` (or `str::rsplitn`) where using `str::split` would be the same.
2026 /// ### Why is this bad?
2027 /// The function `split` is simpler and there is no performance difference in these cases, considering
2028 /// that both functions return a lazy iterator.
2032 /// let str = "key=value=add";
2033 /// let _ = str.splitn(3, '=').next().unwrap();
2038 /// let str = "key=value=add";
2039 /// let _ = str.split('=').next().unwrap();
2041 #[clippy::version = "1.58.0"]
2042 pub NEEDLESS_SPLITN,
2044 "usages of `str::splitn` that can be replaced with `str::split`"
2047 declare_clippy_lint! {
2048 /// ### What it does
2049 /// Checks for unnecessary calls to [`ToOwned::to_owned`](https://doc.rust-lang.org/std/borrow/trait.ToOwned.html#tymethod.to_owned)
2050 /// and other `to_owned`-like functions.
2052 /// ### Why is this bad?
2053 /// The unnecessary calls result in useless allocations.
2055 /// ### Known problems
2056 /// `unnecessary_to_owned` can falsely trigger if `IntoIterator::into_iter` is applied to an
2057 /// owned copy of a resource and the resource is later used mutably. See
2058 /// [#8148](https://github.com/rust-lang/rust-clippy/issues/8148).
2062 /// let path = std::path::Path::new("x");
2063 /// foo(&path.to_string_lossy().to_string());
2064 /// fn foo(s: &str) {}
2068 /// let path = std::path::Path::new("x");
2069 /// foo(&path.to_string_lossy());
2070 /// fn foo(s: &str) {}
2072 #[clippy::version = "1.58.0"]
2073 pub UNNECESSARY_TO_OWNED,
2075 "unnecessary calls to `to_owned`-like functions"
2078 declare_clippy_lint! {
2079 /// ### What it does
2080 /// Checks for use of `.collect::<Vec<String>>().join("")` on iterators.
2082 /// ### Why is this bad?
2083 /// `.collect::<String>()` is more concise and might be more performant
2087 /// let vector = vec!["hello", "world"];
2088 /// let output = vector.iter().map(|item| item.to_uppercase()).collect::<Vec<String>>().join("");
2089 /// println!("{}", output);
2091 /// The correct use would be:
2093 /// let vector = vec!["hello", "world"];
2094 /// let output = vector.iter().map(|item| item.to_uppercase()).collect::<String>();
2095 /// println!("{}", output);
2097 /// ### Known problems
2098 /// While `.collect::<String>()` is sometimes more performant, there are cases where
2099 /// using `.collect::<String>()` over `.collect::<Vec<String>>().join("")`
2100 /// will prevent loop unrolling and will result in a negative performance impact.
2102 /// Additionlly, differences have been observed between aarch64 and x86_64 assembly output,
2103 /// with aarch64 tending to producing faster assembly in more cases when using `.collect::<String>()`
2104 #[clippy::version = "1.61.0"]
2105 pub UNNECESSARY_JOIN,
2107 "using `.collect::<Vec<String>>().join(\"\")` on an iterator"
2110 declare_clippy_lint! {
2111 /// ### What it does
2112 /// Checks for no-op uses of `Option::{as_deref, as_deref_mut}`,
2113 /// for example, `Option<&T>::as_deref()` returns the same type.
2115 /// ### Why is this bad?
2116 /// Redundant code and improving readability.
2120 /// let a = Some(&1);
2121 /// let b = a.as_deref(); // goes from Option<&i32> to Option<&i32>
2123 /// Could be written as:
2125 /// let a = Some(&1);
2128 #[clippy::version = "1.57.0"]
2129 pub NEEDLESS_OPTION_AS_DEREF,
2131 "no-op use of `deref` or `deref_mut` method to `Option`."
2134 pub struct Methods {
2135 avoid_breaking_exported_api: bool,
2136 msrv: Option<RustcVersion>,
2141 pub fn new(avoid_breaking_exported_api: bool, msrv: Option<RustcVersion>) -> Self {
2143 avoid_breaking_exported_api,
2149 impl_lint_pass!(Methods => [
2152 SHOULD_IMPLEMENT_TRAIT,
2153 WRONG_SELF_CONVENTION,
2155 UNWRAP_OR_ELSE_DEFAULT,
2157 RESULT_MAP_OR_INTO_OPTION,
2159 BIND_INSTEAD_OF_MAP,
2168 ITER_OVEREAGER_CLONED,
2169 CLONED_INSTEAD_OF_COPIED,
2171 INEFFICIENT_TO_STRING,
2173 SINGLE_CHAR_PATTERN,
2174 SINGLE_CHAR_ADD_STR,
2178 FILTER_MAP_IDENTITY,
2186 ITERATOR_STEP_BY_ZERO,
2194 STRING_EXTEND_CHARS,
2195 ITER_CLONED_COLLECT,
2199 UNNECESSARY_FILTER_MAP,
2200 UNNECESSARY_FIND_MAP,
2203 UNINIT_ASSUMED_INIT,
2204 MANUAL_SATURATING_ARITHMETIC,
2207 OPTION_AS_REF_DEREF,
2208 UNNECESSARY_LAZY_EVALUATIONS,
2209 MAP_COLLECT_RESULT_UNIT,
2210 FROM_ITER_INSTEAD_OF_COLLECT,
2218 UNNECESSARY_TO_OWNED,
2221 NEEDLESS_OPTION_AS_DEREF,
2224 /// Extracts a method call name, args, and `Span` of the method name.
2225 fn method_call<'tcx>(recv: &'tcx hir::Expr<'tcx>) -> Option<(&'tcx str, &'tcx [hir::Expr<'tcx>], Span)> {
2226 if let ExprKind::MethodCall(path, args, _) = recv.kind {
2227 if !args.iter().any(|e| e.span.from_expansion()) {
2228 let name = path.ident.name.as_str();
2229 return Some((name, args, path.ident.span));
2235 impl<'tcx> LateLintPass<'tcx> for Methods {
2236 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) {
2237 if expr.span.from_expansion() {
2241 check_methods(cx, expr, self.msrv.as_ref());
2244 hir::ExprKind::Call(func, args) => {
2245 from_iter_instead_of_collect::check(cx, expr, args, func);
2247 hir::ExprKind::MethodCall(method_call, args, _) => {
2248 let method_span = method_call.ident.span;
2249 or_fun_call::check(cx, expr, method_span, method_call.ident.as_str(), args);
2250 expect_fun_call::check(cx, expr, method_span, method_call.ident.as_str(), args);
2251 clone_on_copy::check(cx, expr, method_call.ident.name, args);
2252 clone_on_ref_ptr::check(cx, expr, method_call.ident.name, args);
2253 inefficient_to_string::check(cx, expr, method_call.ident.name, args);
2254 single_char_add_str::check(cx, expr, args);
2255 into_iter_on_ref::check(cx, expr, method_span, method_call.ident.name, args);
2256 single_char_pattern::check(cx, expr, method_call.ident.name, args);
2257 unnecessary_to_owned::check(cx, expr, method_call.ident.name, args);
2259 hir::ExprKind::Binary(op, lhs, rhs) if op.node == hir::BinOpKind::Eq || op.node == hir::BinOpKind::Ne => {
2260 let mut info = BinaryExprInfo {
2264 eq: op.node == hir::BinOpKind::Eq,
2266 lint_binary_expr_with_method_call(cx, &mut info);
2272 #[allow(clippy::too_many_lines)]
2273 fn check_impl_item(&mut self, cx: &LateContext<'tcx>, impl_item: &'tcx hir::ImplItem<'_>) {
2274 if in_external_macro(cx.sess(), impl_item.span) {
2277 let name = impl_item.ident.name.as_str();
2278 let parent = cx.tcx.hir().get_parent_item(impl_item.hir_id());
2279 let item = cx.tcx.hir().expect_item(parent);
2280 let self_ty = cx.tcx.type_of(item.def_id);
2282 let implements_trait = matches!(item.kind, hir::ItemKind::Impl(hir::Impl { of_trait: Some(_), .. }));
2284 if let hir::ImplItemKind::Fn(ref sig, id) = impl_item.kind;
2285 if let Some(first_arg) = iter_input_pats(sig.decl, cx.tcx.hir().body(id)).next();
2287 let method_sig = cx.tcx.fn_sig(impl_item.def_id);
2288 let method_sig = cx.tcx.erase_late_bound_regions(method_sig);
2290 let first_arg_ty = method_sig.inputs().iter().next();
2292 // check conventions w.r.t. conversion method names and predicates
2293 if let Some(first_arg_ty) = first_arg_ty;
2296 // if this impl block implements a trait, lint in trait definition instead
2297 if !implements_trait && cx.access_levels.is_exported(impl_item.def_id) {
2298 // check missing trait implementations
2299 for method_config in &TRAIT_METHODS {
2300 if name == method_config.method_name &&
2301 sig.decl.inputs.len() == method_config.param_count &&
2302 method_config.output_type.matches(&sig.decl.output) &&
2303 method_config.self_kind.matches(cx, self_ty, *first_arg_ty) &&
2304 fn_header_equals(method_config.fn_header, sig.header) &&
2305 method_config.lifetime_param_cond(impl_item)
2309 SHOULD_IMPLEMENT_TRAIT,
2312 "method `{}` can be confused for the standard trait method `{}::{}`",
2313 method_config.method_name,
2314 method_config.trait_name,
2315 method_config.method_name
2319 "consider implementing the trait `{}` or choosing a less ambiguous method name",
2320 method_config.trait_name
2327 if sig.decl.implicit_self.has_implicit_self()
2328 && !(self.avoid_breaking_exported_api
2329 && cx.access_levels.is_exported(impl_item.def_id))
2331 wrong_self_convention::check(
2344 // if this impl block implements a trait, lint in trait definition instead
2345 if implements_trait {
2349 if let hir::ImplItemKind::Fn(_, _) = impl_item.kind {
2350 let ret_ty = return_ty(cx, impl_item.hir_id());
2352 // walk the return type and check for Self (this does not check associated types)
2353 if let Some(self_adt) = self_ty.ty_adt_def() {
2354 if contains_adt_constructor(ret_ty, self_adt) {
2357 } else if contains_ty(ret_ty, self_ty) {
2361 // if return type is impl trait, check the associated types
2362 if let ty::Opaque(def_id, _) = *ret_ty.kind() {
2363 // one of the associated types must be Self
2364 for &(predicate, _span) in cx.tcx.explicit_item_bounds(def_id) {
2365 if let ty::PredicateKind::Projection(projection_predicate) = predicate.kind().skip_binder() {
2366 let assoc_ty = match projection_predicate.term {
2367 ty::Term::Ty(ty) => ty,
2368 ty::Term::Const(_c) => continue,
2370 // walk the associated type and check for Self
2371 if let Some(self_adt) = self_ty.ty_adt_def() {
2372 if contains_adt_constructor(assoc_ty, self_adt) {
2375 } else if contains_ty(assoc_ty, self_ty) {
2382 if name == "new" && ret_ty != self_ty {
2387 "methods called `new` usually return `Self`",
2393 fn check_trait_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx TraitItem<'_>) {
2394 if in_external_macro(cx.tcx.sess, item.span) {
2399 if let TraitItemKind::Fn(ref sig, _) = item.kind;
2400 if sig.decl.implicit_self.has_implicit_self();
2401 if let Some(first_arg_ty) = sig.decl.inputs.iter().next();
2404 let first_arg_span = first_arg_ty.span;
2405 let first_arg_ty = hir_ty_to_ty(cx.tcx, first_arg_ty);
2406 let self_ty = TraitRef::identity(cx.tcx, item.def_id.to_def_id()).self_ty().skip_binder();
2407 wrong_self_convention::check(
2409 item.ident.name.as_str(),
2420 if item.ident.name == sym::new;
2421 if let TraitItemKind::Fn(_, _) = item.kind;
2422 let ret_ty = return_ty(cx, item.hir_id());
2423 let self_ty = TraitRef::identity(cx.tcx, item.def_id.to_def_id()).self_ty().skip_binder();
2424 if !contains_ty(ret_ty, self_ty);
2431 "methods called `new` usually return `Self`",
2437 extract_msrv_attr!(LateContext);
2440 #[allow(clippy::too_many_lines)]
2441 fn check_methods<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, msrv: Option<&RustcVersion>) {
2442 if let Some((name, [recv, args @ ..], span)) = method_call(expr) {
2443 match (name, args) {
2444 ("add" | "offset" | "sub" | "wrapping_offset" | "wrapping_add" | "wrapping_sub", [_arg]) => {
2445 zst_offset::check(cx, expr, recv);
2447 ("and_then", [arg]) => {
2448 let biom_option_linted = bind_instead_of_map::OptionAndThenSome::check(cx, expr, recv, arg);
2449 let biom_result_linted = bind_instead_of_map::ResultAndThenOk::check(cx, expr, recv, arg);
2450 if !biom_option_linted && !biom_result_linted {
2451 unnecessary_lazy_eval::check(cx, expr, recv, arg, "and");
2454 ("as_deref" | "as_deref_mut", []) => {
2455 needless_option_as_deref::check(cx, expr, recv, name);
2457 ("as_mut", []) => useless_asref::check(cx, expr, "as_mut", recv),
2458 ("as_ref", []) => useless_asref::check(cx, expr, "as_ref", recv),
2459 ("assume_init", []) => uninit_assumed_init::check(cx, expr, recv),
2460 ("cloned", []) => cloned_instead_of_copied::check(cx, expr, recv, span, msrv),
2461 ("collect", []) => match method_call(recv) {
2462 Some((name @ ("cloned" | "copied"), [recv2], _)) => {
2463 iter_cloned_collect::check(cx, name, expr, recv2);
2465 Some(("map", [m_recv, m_arg], _)) => {
2466 map_collect_result_unit::check(cx, expr, m_recv, m_arg, recv);
2468 Some(("take", [take_self_arg, take_arg], _)) => {
2469 if meets_msrv(msrv, &msrvs::STR_REPEAT) {
2470 manual_str_repeat::check(cx, expr, recv, take_self_arg, take_arg);
2475 (name @ "count", args @ []) => match method_call(recv) {
2476 Some(("cloned", [recv2], _)) => iter_overeager_cloned::check(cx, expr, recv2, name, args),
2477 Some((name2 @ ("into_iter" | "iter" | "iter_mut"), [recv2], _)) => {
2478 iter_count::check(cx, expr, recv2, name2);
2480 Some(("map", [_, arg], _)) => suspicious_map::check(cx, expr, recv, arg),
2483 ("drain", [arg]) => {
2484 iter_with_drain::check(cx, expr, recv, span, arg);
2486 ("expect", [_]) => match method_call(recv) {
2487 Some(("ok", [recv], _)) => ok_expect::check(cx, expr, recv),
2488 Some(("err", [recv], err_span)) => err_expect::check(cx, expr, recv, msrv, span, err_span),
2489 _ => expect_used::check(cx, expr, recv),
2492 ("extend", [arg]) => {
2493 string_extend_chars::check(cx, expr, recv, arg);
2494 extend_with_drain::check(cx, expr, recv, arg);
2496 ("filter_map", [arg]) => {
2497 unnecessary_filter_map::check(cx, expr, arg, name);
2498 filter_map_identity::check(cx, expr, arg, span);
2500 ("find_map", [arg]) => {
2501 unnecessary_filter_map::check(cx, expr, arg, name);
2503 ("flat_map", [arg]) => {
2504 flat_map_identity::check(cx, expr, arg, span);
2505 flat_map_option::check(cx, expr, arg, span);
2507 (name @ "flatten", args @ []) => match method_call(recv) {
2508 Some(("map", [recv, map_arg], map_span)) => map_flatten::check(cx, expr, recv, map_arg, map_span),
2509 Some(("cloned", [recv2], _)) => iter_overeager_cloned::check(cx, expr, recv2, name, args),
2512 ("fold", [init, acc]) => unnecessary_fold::check(cx, expr, init, acc, span),
2513 ("for_each", [_]) => {
2514 if let Some(("inspect", [_, _], span2)) = method_call(recv) {
2515 inspect_for_each::check(cx, expr, span2);
2518 ("get_or_insert_with", [arg]) => unnecessary_lazy_eval::check(cx, expr, recv, arg, "get_or_insert"),
2519 ("is_file", []) => filetype_is_file::check(cx, expr, recv),
2520 ("is_none", []) => check_is_some_is_none(cx, expr, recv, false),
2521 ("is_some", []) => check_is_some_is_none(cx, expr, recv, true),
2522 ("join", [join_arg]) => {
2523 if let Some(("collect", _, span)) = method_call(recv) {
2524 unnecessary_join::check(cx, expr, recv, join_arg, span);
2527 ("last", args @ []) | ("skip", args @ [_]) => {
2528 if let Some((name2, [recv2, args2 @ ..], _span2)) = method_call(recv) {
2529 if let ("cloned", []) = (name2, args2) {
2530 iter_overeager_cloned::check(cx, expr, recv2, name, args);
2534 (name @ ("map" | "map_err"), [m_arg]) => {
2535 if let Some((name, [recv2, args @ ..], span2)) = method_call(recv) {
2536 match (name, args) {
2537 ("as_mut", []) => option_as_ref_deref::check(cx, expr, recv2, m_arg, true, msrv),
2538 ("as_ref", []) => option_as_ref_deref::check(cx, expr, recv2, m_arg, false, msrv),
2539 ("filter", [f_arg]) => {
2540 filter_map::check(cx, expr, recv2, f_arg, span2, recv, m_arg, span, false);
2542 ("find", [f_arg]) => filter_map::check(cx, expr, recv2, f_arg, span2, recv, m_arg, span, true),
2546 map_identity::check(cx, expr, recv, m_arg, name, span);
2548 ("map_or", [def, map]) => option_map_or_none::check(cx, expr, recv, def, map),
2549 (name @ "next", args @ []) => {
2550 if let Some((name2, [recv2, args2 @ ..], _)) = method_call(recv) {
2551 match (name2, args2) {
2552 ("cloned", []) => iter_overeager_cloned::check(cx, expr, recv2, name, args),
2553 ("filter", [arg]) => filter_next::check(cx, expr, recv2, arg),
2554 ("filter_map", [arg]) => filter_map_next::check(cx, expr, recv2, arg, msrv),
2555 ("iter", []) => iter_next_slice::check(cx, expr, recv2),
2556 ("skip", [arg]) => iter_skip_next::check(cx, expr, recv2, arg),
2557 ("skip_while", [_]) => skip_while_next::check(cx, expr),
2562 ("nth", args @ [n_arg]) => match method_call(recv) {
2563 Some(("bytes", [recv2], _)) => bytes_nth::check(cx, expr, recv2, n_arg),
2564 Some(("cloned", [recv2], _)) => iter_overeager_cloned::check(cx, expr, recv2, name, args),
2565 Some(("iter", [recv2], _)) => iter_nth::check(cx, expr, recv2, recv, n_arg, false),
2566 Some(("iter_mut", [recv2], _)) => iter_nth::check(cx, expr, recv2, recv, n_arg, true),
2567 _ => iter_nth_zero::check(cx, expr, recv, n_arg),
2569 ("ok_or_else", [arg]) => unnecessary_lazy_eval::check(cx, expr, recv, arg, "ok_or"),
2570 ("or_else", [arg]) => {
2571 if !bind_instead_of_map::ResultOrElseErrInfo::check(cx, expr, recv, arg) {
2572 unnecessary_lazy_eval::check(cx, expr, recv, arg, "or");
2575 ("splitn" | "rsplitn", [count_arg, pat_arg]) => {
2576 if let Some((Constant::Int(count), _)) = constant(cx, cx.typeck_results(), count_arg) {
2577 suspicious_splitn::check(cx, name, expr, recv, count);
2578 if count == 2 && meets_msrv(msrv, &msrvs::STR_SPLIT_ONCE) {
2579 str_splitn::check_manual_split_once(cx, name, expr, recv, pat_arg);
2582 str_splitn::check_needless_splitn(cx, name, expr, recv, pat_arg, count);
2586 ("splitn_mut" | "rsplitn_mut", [count_arg, _]) => {
2587 if let Some((Constant::Int(count), _)) = constant(cx, cx.typeck_results(), count_arg) {
2588 suspicious_splitn::check(cx, name, expr, recv, count);
2591 ("step_by", [arg]) => iterator_step_by_zero::check(cx, expr, arg),
2592 ("take", args @ [_arg]) => {
2593 if let Some((name2, [recv2, args2 @ ..], _span2)) = method_call(recv) {
2594 if let ("cloned", []) = (name2, args2) {
2595 iter_overeager_cloned::check(cx, expr, recv2, name, args);
2599 ("to_os_string" | "to_owned" | "to_path_buf" | "to_vec", []) => {
2600 implicit_clone::check(cx, name, expr, recv);
2603 match method_call(recv) {
2604 Some(("get", [recv, get_arg], _)) => {
2605 get_unwrap::check(cx, expr, recv, get_arg, false);
2607 Some(("get_mut", [recv, get_arg], _)) => {
2608 get_unwrap::check(cx, expr, recv, get_arg, true);
2610 Some(("or", [recv, or_arg], or_span)) => {
2611 or_then_unwrap::check(cx, expr, recv, or_arg, or_span);
2615 unwrap_used::check(cx, expr, recv);
2617 ("unwrap_or", [u_arg]) => match method_call(recv) {
2618 Some((arith @ ("checked_add" | "checked_sub" | "checked_mul"), [lhs, rhs], _)) => {
2619 manual_saturating_arithmetic::check(cx, expr, lhs, rhs, u_arg, &arith["checked_".len()..]);
2621 Some(("map", [m_recv, m_arg], span)) => {
2622 option_map_unwrap_or::check(cx, expr, m_recv, m_arg, recv, u_arg, span);
2626 ("unwrap_or_else", [u_arg]) => match method_call(recv) {
2627 Some(("map", [recv, map_arg], _)) if map_unwrap_or::check(cx, expr, recv, map_arg, u_arg, msrv) => {},
2629 unwrap_or_else_default::check(cx, expr, recv, u_arg);
2630 unnecessary_lazy_eval::check(cx, expr, recv, u_arg, "unwrap_or");
2639 fn check_is_some_is_none(cx: &LateContext<'_>, expr: &Expr<'_>, recv: &Expr<'_>, is_some: bool) {
2640 if let Some((name @ ("find" | "position" | "rposition"), [f_recv, arg], span)) = method_call(recv) {
2641 search_is_some::check(cx, expr, name, is_some, f_recv, arg, recv, span);
2645 /// Used for `lint_binary_expr_with_method_call`.
2646 #[derive(Copy, Clone)]
2647 struct BinaryExprInfo<'a> {
2648 expr: &'a hir::Expr<'a>,
2649 chain: &'a hir::Expr<'a>,
2650 other: &'a hir::Expr<'a>,
2654 /// Checks for the `CHARS_NEXT_CMP` and `CHARS_LAST_CMP` lints.
2655 fn lint_binary_expr_with_method_call(cx: &LateContext<'_>, info: &mut BinaryExprInfo<'_>) {
2656 macro_rules! lint_with_both_lhs_and_rhs {
2657 ($func:expr, $cx:expr, $info:ident) => {
2658 if !$func($cx, $info) {
2659 ::std::mem::swap(&mut $info.chain, &mut $info.other);
2660 if $func($cx, $info) {
2667 lint_with_both_lhs_and_rhs!(chars_next_cmp::check, cx, info);
2668 lint_with_both_lhs_and_rhs!(chars_last_cmp::check, cx, info);
2669 lint_with_both_lhs_and_rhs!(chars_next_cmp_with_unwrap::check, cx, info);
2670 lint_with_both_lhs_and_rhs!(chars_last_cmp_with_unwrap::check, cx, info);
2673 const FN_HEADER: hir::FnHeader = hir::FnHeader {
2674 unsafety: hir::Unsafety::Normal,
2675 constness: hir::Constness::NotConst,
2676 asyncness: hir::IsAsync::NotAsync,
2677 abi: rustc_target::spec::abi::Abi::Rust,
2680 struct ShouldImplTraitCase {
2681 trait_name: &'static str,
2682 method_name: &'static str,
2684 fn_header: hir::FnHeader,
2685 // implicit self kind expected (none, self, &self, ...)
2686 self_kind: SelfKind,
2687 // checks against the output type
2688 output_type: OutType,
2689 // certain methods with explicit lifetimes can't implement the equivalent trait method
2690 lint_explicit_lifetime: bool,
2692 impl ShouldImplTraitCase {
2694 trait_name: &'static str,
2695 method_name: &'static str,
2697 fn_header: hir::FnHeader,
2698 self_kind: SelfKind,
2699 output_type: OutType,
2700 lint_explicit_lifetime: bool,
2701 ) -> ShouldImplTraitCase {
2702 ShouldImplTraitCase {
2709 lint_explicit_lifetime,
2713 fn lifetime_param_cond(&self, impl_item: &hir::ImplItem<'_>) -> bool {
2714 self.lint_explicit_lifetime
2715 || !impl_item.generics.params.iter().any(|p| {
2718 hir::GenericParamKind::Lifetime {
2719 kind: hir::LifetimeParamKind::Explicit
2727 const TRAIT_METHODS: [ShouldImplTraitCase; 30] = [
2728 ShouldImplTraitCase::new("std::ops::Add", "add", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
2729 ShouldImplTraitCase::new("std::convert::AsMut", "as_mut", 1, FN_HEADER, SelfKind::RefMut, OutType::Ref, true),
2730 ShouldImplTraitCase::new("std::convert::AsRef", "as_ref", 1, FN_HEADER, SelfKind::Ref, OutType::Ref, true),
2731 ShouldImplTraitCase::new("std::ops::BitAnd", "bitand", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
2732 ShouldImplTraitCase::new("std::ops::BitOr", "bitor", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
2733 ShouldImplTraitCase::new("std::ops::BitXor", "bitxor", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
2734 ShouldImplTraitCase::new("std::borrow::Borrow", "borrow", 1, FN_HEADER, SelfKind::Ref, OutType::Ref, true),
2735 ShouldImplTraitCase::new("std::borrow::BorrowMut", "borrow_mut", 1, FN_HEADER, SelfKind::RefMut, OutType::Ref, true),
2736 ShouldImplTraitCase::new("std::clone::Clone", "clone", 1, FN_HEADER, SelfKind::Ref, OutType::Any, true),
2737 ShouldImplTraitCase::new("std::cmp::Ord", "cmp", 2, FN_HEADER, SelfKind::Ref, OutType::Any, true),
2738 // FIXME: default doesn't work
2739 ShouldImplTraitCase::new("std::default::Default", "default", 0, FN_HEADER, SelfKind::No, OutType::Any, true),
2740 ShouldImplTraitCase::new("std::ops::Deref", "deref", 1, FN_HEADER, SelfKind::Ref, OutType::Ref, true),
2741 ShouldImplTraitCase::new("std::ops::DerefMut", "deref_mut", 1, FN_HEADER, SelfKind::RefMut, OutType::Ref, true),
2742 ShouldImplTraitCase::new("std::ops::Div", "div", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
2743 ShouldImplTraitCase::new("std::ops::Drop", "drop", 1, FN_HEADER, SelfKind::RefMut, OutType::Unit, true),
2744 ShouldImplTraitCase::new("std::cmp::PartialEq", "eq", 2, FN_HEADER, SelfKind::Ref, OutType::Bool, true),
2745 ShouldImplTraitCase::new("std::iter::FromIterator", "from_iter", 1, FN_HEADER, SelfKind::No, OutType::Any, true),
2746 ShouldImplTraitCase::new("std::str::FromStr", "from_str", 1, FN_HEADER, SelfKind::No, OutType::Any, true),
2747 ShouldImplTraitCase::new("std::hash::Hash", "hash", 2, FN_HEADER, SelfKind::Ref, OutType::Unit, true),
2748 ShouldImplTraitCase::new("std::ops::Index", "index", 2, FN_HEADER, SelfKind::Ref, OutType::Ref, true),
2749 ShouldImplTraitCase::new("std::ops::IndexMut", "index_mut", 2, FN_HEADER, SelfKind::RefMut, OutType::Ref, true),
2750 ShouldImplTraitCase::new("std::iter::IntoIterator", "into_iter", 1, FN_HEADER, SelfKind::Value, OutType::Any, true),
2751 ShouldImplTraitCase::new("std::ops::Mul", "mul", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
2752 ShouldImplTraitCase::new("std::ops::Neg", "neg", 1, FN_HEADER, SelfKind::Value, OutType::Any, true),
2753 ShouldImplTraitCase::new("std::iter::Iterator", "next", 1, FN_HEADER, SelfKind::RefMut, OutType::Any, false),
2754 ShouldImplTraitCase::new("std::ops::Not", "not", 1, FN_HEADER, SelfKind::Value, OutType::Any, true),
2755 ShouldImplTraitCase::new("std::ops::Rem", "rem", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
2756 ShouldImplTraitCase::new("std::ops::Shl", "shl", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
2757 ShouldImplTraitCase::new("std::ops::Shr", "shr", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
2758 ShouldImplTraitCase::new("std::ops::Sub", "sub", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
2761 #[derive(Clone, Copy, PartialEq, Debug)]
2770 fn matches<'a>(self, cx: &LateContext<'a>, parent_ty: Ty<'a>, ty: Ty<'a>) -> bool {
2771 fn matches_value<'a>(cx: &LateContext<'a>, parent_ty: Ty<'_>, ty: Ty<'_>) -> bool {
2772 if ty == parent_ty {
2774 } else if ty.is_box() {
2775 ty.boxed_ty() == parent_ty
2776 } else if is_type_diagnostic_item(cx, ty, sym::Rc) || is_type_diagnostic_item(cx, ty, sym::Arc) {
2777 if let ty::Adt(_, substs) = ty.kind() {
2778 substs.types().next().map_or(false, |t| t == parent_ty)
2787 fn matches_ref<'a>(cx: &LateContext<'a>, mutability: hir::Mutability, parent_ty: Ty<'a>, ty: Ty<'a>) -> bool {
2788 if let ty::Ref(_, t, m) = *ty.kind() {
2789 return m == mutability && t == parent_ty;
2792 let trait_path = match mutability {
2793 hir::Mutability::Not => &paths::ASREF_TRAIT,
2794 hir::Mutability::Mut => &paths::ASMUT_TRAIT,
2797 let trait_def_id = match get_trait_def_id(cx, trait_path) {
2799 None => return false,
2801 implements_trait(cx, ty, trait_def_id, &[parent_ty.into()])
2804 fn matches_none<'a>(cx: &LateContext<'a>, parent_ty: Ty<'a>, ty: Ty<'a>) -> bool {
2805 !matches_value(cx, parent_ty, ty)
2806 && !matches_ref(cx, hir::Mutability::Not, parent_ty, ty)
2807 && !matches_ref(cx, hir::Mutability::Mut, parent_ty, ty)
2811 Self::Value => matches_value(cx, parent_ty, ty),
2812 Self::Ref => matches_ref(cx, hir::Mutability::Not, parent_ty, ty) || ty == parent_ty && is_copy(cx, ty),
2813 Self::RefMut => matches_ref(cx, hir::Mutability::Mut, parent_ty, ty),
2814 Self::No => matches_none(cx, parent_ty, ty),
2819 fn description(self) -> &'static str {
2821 Self::Value => "`self` by value",
2822 Self::Ref => "`self` by reference",
2823 Self::RefMut => "`self` by mutable reference",
2824 Self::No => "no `self`",
2829 #[derive(Clone, Copy)]
2838 fn matches(self, ty: &hir::FnRetTy<'_>) -> bool {
2839 let is_unit = |ty: &hir::Ty<'_>| matches!(ty.kind, hir::TyKind::Tup(&[]));
2841 (Self::Unit, &hir::FnRetTy::DefaultReturn(_)) => true,
2842 (Self::Unit, &hir::FnRetTy::Return(ty)) if is_unit(ty) => true,
2843 (Self::Bool, &hir::FnRetTy::Return(ty)) if is_bool(ty) => true,
2844 (Self::Any, &hir::FnRetTy::Return(ty)) if !is_unit(ty) => true,
2845 (Self::Ref, &hir::FnRetTy::Return(ty)) => matches!(ty.kind, hir::TyKind::Rptr(_, _)),
2851 fn is_bool(ty: &hir::Ty<'_>) -> bool {
2852 if let hir::TyKind::Path(QPath::Resolved(_, path)) = ty.kind {
2853 matches!(path.res, Res::PrimTy(PrimTy::Bool))
2859 fn fn_header_equals(expected: hir::FnHeader, actual: hir::FnHeader) -> bool {
2860 expected.constness == actual.constness
2861 && expected.unsafety == actual.unsafety
2862 && expected.asyncness == actual.asyncness