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;
47 mod option_as_ref_deref;
48 mod option_map_or_none;
49 mod option_map_unwrap_or;
53 mod single_char_add_str;
54 mod single_char_insert_string;
55 mod single_char_pattern;
56 mod single_char_push_string;
59 mod string_extend_chars;
61 mod suspicious_splitn;
62 mod uninit_assumed_init;
63 mod unnecessary_filter_map;
65 mod unnecessary_iter_cloned;
67 mod unnecessary_lazy_eval;
68 mod unnecessary_to_owned;
69 mod unwrap_or_else_default;
73 mod wrong_self_convention;
76 use bind_instead_of_map::BindInsteadOfMap;
77 use clippy_utils::consts::{constant, Constant};
78 use clippy_utils::diagnostics::{span_lint, span_lint_and_help};
79 use clippy_utils::ty::{contains_adt_constructor, contains_ty, implements_trait, is_copy, is_type_diagnostic_item};
80 use clippy_utils::{contains_return, get_trait_def_id, iter_input_pats, meets_msrv, msrvs, paths, return_ty};
81 use if_chain::if_chain;
83 use rustc_hir::def::Res;
84 use rustc_hir::{Expr, ExprKind, PrimTy, QPath, TraitItem, TraitItemKind};
85 use rustc_lint::{LateContext, LateLintPass, LintContext};
86 use rustc_middle::lint::in_external_macro;
87 use rustc_middle::ty::{self, TraitRef, Ty};
88 use rustc_semver::RustcVersion;
89 use rustc_session::{declare_tool_lint, impl_lint_pass};
90 use rustc_span::{sym, Span};
91 use rustc_typeck::hir_ty_to_ty;
93 declare_clippy_lint! {
95 /// Checks for usages of `cloned()` on an `Iterator` or `Option` where
96 /// `copied()` could be used instead.
98 /// ### Why is this bad?
99 /// `copied()` is better because it guarantees that the type being cloned
100 /// implements `Copy`.
104 /// [1, 2, 3].iter().cloned();
108 /// [1, 2, 3].iter().copied();
110 #[clippy::version = "1.53.0"]
111 pub CLONED_INSTEAD_OF_COPIED,
113 "used `cloned` where `copied` could be used instead"
116 declare_clippy_lint! {
118 /// Checks for usage of `_.cloned().<func>()` where call to `.cloned()` can be postponed.
120 /// ### Why is this bad?
121 /// It's often inefficient to clone all elements of an iterator, when eventually, only some
122 /// of them will be consumed.
126 /// # let vec = vec!["string".to_string()];
129 /// vec.iter().cloned().take(10);
132 /// vec.iter().take(10).cloned();
135 /// vec.iter().cloned().last();
138 /// vec.iter().last().cloned();
141 /// ### Known Problems
142 /// This `lint` removes the side of effect of cloning items in the iterator.
143 /// A code that relies on that side-effect could fail.
145 #[clippy::version = "1.59.0"]
146 pub ITER_OVEREAGER_CLONED,
148 "using `cloned()` early with `Iterator::iter()` can lead to some performance inefficiencies"
151 declare_clippy_lint! {
153 /// Checks for usages of `Iterator::flat_map()` where `filter_map()` could be
156 /// ### Why is this bad?
157 /// When applicable, `filter_map()` is more clear since it shows that
158 /// `Option` is used to produce 0 or 1 items.
162 /// let nums: Vec<i32> = ["1", "2", "whee!"].iter().flat_map(|x| x.parse().ok()).collect();
166 /// let nums: Vec<i32> = ["1", "2", "whee!"].iter().filter_map(|x| x.parse().ok()).collect();
168 #[clippy::version = "1.53.0"]
171 "used `flat_map` where `filter_map` could be used instead"
174 declare_clippy_lint! {
176 /// Checks for `.unwrap()` calls on `Option`s and on `Result`s.
178 /// ### Why is this bad?
179 /// It is better to handle the `None` or `Err` case,
180 /// or at least call `.expect(_)` with a more helpful message. Still, for a lot of
181 /// quick-and-dirty code, `unwrap` is a good choice, which is why this lint is
182 /// `Allow` by default.
184 /// `result.unwrap()` will let the thread panic on `Err` values.
185 /// Normally, you want to implement more sophisticated error handling,
186 /// and propagate errors upwards with `?` operator.
188 /// Even if you want to panic on errors, not all `Error`s implement good
189 /// messages on display. Therefore, it may be beneficial to look at the places
190 /// where they may get displayed. Activate this lint to do just that.
194 /// # let opt = Some(1);
200 /// opt.expect("more helpful message");
206 /// # let res: Result<usize, ()> = Ok(1);
212 /// res.expect("more helpful message");
214 #[clippy::version = "1.45.0"]
217 "using `.unwrap()` on `Result` or `Option`, which should at least get a better message using `expect()`"
220 declare_clippy_lint! {
222 /// Checks for `.expect()` calls on `Option`s and `Result`s.
224 /// ### Why is this bad?
225 /// Usually it is better to handle the `None` or `Err` case.
226 /// Still, for a lot of quick-and-dirty code, `expect` is a good choice, which is why
227 /// this lint is `Allow` by default.
229 /// `result.expect()` will let the thread panic on `Err`
230 /// values. Normally, you want to implement more sophisticated error handling,
231 /// and propagate errors upwards with `?` operator.
235 /// # let opt = Some(1);
238 /// opt.expect("one");
241 /// let opt = Some(1);
248 /// # let res: Result<usize, ()> = Ok(1);
251 /// res.expect("one");
255 /// # Ok::<(), ()>(())
257 #[clippy::version = "1.45.0"]
260 "using `.expect()` on `Result` or `Option`, which might be better handled"
263 declare_clippy_lint! {
265 /// Checks for methods that should live in a trait
266 /// implementation of a `std` trait (see [llogiq's blog
267 /// post](http://llogiq.github.io/2015/07/30/traits.html) for further
268 /// information) instead of an inherent implementation.
270 /// ### Why is this bad?
271 /// Implementing the traits improve ergonomics for users of
272 /// the code, often with very little cost. Also people seeing a `mul(...)`
274 /// may expect `*` to work equally, so you should have good reason to disappoint
281 /// fn add(&self, other: &X) -> X {
287 #[clippy::version = "pre 1.29.0"]
288 pub SHOULD_IMPLEMENT_TRAIT,
290 "defining a method that should be implementing a std trait"
293 declare_clippy_lint! {
295 /// Checks for methods with certain name prefixes and which
296 /// doesn't match how self is taken. The actual rules are:
298 /// |Prefix |Postfix |`self` taken | `self` type |
299 /// |-------|------------|-----------------------|--------------|
300 /// |`as_` | none |`&self` or `&mut self` | any |
301 /// |`from_`| none | none | any |
302 /// |`into_`| none |`self` | any |
303 /// |`is_` | none |`&self` or none | any |
304 /// |`to_` | `_mut` |`&mut self` | any |
305 /// |`to_` | not `_mut` |`self` | `Copy` |
306 /// |`to_` | not `_mut` |`&self` | not `Copy` |
308 /// Note: Clippy doesn't trigger methods with `to_` prefix in:
309 /// - Traits definition.
310 /// Clippy can not tell if a type that implements a trait is `Copy` or not.
311 /// - Traits implementation, when `&self` is taken.
312 /// The method signature is controlled by the trait and often `&self` is required for all types that implement the trait
313 /// (see e.g. the `std::string::ToString` trait).
315 /// Clippy allows `Pin<&Self>` and `Pin<&mut Self>` if `&self` and `&mut self` is required.
317 /// Please find more info here:
318 /// https://rust-lang.github.io/api-guidelines/naming.html#ad-hoc-conversions-follow-as_-to_-into_-conventions-c-conv
320 /// ### Why is this bad?
321 /// Consistency breeds readability. If you follow the
322 /// conventions, your users won't be surprised that they, e.g., need to supply a
323 /// mutable reference to a `as_..` function.
329 /// fn as_str(self) -> &'static str {
335 #[clippy::version = "pre 1.29.0"]
336 pub WRONG_SELF_CONVENTION,
338 "defining a method named with an established prefix (like \"into_\") that takes `self` with the wrong convention"
341 declare_clippy_lint! {
343 /// Checks for usage of `ok().expect(..)`.
345 /// ### Why is this bad?
346 /// Because you usually call `expect()` on the `Result`
347 /// directly to get a better error message.
349 /// ### Known problems
350 /// The error type needs to implement `Debug`
354 /// # let x = Ok::<_, ()>(());
357 /// x.ok().expect("why did I do this again?");
360 /// x.expect("why did I do this again?");
362 #[clippy::version = "pre 1.29.0"]
365 "using `ok().expect()`, which gives worse error messages than calling `expect` directly on the Result"
368 declare_clippy_lint! {
370 /// Checks for `.err().expect()` calls on the `Result` type.
372 /// ### Why is this bad?
373 /// `.expect_err()` can be called directly to avoid the extra type conversion from `err()`.
377 /// let x: Result<u32, &str> = Ok(10);
378 /// x.err().expect("Testing err().expect()");
382 /// let x: Result<u32, &str> = Ok(10);
383 /// x.expect_err("Testing expect_err");
385 #[clippy::version = "1.61.0"]
388 r#"using `.err().expect("")` when `.expect_err("")` can be used"#
391 declare_clippy_lint! {
393 /// Checks for usages of `_.unwrap_or_else(Default::default)` on `Option` and
396 /// ### Why is this bad?
397 /// Readability, these can be written as `_.unwrap_or_default`, which is
398 /// simpler and more concise.
402 /// # let x = Some(1);
405 /// x.unwrap_or_else(Default::default);
406 /// x.unwrap_or_else(u32::default);
409 /// x.unwrap_or_default();
411 #[clippy::version = "1.56.0"]
412 pub UNWRAP_OR_ELSE_DEFAULT,
414 "using `.unwrap_or_else(Default::default)`, which is more succinctly expressed as `.unwrap_or_default()`"
417 declare_clippy_lint! {
419 /// Checks for usage of `option.map(_).unwrap_or(_)` or `option.map(_).unwrap_or_else(_)` or
420 /// `result.map(_).unwrap_or_else(_)`.
422 /// ### Why is this bad?
423 /// Readability, these can be written more concisely (resp.) as
424 /// `option.map_or(_, _)`, `option.map_or_else(_, _)` and `result.map_or_else(_, _)`.
426 /// ### Known problems
427 /// The order of the arguments is not in execution order
431 /// # let x = Some(1);
434 /// x.map(|a| a + 1).unwrap_or(0);
437 /// x.map_or(0, |a| a + 1);
443 /// # let x: Result<usize, ()> = Ok(1);
444 /// # fn some_function(foo: ()) -> usize { 1 }
447 /// x.map(|a| a + 1).unwrap_or_else(some_function);
450 /// x.map_or_else(some_function, |a| a + 1);
452 #[clippy::version = "1.45.0"]
455 "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)`"
458 declare_clippy_lint! {
460 /// Checks for usage of `_.map_or(None, _)`.
462 /// ### Why is this bad?
463 /// Readability, this can be written more concisely as
466 /// ### Known problems
467 /// The order of the arguments is not in execution order.
471 /// # let opt = Some(1);
474 /// opt.map_or(None, |a| Some(a + 1));
477 /// opt.and_then(|a| Some(a + 1));
479 #[clippy::version = "pre 1.29.0"]
480 pub OPTION_MAP_OR_NONE,
482 "using `Option.map_or(None, f)`, which is more succinctly expressed as `and_then(f)`"
485 declare_clippy_lint! {
487 /// Checks for usage of `_.map_or(None, Some)`.
489 /// ### Why is this bad?
490 /// Readability, this can be written more concisely as
496 /// # let r: Result<u32, &str> = Ok(1);
497 /// assert_eq!(Some(1), r.map_or(None, Some));
502 /// # let r: Result<u32, &str> = Ok(1);
503 /// assert_eq!(Some(1), r.ok());
505 #[clippy::version = "1.44.0"]
506 pub RESULT_MAP_OR_INTO_OPTION,
508 "using `Result.map_or(None, Some)`, which is more succinctly expressed as `ok()`"
511 declare_clippy_lint! {
513 /// Checks for usage of `_.and_then(|x| Some(y))`, `_.and_then(|x| Ok(y))` or
514 /// `_.or_else(|x| Err(y))`.
516 /// ### Why is this bad?
517 /// Readability, this can be written more concisely as
518 /// `_.map(|x| y)` or `_.map_err(|x| y)`.
522 /// # fn opt() -> Option<&'static str> { Some("42") }
523 /// # fn res() -> Result<&'static str, &'static str> { Ok("42") }
524 /// let _ = opt().and_then(|s| Some(s.len()));
525 /// let _ = res().and_then(|s| if s.len() == 42 { Ok(10) } else { Ok(20) });
526 /// let _ = res().or_else(|s| if s.len() == 42 { Err(10) } else { Err(20) });
529 /// The correct use would be:
532 /// # fn opt() -> Option<&'static str> { Some("42") }
533 /// # fn res() -> Result<&'static str, &'static str> { Ok("42") }
534 /// let _ = opt().map(|s| s.len());
535 /// let _ = res().map(|s| if s.len() == 42 { 10 } else { 20 });
536 /// let _ = res().map_err(|s| if s.len() == 42 { 10 } else { 20 });
538 #[clippy::version = "1.45.0"]
539 pub BIND_INSTEAD_OF_MAP,
541 "using `Option.and_then(|x| Some(y))`, which is more succinctly expressed as `map(|x| y)`"
544 declare_clippy_lint! {
546 /// Checks for usage of `_.filter(_).next()`.
548 /// ### Why is this bad?
549 /// Readability, this can be written more concisely as
554 /// # let vec = vec![1];
555 /// vec.iter().filter(|x| **x == 0).next();
557 /// Could be written as
559 /// # let vec = vec![1];
560 /// vec.iter().find(|x| **x == 0);
562 #[clippy::version = "pre 1.29.0"]
565 "using `filter(p).next()`, which is more succinctly expressed as `.find(p)`"
568 declare_clippy_lint! {
570 /// Checks for usage of `_.skip_while(condition).next()`.
572 /// ### Why is this bad?
573 /// Readability, this can be written more concisely as
574 /// `_.find(!condition)`.
578 /// # let vec = vec![1];
579 /// vec.iter().skip_while(|x| **x == 0).next();
581 /// Could be written as
583 /// # let vec = vec![1];
584 /// vec.iter().find(|x| **x != 0);
586 #[clippy::version = "1.42.0"]
589 "using `skip_while(p).next()`, which is more succinctly expressed as `.find(!p)`"
592 declare_clippy_lint! {
594 /// Checks for usage of `_.map(_).flatten(_)` on `Iterator` and `Option`
596 /// ### Why is this bad?
597 /// Readability, this can be written more concisely as
598 /// `_.flat_map(_)` for `Iterator` or `_.and_then(_)` for `Option`
602 /// let vec = vec![vec![1]];
603 /// let opt = Some(5);
606 /// vec.iter().map(|x| x.iter()).flatten();
607 /// opt.map(|x| Some(x * 2)).flatten();
610 /// vec.iter().flat_map(|x| x.iter());
611 /// opt.and_then(|x| Some(x * 2));
613 #[clippy::version = "1.31.0"]
616 "using combinations of `flatten` and `map` which can usually be written as a single method call"
619 declare_clippy_lint! {
621 /// Checks for usage of `_.filter(_).map(_)` that can be written more simply
622 /// as `filter_map(_)`.
624 /// ### Why is this bad?
625 /// Redundant code in the `filter` and `map` operations is poor style and
632 /// .filter(|n| n.checked_add(1).is_some())
633 /// .map(|n| n.checked_add(1).unwrap());
638 /// (0_i32..10).filter_map(|n| n.checked_add(1));
640 #[clippy::version = "1.51.0"]
641 pub MANUAL_FILTER_MAP,
643 "using `_.filter(_).map(_)` in a way that can be written more simply as `filter_map(_)`"
646 declare_clippy_lint! {
648 /// Checks for usage of `_.find(_).map(_)` that can be written more simply
649 /// as `find_map(_)`.
651 /// ### Why is this bad?
652 /// Redundant code in the `find` and `map` operations is poor style and
659 /// .find(|n| n.checked_add(1).is_some())
660 /// .map(|n| n.checked_add(1).unwrap());
665 /// (0_i32..10).find_map(|n| n.checked_add(1));
667 #[clippy::version = "1.51.0"]
670 "using `_.find(_).map(_)` in a way that can be written more simply as `find_map(_)`"
673 declare_clippy_lint! {
675 /// Checks for usage of `_.filter_map(_).next()`.
677 /// ### Why is this bad?
678 /// Readability, this can be written more concisely as
683 /// (0..3).filter_map(|x| if x == 2 { Some(x) } else { None }).next();
685 /// Can be written as
688 /// (0..3).find_map(|x| if x == 2 { Some(x) } else { None });
690 #[clippy::version = "1.36.0"]
693 "using combination of `filter_map` and `next` which can usually be written as a single method call"
696 declare_clippy_lint! {
698 /// Checks for usage of `flat_map(|x| x)`.
700 /// ### Why is this bad?
701 /// Readability, this can be written more concisely by using `flatten`.
705 /// # let iter = vec![vec![0]].into_iter();
706 /// iter.flat_map(|x| x);
708 /// Can be written as
710 /// # let iter = vec![vec![0]].into_iter();
713 #[clippy::version = "1.39.0"]
714 pub FLAT_MAP_IDENTITY,
716 "call to `flat_map` where `flatten` is sufficient"
719 declare_clippy_lint! {
721 /// Checks for an iterator or string search (such as `find()`,
722 /// `position()`, or `rposition()`) followed by a call to `is_some()` or `is_none()`.
724 /// ### Why is this bad?
725 /// Readability, this can be written more concisely as:
726 /// * `_.any(_)`, or `_.contains(_)` for `is_some()`,
727 /// * `!_.any(_)`, or `!_.contains(_)` for `is_none()`.
731 /// let vec = vec![1];
732 /// vec.iter().find(|x| **x == 0).is_some();
734 /// let _ = "hello world".find("world").is_none();
736 /// Could be written as
738 /// let vec = vec![1];
739 /// vec.iter().any(|x| *x == 0);
741 /// let _ = !"hello world".contains("world");
743 #[clippy::version = "pre 1.29.0"]
746 "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()`)"
749 declare_clippy_lint! {
751 /// Checks for usage of `.chars().next()` on a `str` to check
752 /// if it starts with a given char.
754 /// ### Why is this bad?
755 /// Readability, this can be written more concisely as
756 /// `_.starts_with(_)`.
760 /// let name = "foo";
761 /// if name.chars().next() == Some('_') {};
763 /// Could be written as
765 /// let name = "foo";
766 /// if name.starts_with('_') {};
768 #[clippy::version = "pre 1.29.0"]
771 "using `.chars().next()` to check if a string starts with a char"
774 declare_clippy_lint! {
776 /// Checks for calls to `.or(foo(..))`, `.unwrap_or(foo(..))`,
777 /// etc., and suggests to use `or_else`, `unwrap_or_else`, etc., or
778 /// `unwrap_or_default` instead.
780 /// ### Why is this bad?
781 /// The function will always be called and potentially
782 /// allocate an object acting as the default.
784 /// ### Known problems
785 /// If the function has side-effects, not calling it will
786 /// change the semantic of the program, but you shouldn't rely on that anyway.
790 /// # let foo = Some(String::new());
791 /// foo.unwrap_or(String::new());
793 /// this can instead be written:
795 /// # let foo = Some(String::new());
796 /// foo.unwrap_or_else(String::new);
800 /// # let foo = Some(String::new());
801 /// foo.unwrap_or_default();
803 #[clippy::version = "pre 1.29.0"]
806 "using any `*or` method with a function call, which suggests `*or_else`"
809 declare_clippy_lint! {
811 /// Checks for `.or(…).unwrap()` calls to Options and Results.
813 /// ### Why is this bad?
814 /// You should use `.unwrap_or(…)` instead for clarity.
818 /// # let fallback = "fallback";
820 /// # type Error = &'static str;
821 /// # let result: Result<&str, Error> = Err("error");
822 /// let value = result.or::<Error>(Ok(fallback)).unwrap();
825 /// # let option: Option<&str> = None;
826 /// let value = option.or(Some(fallback)).unwrap();
830 /// # let fallback = "fallback";
832 /// # let result: Result<&str, &str> = Err("error");
833 /// let value = result.unwrap_or(fallback);
836 /// # let option: Option<&str> = None;
837 /// let value = option.unwrap_or(fallback);
839 #[clippy::version = "1.61.0"]
842 "checks for `.or(…).unwrap()` calls to Options and Results."
845 declare_clippy_lint! {
847 /// Checks for calls to `.expect(&format!(...))`, `.expect(foo(..))`,
848 /// etc., and suggests to use `unwrap_or_else` instead
850 /// ### Why is this bad?
851 /// The function will always be called.
853 /// ### Known problems
854 /// If the function has side-effects, not calling it will
855 /// change the semantics of the program, but you shouldn't rely on that anyway.
859 /// # let foo = Some(String::new());
860 /// # let err_code = "418";
861 /// # let err_msg = "I'm a teapot";
862 /// foo.expect(&format!("Err {}: {}", err_code, err_msg));
866 /// # let foo = Some(String::new());
867 /// # let err_code = "418";
868 /// # let err_msg = "I'm a teapot";
869 /// foo.expect(format!("Err {}: {}", err_code, err_msg).as_str());
871 /// this can instead be written:
873 /// # let foo = Some(String::new());
874 /// # let err_code = "418";
875 /// # let err_msg = "I'm a teapot";
876 /// foo.unwrap_or_else(|| panic!("Err {}: {}", err_code, err_msg));
878 #[clippy::version = "pre 1.29.0"]
881 "using any `expect` method with a function call"
884 declare_clippy_lint! {
886 /// Checks for usage of `.clone()` on a `Copy` type.
888 /// ### Why is this bad?
889 /// The only reason `Copy` types implement `Clone` is for
890 /// generics, not for using the `clone` method on a concrete type.
896 #[clippy::version = "pre 1.29.0"]
899 "using `clone` on a `Copy` type"
902 declare_clippy_lint! {
904 /// Checks for usage of `.clone()` on a ref-counted pointer,
905 /// (`Rc`, `Arc`, `rc::Weak`, or `sync::Weak`), and suggests calling Clone via unified
906 /// function syntax instead (e.g., `Rc::clone(foo)`).
908 /// ### Why is this bad?
909 /// Calling '.clone()' on an Rc, Arc, or Weak
910 /// can obscure the fact that only the pointer is being cloned, not the underlying
915 /// # use std::rc::Rc;
916 /// let x = Rc::new(1);
924 #[clippy::version = "pre 1.29.0"]
925 pub CLONE_ON_REF_PTR,
927 "using 'clone' on a ref-counted pointer"
930 declare_clippy_lint! {
932 /// Checks for usage of `.clone()` on an `&&T`.
934 /// ### Why is this bad?
935 /// Cloning an `&&T` copies the inner `&T`, instead of
936 /// cloning the underlying `T`.
943 /// let z = y.clone();
944 /// println!("{:p} {:p}", *y, z); // prints out the same pointer
947 #[clippy::version = "pre 1.29.0"]
948 pub CLONE_DOUBLE_REF,
950 "using `clone` on `&&T`"
953 declare_clippy_lint! {
955 /// Checks for usage of `.to_string()` on an `&&T` where
956 /// `T` implements `ToString` directly (like `&&str` or `&&String`).
958 /// ### Why is this bad?
959 /// This bypasses the specialized implementation of
960 /// `ToString` and instead goes through the more expensive string formatting
965 /// // Generic implementation for `T: Display` is used (slow)
966 /// ["foo", "bar"].iter().map(|s| s.to_string());
968 /// // OK, the specialized impl is used
969 /// ["foo", "bar"].iter().map(|&s| s.to_string());
971 #[clippy::version = "1.40.0"]
972 pub INEFFICIENT_TO_STRING,
974 "using `to_string` on `&&T` where `T: ToString`"
977 declare_clippy_lint! {
979 /// Checks for `new` not returning a type that contains `Self`.
981 /// ### Why is this bad?
982 /// As a convention, `new` methods are used to make a new
983 /// instance of a type.
986 /// In an impl block:
989 /// # struct NotAFoo;
991 /// fn new() -> NotAFoo {
1001 /// // Bad. The type name must contain `Self`
1002 /// fn new() -> Bar {
1010 /// # struct FooError;
1012 /// // Good. Return type contains `Self`
1013 /// fn new() -> Result<Foo, FooError> {
1019 /// Or in a trait definition:
1021 /// pub trait Trait {
1022 /// // Bad. The type name must contain `Self`
1028 /// pub trait Trait {
1029 /// // Good. Return type contains `Self`
1030 /// fn new() -> Self;
1033 #[clippy::version = "pre 1.29.0"]
1034 pub NEW_RET_NO_SELF,
1036 "not returning type containing `Self` in a `new` method"
1039 declare_clippy_lint! {
1040 /// ### What it does
1041 /// Checks for string methods that receive a single-character
1042 /// `str` as an argument, e.g., `_.split("x")`.
1044 /// ### Why is this bad?
1045 /// Performing these methods using a `char` is faster than
1048 /// ### Known problems
1049 /// Does not catch multi-byte unicode characters.
1058 #[clippy::version = "pre 1.29.0"]
1059 pub SINGLE_CHAR_PATTERN,
1061 "using a single-character str where a char could be used, e.g., `_.split(\"x\")`"
1064 declare_clippy_lint! {
1065 /// ### What it does
1066 /// Checks for calling `.step_by(0)` on iterators which panics.
1068 /// ### Why is this bad?
1069 /// This very much looks like an oversight. Use `panic!()` instead if you
1070 /// actually intend to panic.
1073 /// ```rust,should_panic
1074 /// for x in (0..100).step_by(0) {
1078 #[clippy::version = "pre 1.29.0"]
1079 pub ITERATOR_STEP_BY_ZERO,
1081 "using `Iterator::step_by(0)`, which will panic at runtime"
1084 declare_clippy_lint! {
1085 /// ### What it does
1086 /// Checks for indirect collection of populated `Option`
1088 /// ### Why is this bad?
1089 /// `Option` is like a collection of 0-1 things, so `flatten`
1090 /// automatically does this without suspicious-looking `unwrap` calls.
1094 /// let _ = std::iter::empty::<Option<i32>>().filter(Option::is_some).map(Option::unwrap);
1098 /// let _ = std::iter::empty::<Option<i32>>().flatten();
1100 #[clippy::version = "1.53.0"]
1101 pub OPTION_FILTER_MAP,
1103 "filtering `Option` for `Some` then force-unwrapping, which can be one type-safe operation"
1106 declare_clippy_lint! {
1107 /// ### What it does
1108 /// Checks for the use of `iter.nth(0)`.
1110 /// ### Why is this bad?
1111 /// `iter.next()` is equivalent to
1112 /// `iter.nth(0)`, as they both consume the next element,
1113 /// but is more readable.
1117 /// # use std::collections::HashSet;
1119 /// # let mut s = HashSet::new();
1121 /// let x = s.iter().nth(0);
1124 /// # let mut s = HashSet::new();
1126 /// let x = s.iter().next();
1128 #[clippy::version = "1.42.0"]
1131 "replace `iter.nth(0)` with `iter.next()`"
1134 declare_clippy_lint! {
1135 /// ### What it does
1136 /// Checks for use of `.iter().nth()` (and the related
1137 /// `.iter_mut().nth()`) on standard library types with *O*(1) element access.
1139 /// ### Why is this bad?
1140 /// `.get()` and `.get_mut()` are more efficient and more
1145 /// let some_vec = vec![0, 1, 2, 3];
1146 /// let bad_vec = some_vec.iter().nth(3);
1147 /// let bad_slice = &some_vec[..].iter().nth(3);
1149 /// The correct use would be:
1151 /// let some_vec = vec![0, 1, 2, 3];
1152 /// let bad_vec = some_vec.get(3);
1153 /// let bad_slice = &some_vec[..].get(3);
1155 #[clippy::version = "pre 1.29.0"]
1158 "using `.iter().nth()` on a standard library type with O(1) element access"
1161 declare_clippy_lint! {
1162 /// ### What it does
1163 /// Checks for use of `.skip(x).next()` on iterators.
1165 /// ### Why is this bad?
1166 /// `.nth(x)` is cleaner
1170 /// let some_vec = vec![0, 1, 2, 3];
1171 /// let bad_vec = some_vec.iter().skip(3).next();
1172 /// let bad_slice = &some_vec[..].iter().skip(3).next();
1174 /// The correct use would be:
1176 /// let some_vec = vec![0, 1, 2, 3];
1177 /// let bad_vec = some_vec.iter().nth(3);
1178 /// let bad_slice = &some_vec[..].iter().nth(3);
1180 #[clippy::version = "pre 1.29.0"]
1183 "using `.skip(x).next()` on an iterator"
1186 declare_clippy_lint! {
1187 /// ### What it does
1188 /// Checks for use of `.drain(..)` on `Vec` and `VecDeque` for iteration.
1190 /// ### Why is this bad?
1191 /// `.into_iter()` is simpler with better performance.
1195 /// # use std::collections::HashSet;
1196 /// let mut foo = vec![0, 1, 2, 3];
1197 /// let bar: HashSet<usize> = foo.drain(..).collect();
1201 /// # use std::collections::HashSet;
1202 /// let foo = vec![0, 1, 2, 3];
1203 /// let bar: HashSet<usize> = foo.into_iter().collect();
1205 #[clippy::version = "1.61.0"]
1206 pub ITER_WITH_DRAIN,
1208 "replace `.drain(..)` with `.into_iter()`"
1211 declare_clippy_lint! {
1212 /// ### What it does
1213 /// Checks for use of `.get().unwrap()` (or
1214 /// `.get_mut().unwrap`) on a standard library type which implements `Index`
1216 /// ### Why is this bad?
1217 /// Using the Index trait (`[]`) is more clear and more
1220 /// ### Known problems
1221 /// Not a replacement for error handling: Using either
1222 /// `.unwrap()` or the Index trait (`[]`) carries the risk of causing a `panic`
1223 /// if the value being accessed is `None`. If the use of `.get().unwrap()` is a
1224 /// temporary placeholder for dealing with the `Option` type, then this does
1225 /// not mitigate the need for error handling. If there is a chance that `.get()`
1226 /// will be `None` in your program, then it is advisable that the `None` case
1227 /// is handled in a future refactor instead of using `.unwrap()` or the Index
1232 /// let mut some_vec = vec![0, 1, 2, 3];
1233 /// let last = some_vec.get(3).unwrap();
1234 /// *some_vec.get_mut(0).unwrap() = 1;
1236 /// The correct use would be:
1238 /// let mut some_vec = vec![0, 1, 2, 3];
1239 /// let last = some_vec[3];
1240 /// some_vec[0] = 1;
1242 #[clippy::version = "pre 1.29.0"]
1245 "using `.get().unwrap()` or `.get_mut().unwrap()` when using `[]` would work instead"
1248 declare_clippy_lint! {
1249 /// ### What it does
1250 /// Checks for occurrences where one vector gets extended instead of append
1252 /// ### Why is this bad?
1253 /// Using `append` instead of `extend` is more concise and faster
1257 /// let mut a = vec![1, 2, 3];
1258 /// let mut b = vec![4, 5, 6];
1261 /// a.extend(b.drain(..));
1264 /// a.append(&mut b);
1266 #[clippy::version = "1.55.0"]
1267 pub EXTEND_WITH_DRAIN,
1269 "using vec.append(&mut vec) to move the full range of a vecor to another"
1272 declare_clippy_lint! {
1273 /// ### What it does
1274 /// Checks for the use of `.extend(s.chars())` where s is a
1275 /// `&str` or `String`.
1277 /// ### Why is this bad?
1278 /// `.push_str(s)` is clearer
1282 /// let abc = "abc";
1283 /// let def = String::from("def");
1284 /// let mut s = String::new();
1285 /// s.extend(abc.chars());
1286 /// s.extend(def.chars());
1288 /// The correct use would be:
1290 /// let abc = "abc";
1291 /// let def = String::from("def");
1292 /// let mut s = String::new();
1293 /// s.push_str(abc);
1294 /// s.push_str(&def);
1296 #[clippy::version = "pre 1.29.0"]
1297 pub STRING_EXTEND_CHARS,
1299 "using `x.extend(s.chars())` where s is a `&str` or `String`"
1302 declare_clippy_lint! {
1303 /// ### What it does
1304 /// Checks for the use of `.cloned().collect()` on slice to
1307 /// ### Why is this bad?
1308 /// `.to_vec()` is clearer
1312 /// let s = [1, 2, 3, 4, 5];
1313 /// let s2: Vec<isize> = s[..].iter().cloned().collect();
1315 /// The better use would be:
1317 /// let s = [1, 2, 3, 4, 5];
1318 /// let s2: Vec<isize> = s.to_vec();
1320 #[clippy::version = "pre 1.29.0"]
1321 pub ITER_CLONED_COLLECT,
1323 "using `.cloned().collect()` on slice to create a `Vec`"
1326 declare_clippy_lint! {
1327 /// ### What it does
1328 /// Checks for usage of `_.chars().last()` or
1329 /// `_.chars().next_back()` on a `str` to check if it ends with a given char.
1331 /// ### Why is this bad?
1332 /// Readability, this can be written more concisely as
1333 /// `_.ends_with(_)`.
1337 /// # let name = "_";
1340 /// name.chars().last() == Some('_') || name.chars().next_back() == Some('-');
1343 /// name.ends_with('_') || name.ends_with('-');
1345 #[clippy::version = "pre 1.29.0"]
1348 "using `.chars().last()` or `.chars().next_back()` to check if a string ends with a char"
1351 declare_clippy_lint! {
1352 /// ### What it does
1353 /// Checks for usage of `.as_ref()` or `.as_mut()` where the
1354 /// types before and after the call are the same.
1356 /// ### Why is this bad?
1357 /// The call is unnecessary.
1361 /// # fn do_stuff(x: &[i32]) {}
1362 /// let x: &[i32] = &[1, 2, 3, 4, 5];
1363 /// do_stuff(x.as_ref());
1365 /// The correct use would be:
1367 /// # fn do_stuff(x: &[i32]) {}
1368 /// let x: &[i32] = &[1, 2, 3, 4, 5];
1371 #[clippy::version = "pre 1.29.0"]
1374 "using `as_ref` where the types before and after the call are the same"
1377 declare_clippy_lint! {
1378 /// ### What it does
1379 /// Checks for using `fold` when a more succinct alternative exists.
1380 /// Specifically, this checks for `fold`s which could be replaced by `any`, `all`,
1381 /// `sum` or `product`.
1383 /// ### Why is this bad?
1388 /// let _ = (0..3).fold(false, |acc, x| acc || x > 2);
1390 /// This could be written as:
1392 /// let _ = (0..3).any(|x| x > 2);
1394 #[clippy::version = "pre 1.29.0"]
1395 pub UNNECESSARY_FOLD,
1397 "using `fold` when a more succinct alternative exists"
1400 declare_clippy_lint! {
1401 /// ### What it does
1402 /// Checks for `filter_map` calls that could be replaced by `filter` or `map`.
1403 /// More specifically it checks if the closure provided is only performing one of the
1404 /// filter or map operations and suggests the appropriate option.
1406 /// ### Why is this bad?
1407 /// Complexity. The intent is also clearer if only a single
1408 /// operation is being performed.
1412 /// let _ = (0..3).filter_map(|x| if x > 2 { Some(x) } else { None });
1414 /// // As there is no transformation of the argument this could be written as:
1415 /// let _ = (0..3).filter(|&x| x > 2);
1419 /// let _ = (0..4).filter_map(|x| Some(x + 1));
1421 /// // As there is no conditional check on the argument this could be written as:
1422 /// let _ = (0..4).map(|x| x + 1);
1424 #[clippy::version = "1.31.0"]
1425 pub UNNECESSARY_FILTER_MAP,
1427 "using `filter_map` when a more succinct alternative exists"
1430 declare_clippy_lint! {
1431 /// ### What it does
1432 /// Checks for `find_map` calls that could be replaced by `find` or `map`. More
1433 /// specifically it checks if the closure provided is only performing one of the
1434 /// find or map operations and suggests the appropriate option.
1436 /// ### Why is this bad?
1437 /// Complexity. The intent is also clearer if only a single
1438 /// operation is being performed.
1442 /// let _ = (0..3).find_map(|x| if x > 2 { Some(x) } else { None });
1444 /// // As there is no transformation of the argument this could be written as:
1445 /// let _ = (0..3).find(|&x| x > 2);
1449 /// let _ = (0..4).find_map(|x| Some(x + 1));
1451 /// // As there is no conditional check on the argument this could be written as:
1452 /// let _ = (0..4).map(|x| x + 1).next();
1454 #[clippy::version = "1.61.0"]
1455 pub UNNECESSARY_FIND_MAP,
1457 "using `find_map` when a more succinct alternative exists"
1460 declare_clippy_lint! {
1461 /// ### What it does
1462 /// Checks for `into_iter` calls on references which should be replaced by `iter`
1465 /// ### Why is this bad?
1466 /// Readability. Calling `into_iter` on a reference will not move out its
1467 /// content into the resulting iterator, which is confusing. It is better just call `iter` or
1468 /// `iter_mut` directly.
1473 /// let _ = (&vec![3, 4, 5]).into_iter();
1476 /// let _ = (&vec![3, 4, 5]).iter();
1478 #[clippy::version = "1.32.0"]
1479 pub INTO_ITER_ON_REF,
1481 "using `.into_iter()` on a reference"
1484 declare_clippy_lint! {
1485 /// ### What it does
1486 /// Checks for calls to `map` followed by a `count`.
1488 /// ### Why is this bad?
1489 /// It looks suspicious. Maybe `map` was confused with `filter`.
1490 /// If the `map` call is intentional, this should be rewritten
1491 /// using `inspect`. Or, if you intend to drive the iterator to
1492 /// completion, you can just use `for_each` instead.
1496 /// let _ = (0..3).map(|x| x + 2).count();
1498 #[clippy::version = "1.39.0"]
1501 "suspicious usage of map"
1504 declare_clippy_lint! {
1505 /// ### What it does
1506 /// Checks for `MaybeUninit::uninit().assume_init()`.
1508 /// ### Why is this bad?
1509 /// For most types, this is undefined behavior.
1511 /// ### Known problems
1512 /// For now, we accept empty tuples and tuples / arrays
1513 /// of `MaybeUninit`. There may be other types that allow uninitialized
1514 /// data, but those are not yet rigorously defined.
1518 /// // Beware the UB
1519 /// use std::mem::MaybeUninit;
1521 /// let _: usize = unsafe { MaybeUninit::uninit().assume_init() };
1524 /// Note that the following is OK:
1527 /// use std::mem::MaybeUninit;
1529 /// let _: [MaybeUninit<bool>; 5] = unsafe {
1530 /// MaybeUninit::uninit().assume_init()
1533 #[clippy::version = "1.39.0"]
1534 pub UNINIT_ASSUMED_INIT,
1536 "`MaybeUninit::uninit().assume_init()`"
1539 declare_clippy_lint! {
1540 /// ### What it does
1541 /// Checks for `.checked_add/sub(x).unwrap_or(MAX/MIN)`.
1543 /// ### Why is this bad?
1544 /// These can be written simply with `saturating_add/sub` methods.
1548 /// # let y: u32 = 0;
1549 /// # let x: u32 = 100;
1550 /// let add = x.checked_add(y).unwrap_or(u32::MAX);
1551 /// let sub = x.checked_sub(y).unwrap_or(u32::MIN);
1554 /// can be written using dedicated methods for saturating addition/subtraction as:
1557 /// # let y: u32 = 0;
1558 /// # let x: u32 = 100;
1559 /// let add = x.saturating_add(y);
1560 /// let sub = x.saturating_sub(y);
1562 #[clippy::version = "1.39.0"]
1563 pub MANUAL_SATURATING_ARITHMETIC,
1565 "`.chcked_add/sub(x).unwrap_or(MAX/MIN)`"
1568 declare_clippy_lint! {
1569 /// ### What it does
1570 /// Checks for `offset(_)`, `wrapping_`{`add`, `sub`}, etc. on raw pointers to
1571 /// zero-sized types
1573 /// ### Why is this bad?
1574 /// This is a no-op, and likely unintended
1578 /// unsafe { (&() as *const ()).offset(1) };
1580 #[clippy::version = "1.41.0"]
1583 "Check for offset calculations on raw pointers to zero-sized types"
1586 declare_clippy_lint! {
1587 /// ### What it does
1588 /// Checks for `FileType::is_file()`.
1590 /// ### Why is this bad?
1591 /// When people testing a file type with `FileType::is_file`
1592 /// they are testing whether a path is something they can get bytes from. But
1593 /// `is_file` doesn't cover special file types in unix-like systems, and doesn't cover
1594 /// symlink in windows. Using `!FileType::is_dir()` is a better way to that intention.
1599 /// let metadata = std::fs::metadata("foo.txt")?;
1600 /// let filetype = metadata.file_type();
1602 /// if filetype.is_file() {
1605 /// # Ok::<_, std::io::Error>(())
1609 /// should be written as:
1613 /// let metadata = std::fs::metadata("foo.txt")?;
1614 /// let filetype = metadata.file_type();
1616 /// if !filetype.is_dir() {
1619 /// # Ok::<_, std::io::Error>(())
1622 #[clippy::version = "1.42.0"]
1623 pub FILETYPE_IS_FILE,
1625 "`FileType::is_file` is not recommended to test for readable file type"
1628 declare_clippy_lint! {
1629 /// ### What it does
1630 /// Checks for usage of `_.as_ref().map(Deref::deref)` or it's aliases (such as String::as_str).
1632 /// ### Why is this bad?
1633 /// Readability, this can be written more concisely as
1638 /// # let opt = Some("".to_string());
1639 /// opt.as_ref().map(String::as_str)
1642 /// Can be written as
1644 /// # let opt = Some("".to_string());
1648 #[clippy::version = "1.42.0"]
1649 pub OPTION_AS_REF_DEREF,
1651 "using `as_ref().map(Deref::deref)`, which is more succinctly expressed as `as_deref()`"
1654 declare_clippy_lint! {
1655 /// ### What it does
1656 /// Checks for usage of `iter().next()` on a Slice or an Array
1658 /// ### Why is this bad?
1659 /// These can be shortened into `.get()`
1663 /// # let a = [1, 2, 3];
1664 /// # let b = vec![1, 2, 3];
1665 /// a[2..].iter().next();
1666 /// b.iter().next();
1668 /// should be written as:
1670 /// # let a = [1, 2, 3];
1671 /// # let b = vec![1, 2, 3];
1675 #[clippy::version = "1.46.0"]
1676 pub ITER_NEXT_SLICE,
1678 "using `.iter().next()` on a sliced array, which can be shortened to just `.get()`"
1681 declare_clippy_lint! {
1682 /// ### What it does
1683 /// Warns when using `push_str`/`insert_str` with a single-character string literal
1684 /// where `push`/`insert` with a `char` would work fine.
1686 /// ### Why is this bad?
1687 /// It's less clear that we are pushing a single character.
1691 /// let mut string = String::new();
1692 /// string.insert_str(0, "R");
1693 /// string.push_str("R");
1695 /// Could be written as
1697 /// let mut string = String::new();
1698 /// string.insert(0, 'R');
1699 /// string.push('R');
1701 #[clippy::version = "1.49.0"]
1702 pub SINGLE_CHAR_ADD_STR,
1704 "`push_str()` or `insert_str()` used with a single-character string literal as parameter"
1707 declare_clippy_lint! {
1708 /// ### What it does
1709 /// As the counterpart to `or_fun_call`, this lint looks for unnecessary
1710 /// lazily evaluated closures on `Option` and `Result`.
1712 /// This lint suggests changing the following functions, when eager evaluation results in
1714 /// - `unwrap_or_else` to `unwrap_or`
1715 /// - `and_then` to `and`
1716 /// - `or_else` to `or`
1717 /// - `get_or_insert_with` to `get_or_insert`
1718 /// - `ok_or_else` to `ok_or`
1720 /// ### Why is this bad?
1721 /// Using eager evaluation is shorter and simpler in some cases.
1723 /// ### Known problems
1724 /// It is possible, but not recommended for `Deref` and `Index` to have
1725 /// side effects. Eagerly evaluating them can change the semantics of the program.
1729 /// // example code where clippy issues a warning
1730 /// let opt: Option<u32> = None;
1732 /// opt.unwrap_or_else(|| 42);
1736 /// let opt: Option<u32> = None;
1738 /// opt.unwrap_or(42);
1740 #[clippy::version = "1.48.0"]
1741 pub UNNECESSARY_LAZY_EVALUATIONS,
1743 "using unnecessary lazy evaluation, which can be replaced with simpler eager evaluation"
1746 declare_clippy_lint! {
1747 /// ### What it does
1748 /// Checks for usage of `_.map(_).collect::<Result<(), _>()`.
1750 /// ### Why is this bad?
1751 /// Using `try_for_each` instead is more readable and idiomatic.
1755 /// (0..3).map(|t| Err(t)).collect::<Result<(), _>>();
1759 /// (0..3).try_for_each(|t| Err(t));
1761 #[clippy::version = "1.49.0"]
1762 pub MAP_COLLECT_RESULT_UNIT,
1764 "using `.map(_).collect::<Result<(),_>()`, which can be replaced with `try_for_each`"
1767 declare_clippy_lint! {
1768 /// ### What it does
1769 /// Checks for `from_iter()` function calls on types that implement the `FromIterator`
1772 /// ### Why is this bad?
1773 /// It is recommended style to use collect. See
1774 /// [FromIterator documentation](https://doc.rust-lang.org/std/iter/trait.FromIterator.html)
1778 /// use std::iter::FromIterator;
1780 /// let five_fives = std::iter::repeat(5).take(5);
1782 /// let v = Vec::from_iter(five_fives);
1784 /// assert_eq!(v, vec![5, 5, 5, 5, 5]);
1788 /// let five_fives = std::iter::repeat(5).take(5);
1790 /// let v: Vec<i32> = five_fives.collect();
1792 /// assert_eq!(v, vec![5, 5, 5, 5, 5]);
1794 #[clippy::version = "1.49.0"]
1795 pub FROM_ITER_INSTEAD_OF_COLLECT,
1797 "use `.collect()` instead of `::from_iter()`"
1800 declare_clippy_lint! {
1801 /// ### What it does
1802 /// Checks for usage of `inspect().for_each()`.
1804 /// ### Why is this bad?
1805 /// It is the same as performing the computation
1806 /// inside `inspect` at the beginning of the closure in `for_each`.
1810 /// [1,2,3,4,5].iter()
1811 /// .inspect(|&x| println!("inspect the number: {}", x))
1812 /// .for_each(|&x| {
1813 /// assert!(x >= 0);
1816 /// Can be written as
1818 /// [1,2,3,4,5].iter()
1819 /// .for_each(|&x| {
1820 /// println!("inspect the number: {}", x);
1821 /// assert!(x >= 0);
1824 #[clippy::version = "1.51.0"]
1825 pub INSPECT_FOR_EACH,
1827 "using `.inspect().for_each()`, which can be replaced with `.for_each()`"
1830 declare_clippy_lint! {
1831 /// ### What it does
1832 /// Checks for usage of `filter_map(|x| x)`.
1834 /// ### Why is this bad?
1835 /// Readability, this can be written more concisely by using `flatten`.
1839 /// # let iter = vec![Some(1)].into_iter();
1840 /// iter.filter_map(|x| x);
1844 /// # let iter = vec![Some(1)].into_iter();
1847 #[clippy::version = "1.52.0"]
1848 pub FILTER_MAP_IDENTITY,
1850 "call to `filter_map` where `flatten` is sufficient"
1853 declare_clippy_lint! {
1854 /// ### What it does
1855 /// Checks for instances of `map(f)` where `f` is the identity function.
1857 /// ### Why is this bad?
1858 /// It can be written more concisely without the call to `map`.
1862 /// let x = [1, 2, 3];
1863 /// let y: Vec<_> = x.iter().map(|x| x).map(|x| 2*x).collect();
1867 /// let x = [1, 2, 3];
1868 /// let y: Vec<_> = x.iter().map(|x| 2*x).collect();
1870 #[clippy::version = "1.52.0"]
1873 "using iterator.map(|x| x)"
1876 declare_clippy_lint! {
1877 /// ### What it does
1878 /// Checks for the use of `.bytes().nth()`.
1880 /// ### Why is this bad?
1881 /// `.as_bytes().get()` is more efficient and more
1887 /// let _ = "Hello".bytes().nth(3);
1890 /// let _ = "Hello".as_bytes().get(3);
1892 #[clippy::version = "1.52.0"]
1895 "replace `.bytes().nth()` with `.as_bytes().get()`"
1898 declare_clippy_lint! {
1899 /// ### What it does
1900 /// Checks for the usage of `_.to_owned()`, `vec.to_vec()`, or similar when calling `_.clone()` would be clearer.
1902 /// ### Why is this bad?
1903 /// These methods do the same thing as `_.clone()` but may be confusing as
1904 /// to why we are calling `to_vec` on something that is already a `Vec` or calling `to_owned` on something that is already owned.
1908 /// let a = vec![1, 2, 3];
1909 /// let b = a.to_vec();
1910 /// let c = a.to_owned();
1914 /// let a = vec![1, 2, 3];
1915 /// let b = a.clone();
1916 /// let c = a.clone();
1918 #[clippy::version = "1.52.0"]
1921 "implicitly cloning a value by invoking a function on its dereferenced type"
1924 declare_clippy_lint! {
1925 /// ### What it does
1926 /// Checks for the use of `.iter().count()`.
1928 /// ### Why is this bad?
1929 /// `.len()` is more efficient and more
1935 /// let some_vec = vec![0, 1, 2, 3];
1936 /// let _ = some_vec.iter().count();
1937 /// let _ = &some_vec[..].iter().count();
1940 /// let some_vec = vec![0, 1, 2, 3];
1941 /// let _ = some_vec.len();
1942 /// let _ = &some_vec[..].len();
1944 #[clippy::version = "1.52.0"]
1947 "replace `.iter().count()` with `.len()`"
1950 declare_clippy_lint! {
1951 /// ### What it does
1952 /// Checks for calls to [`splitn`]
1953 /// (https://doc.rust-lang.org/std/primitive.str.html#method.splitn) and
1954 /// related functions with either zero or one splits.
1956 /// ### Why is this bad?
1957 /// These calls don't actually split the value and are
1958 /// likely to be intended as a different number.
1964 /// for x in s.splitn(1, ":") {
1970 /// for x in s.splitn(2, ":") {
1974 #[clippy::version = "1.54.0"]
1975 pub SUSPICIOUS_SPLITN,
1977 "checks for `.splitn(0, ..)` and `.splitn(1, ..)`"
1980 declare_clippy_lint! {
1981 /// ### What it does
1982 /// Checks for manual implementations of `str::repeat`
1984 /// ### Why is this bad?
1985 /// These are both harder to read, as well as less performant.
1990 /// let x: String = std::iter::repeat('x').take(10).collect();
1993 /// let x: String = "x".repeat(10);
1995 #[clippy::version = "1.54.0"]
1996 pub MANUAL_STR_REPEAT,
1998 "manual implementation of `str::repeat`"
2001 declare_clippy_lint! {
2002 /// ### What it does
2003 /// Checks for usages of `str::splitn(2, _)`
2005 /// ### Why is this bad?
2006 /// `split_once` is both clearer in intent and slightly more efficient.
2011 /// let (key, value) = _.splitn(2, '=').next_tuple()?;
2012 /// let value = _.splitn(2, '=').nth(1)?;
2015 /// let (key, value) = _.split_once('=')?;
2016 /// let value = _.split_once('=')?.1;
2018 #[clippy::version = "1.57.0"]
2019 pub MANUAL_SPLIT_ONCE,
2021 "replace `.splitn(2, pat)` with `.split_once(pat)`"
2024 declare_clippy_lint! {
2025 /// ### What it does
2026 /// Checks for usages of `str::splitn` (or `str::rsplitn`) where using `str::split` would be the same.
2027 /// ### Why is this bad?
2028 /// The function `split` is simpler and there is no performance difference in these cases, considering
2029 /// that both functions return a lazy iterator.
2033 /// let str = "key=value=add";
2034 /// let _ = str.splitn(3, '=').next().unwrap();
2039 /// let str = "key=value=add";
2040 /// let _ = str.split('=').next().unwrap();
2042 #[clippy::version = "1.58.0"]
2043 pub NEEDLESS_SPLITN,
2045 "usages of `str::splitn` that can be replaced with `str::split`"
2048 declare_clippy_lint! {
2049 /// ### What it does
2050 /// Checks for unnecessary calls to [`ToOwned::to_owned`](https://doc.rust-lang.org/std/borrow/trait.ToOwned.html#tymethod.to_owned)
2051 /// and other `to_owned`-like functions.
2053 /// ### Why is this bad?
2054 /// The unnecessary calls result in useless allocations.
2056 /// ### Known problems
2057 /// `unnecessary_to_owned` can falsely trigger if `IntoIterator::into_iter` is applied to an
2058 /// owned copy of a resource and the resource is later used mutably. See
2059 /// [#8148](https://github.com/rust-lang/rust-clippy/issues/8148).
2063 /// let path = std::path::Path::new("x");
2064 /// foo(&path.to_string_lossy().to_string());
2065 /// fn foo(s: &str) {}
2069 /// let path = std::path::Path::new("x");
2070 /// foo(&path.to_string_lossy());
2071 /// fn foo(s: &str) {}
2073 #[clippy::version = "1.58.0"]
2074 pub UNNECESSARY_TO_OWNED,
2076 "unnecessary calls to `to_owned`-like functions"
2079 declare_clippy_lint! {
2080 /// ### What it does
2081 /// Checks for use of `.collect::<Vec<String>>().join("")` on iterators.
2083 /// ### Why is this bad?
2084 /// `.collect::<String>()` is more concise and might be more performant
2088 /// let vector = vec!["hello", "world"];
2089 /// let output = vector.iter().map(|item| item.to_uppercase()).collect::<Vec<String>>().join("");
2090 /// println!("{}", output);
2092 /// The correct use would be:
2094 /// let vector = vec!["hello", "world"];
2095 /// let output = vector.iter().map(|item| item.to_uppercase()).collect::<String>();
2096 /// println!("{}", output);
2098 /// ### Known problems
2099 /// While `.collect::<String>()` is sometimes more performant, there are cases where
2100 /// using `.collect::<String>()` over `.collect::<Vec<String>>().join("")`
2101 /// will prevent loop unrolling and will result in a negative performance impact.
2103 /// Additionlly, differences have been observed between aarch64 and x86_64 assembly output,
2104 /// with aarch64 tending to producing faster assembly in more cases when using `.collect::<String>()`
2105 #[clippy::version = "1.61.0"]
2106 pub UNNECESSARY_JOIN,
2108 "using `.collect::<Vec<String>>().join(\"\")` on an iterator"
2111 declare_clippy_lint! {
2112 /// ### What it does
2113 /// Checks for no-op uses of `Option::{as_deref, as_deref_mut}`,
2114 /// for example, `Option<&T>::as_deref()` returns the same type.
2116 /// ### Why is this bad?
2117 /// Redundant code and improving readability.
2121 /// let a = Some(&1);
2122 /// let b = a.as_deref(); // goes from Option<&i32> to Option<&i32>
2124 /// Could be written as:
2126 /// let a = Some(&1);
2129 #[clippy::version = "1.57.0"]
2130 pub NEEDLESS_OPTION_AS_DEREF,
2132 "no-op use of `deref` or `deref_mut` method to `Option`."
2135 declare_clippy_lint! {
2136 /// ### What it does
2137 /// Finds usages of [`char::is_digit`]
2138 /// (https://doc.rust-lang.org/stable/std/primitive.char.html#method.is_digit) that
2139 /// can be replaced with [`is_ascii_digit`]
2140 /// (https://doc.rust-lang.org/stable/std/primitive.char.html#method.is_ascii_digit) or
2141 /// [`is_ascii_hexdigit`]
2142 /// (https://doc.rust-lang.org/stable/std/primitive.char.html#method.is_ascii_hexdigit).
2144 /// ### Why is this bad?
2145 /// `is_digit(..)` is slower and requires specifying the radix.
2149 /// let c: char = '6';
2155 /// let c: char = '6';
2156 /// c.is_ascii_digit();
2157 /// c.is_ascii_hexdigit();
2159 #[clippy::version = "1.61.0"]
2160 pub IS_DIGIT_ASCII_RADIX,
2162 "use of `char::is_digit(..)` with literal radix of 10 or 16"
2165 pub struct Methods {
2166 avoid_breaking_exported_api: bool,
2167 msrv: Option<RustcVersion>,
2172 pub fn new(avoid_breaking_exported_api: bool, msrv: Option<RustcVersion>) -> Self {
2174 avoid_breaking_exported_api,
2180 impl_lint_pass!(Methods => [
2183 SHOULD_IMPLEMENT_TRAIT,
2184 WRONG_SELF_CONVENTION,
2186 UNWRAP_OR_ELSE_DEFAULT,
2188 RESULT_MAP_OR_INTO_OPTION,
2190 BIND_INSTEAD_OF_MAP,
2199 ITER_OVEREAGER_CLONED,
2200 CLONED_INSTEAD_OF_COPIED,
2202 INEFFICIENT_TO_STRING,
2204 SINGLE_CHAR_PATTERN,
2205 SINGLE_CHAR_ADD_STR,
2209 FILTER_MAP_IDENTITY,
2217 ITERATOR_STEP_BY_ZERO,
2225 STRING_EXTEND_CHARS,
2226 ITER_CLONED_COLLECT,
2230 UNNECESSARY_FILTER_MAP,
2231 UNNECESSARY_FIND_MAP,
2234 UNINIT_ASSUMED_INIT,
2235 MANUAL_SATURATING_ARITHMETIC,
2238 OPTION_AS_REF_DEREF,
2239 UNNECESSARY_LAZY_EVALUATIONS,
2240 MAP_COLLECT_RESULT_UNIT,
2241 FROM_ITER_INSTEAD_OF_COLLECT,
2249 UNNECESSARY_TO_OWNED,
2252 NEEDLESS_OPTION_AS_DEREF,
2253 IS_DIGIT_ASCII_RADIX,
2256 /// Extracts a method call name, args, and `Span` of the method name.
2257 fn method_call<'tcx>(recv: &'tcx hir::Expr<'tcx>) -> Option<(&'tcx str, &'tcx [hir::Expr<'tcx>], Span)> {
2258 if let ExprKind::MethodCall(path, args, _) = recv.kind {
2259 if !args.iter().any(|e| e.span.from_expansion()) {
2260 let name = path.ident.name.as_str();
2261 return Some((name, args, path.ident.span));
2267 impl<'tcx> LateLintPass<'tcx> for Methods {
2268 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) {
2269 if expr.span.from_expansion() {
2273 check_methods(cx, expr, self.msrv.as_ref());
2276 hir::ExprKind::Call(func, args) => {
2277 from_iter_instead_of_collect::check(cx, expr, args, func);
2279 hir::ExprKind::MethodCall(method_call, args, _) => {
2280 let method_span = method_call.ident.span;
2281 or_fun_call::check(cx, expr, method_span, method_call.ident.as_str(), args);
2282 expect_fun_call::check(cx, expr, method_span, method_call.ident.as_str(), args);
2283 clone_on_copy::check(cx, expr, method_call.ident.name, args);
2284 clone_on_ref_ptr::check(cx, expr, method_call.ident.name, args);
2285 inefficient_to_string::check(cx, expr, method_call.ident.name, args);
2286 single_char_add_str::check(cx, expr, args);
2287 into_iter_on_ref::check(cx, expr, method_span, method_call.ident.name, args);
2288 single_char_pattern::check(cx, expr, method_call.ident.name, args);
2289 unnecessary_to_owned::check(cx, expr, method_call.ident.name, args);
2291 hir::ExprKind::Binary(op, lhs, rhs) if op.node == hir::BinOpKind::Eq || op.node == hir::BinOpKind::Ne => {
2292 let mut info = BinaryExprInfo {
2296 eq: op.node == hir::BinOpKind::Eq,
2298 lint_binary_expr_with_method_call(cx, &mut info);
2304 #[allow(clippy::too_many_lines)]
2305 fn check_impl_item(&mut self, cx: &LateContext<'tcx>, impl_item: &'tcx hir::ImplItem<'_>) {
2306 if in_external_macro(cx.sess(), impl_item.span) {
2309 let name = impl_item.ident.name.as_str();
2310 let parent = cx.tcx.hir().get_parent_item(impl_item.hir_id());
2311 let item = cx.tcx.hir().expect_item(parent);
2312 let self_ty = cx.tcx.type_of(item.def_id);
2314 let implements_trait = matches!(item.kind, hir::ItemKind::Impl(hir::Impl { of_trait: Some(_), .. }));
2316 if let hir::ImplItemKind::Fn(ref sig, id) = impl_item.kind;
2317 if let Some(first_arg) = iter_input_pats(sig.decl, cx.tcx.hir().body(id)).next();
2319 let method_sig = cx.tcx.fn_sig(impl_item.def_id);
2320 let method_sig = cx.tcx.erase_late_bound_regions(method_sig);
2322 let first_arg_ty = method_sig.inputs().iter().next();
2324 // check conventions w.r.t. conversion method names and predicates
2325 if let Some(first_arg_ty) = first_arg_ty;
2328 // if this impl block implements a trait, lint in trait definition instead
2329 if !implements_trait && cx.access_levels.is_exported(impl_item.def_id) {
2330 // check missing trait implementations
2331 for method_config in &TRAIT_METHODS {
2332 if name == method_config.method_name &&
2333 sig.decl.inputs.len() == method_config.param_count &&
2334 method_config.output_type.matches(&sig.decl.output) &&
2335 method_config.self_kind.matches(cx, self_ty, *first_arg_ty) &&
2336 fn_header_equals(method_config.fn_header, sig.header) &&
2337 method_config.lifetime_param_cond(impl_item)
2341 SHOULD_IMPLEMENT_TRAIT,
2344 "method `{}` can be confused for the standard trait method `{}::{}`",
2345 method_config.method_name,
2346 method_config.trait_name,
2347 method_config.method_name
2351 "consider implementing the trait `{}` or choosing a less ambiguous method name",
2352 method_config.trait_name
2359 if sig.decl.implicit_self.has_implicit_self()
2360 && !(self.avoid_breaking_exported_api
2361 && cx.access_levels.is_exported(impl_item.def_id))
2363 wrong_self_convention::check(
2376 // if this impl block implements a trait, lint in trait definition instead
2377 if implements_trait {
2381 if let hir::ImplItemKind::Fn(_, _) = impl_item.kind {
2382 let ret_ty = return_ty(cx, impl_item.hir_id());
2384 // walk the return type and check for Self (this does not check associated types)
2385 if let Some(self_adt) = self_ty.ty_adt_def() {
2386 if contains_adt_constructor(ret_ty, self_adt) {
2389 } else if contains_ty(ret_ty, self_ty) {
2393 // if return type is impl trait, check the associated types
2394 if let ty::Opaque(def_id, _) = *ret_ty.kind() {
2395 // one of the associated types must be Self
2396 for &(predicate, _span) in cx.tcx.explicit_item_bounds(def_id) {
2397 if let ty::PredicateKind::Projection(projection_predicate) = predicate.kind().skip_binder() {
2398 let assoc_ty = match projection_predicate.term {
2399 ty::Term::Ty(ty) => ty,
2400 ty::Term::Const(_c) => continue,
2402 // walk the associated type and check for Self
2403 if let Some(self_adt) = self_ty.ty_adt_def() {
2404 if contains_adt_constructor(assoc_ty, self_adt) {
2407 } else if contains_ty(assoc_ty, self_ty) {
2414 if name == "new" && ret_ty != self_ty {
2419 "methods called `new` usually return `Self`",
2425 fn check_trait_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx TraitItem<'_>) {
2426 if in_external_macro(cx.tcx.sess, item.span) {
2431 if let TraitItemKind::Fn(ref sig, _) = item.kind;
2432 if sig.decl.implicit_self.has_implicit_self();
2433 if let Some(first_arg_ty) = sig.decl.inputs.iter().next();
2436 let first_arg_span = first_arg_ty.span;
2437 let first_arg_ty = hir_ty_to_ty(cx.tcx, first_arg_ty);
2438 let self_ty = TraitRef::identity(cx.tcx, item.def_id.to_def_id()).self_ty().skip_binder();
2439 wrong_self_convention::check(
2441 item.ident.name.as_str(),
2452 if item.ident.name == sym::new;
2453 if let TraitItemKind::Fn(_, _) = item.kind;
2454 let ret_ty = return_ty(cx, item.hir_id());
2455 let self_ty = TraitRef::identity(cx.tcx, item.def_id.to_def_id()).self_ty().skip_binder();
2456 if !contains_ty(ret_ty, self_ty);
2463 "methods called `new` usually return `Self`",
2469 extract_msrv_attr!(LateContext);
2472 #[allow(clippy::too_many_lines)]
2473 fn check_methods<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, msrv: Option<&RustcVersion>) {
2474 if let Some((name, [recv, args @ ..], span)) = method_call(expr) {
2475 match (name, args) {
2476 ("add" | "offset" | "sub" | "wrapping_offset" | "wrapping_add" | "wrapping_sub", [_arg]) => {
2477 zst_offset::check(cx, expr, recv);
2479 ("and_then", [arg]) => {
2480 let biom_option_linted = bind_instead_of_map::OptionAndThenSome::check(cx, expr, recv, arg);
2481 let biom_result_linted = bind_instead_of_map::ResultAndThenOk::check(cx, expr, recv, arg);
2482 if !biom_option_linted && !biom_result_linted {
2483 unnecessary_lazy_eval::check(cx, expr, recv, arg, "and");
2486 ("as_deref" | "as_deref_mut", []) => {
2487 needless_option_as_deref::check(cx, expr, recv, name);
2489 ("as_mut", []) => useless_asref::check(cx, expr, "as_mut", recv),
2490 ("as_ref", []) => useless_asref::check(cx, expr, "as_ref", recv),
2491 ("assume_init", []) => uninit_assumed_init::check(cx, expr, recv),
2492 ("cloned", []) => cloned_instead_of_copied::check(cx, expr, recv, span, msrv),
2493 ("collect", []) => match method_call(recv) {
2494 Some((name @ ("cloned" | "copied"), [recv2], _)) => {
2495 iter_cloned_collect::check(cx, name, expr, recv2);
2497 Some(("map", [m_recv, m_arg], _)) => {
2498 map_collect_result_unit::check(cx, expr, m_recv, m_arg, recv);
2500 Some(("take", [take_self_arg, take_arg], _)) => {
2501 if meets_msrv(msrv, &msrvs::STR_REPEAT) {
2502 manual_str_repeat::check(cx, expr, recv, take_self_arg, take_arg);
2507 (name @ "count", args @ []) => match method_call(recv) {
2508 Some(("cloned", [recv2], _)) => iter_overeager_cloned::check(cx, expr, recv2, name, args),
2509 Some((name2 @ ("into_iter" | "iter" | "iter_mut"), [recv2], _)) => {
2510 iter_count::check(cx, expr, recv2, name2);
2512 Some(("map", [_, arg], _)) => suspicious_map::check(cx, expr, recv, arg),
2515 ("drain", [arg]) => {
2516 iter_with_drain::check(cx, expr, recv, span, arg);
2518 ("expect", [_]) => match method_call(recv) {
2519 Some(("ok", [recv], _)) => ok_expect::check(cx, expr, recv),
2520 Some(("err", [recv], err_span)) => err_expect::check(cx, expr, recv, msrv, span, err_span),
2521 _ => expect_used::check(cx, expr, recv),
2523 ("extend", [arg]) => {
2524 string_extend_chars::check(cx, expr, recv, arg);
2525 extend_with_drain::check(cx, expr, recv, arg);
2527 ("filter_map", [arg]) => {
2528 unnecessary_filter_map::check(cx, expr, arg, name);
2529 filter_map_identity::check(cx, expr, arg, span);
2531 ("find_map", [arg]) => {
2532 unnecessary_filter_map::check(cx, expr, arg, name);
2534 ("flat_map", [arg]) => {
2535 flat_map_identity::check(cx, expr, arg, span);
2536 flat_map_option::check(cx, expr, arg, span);
2538 (name @ "flatten", args @ []) => match method_call(recv) {
2539 Some(("map", [recv, map_arg], map_span)) => map_flatten::check(cx, expr, recv, map_arg, map_span),
2540 Some(("cloned", [recv2], _)) => iter_overeager_cloned::check(cx, expr, recv2, name, args),
2543 ("fold", [init, acc]) => unnecessary_fold::check(cx, expr, init, acc, span),
2544 ("for_each", [_]) => {
2545 if let Some(("inspect", [_, _], span2)) = method_call(recv) {
2546 inspect_for_each::check(cx, expr, span2);
2549 ("get_or_insert_with", [arg]) => unnecessary_lazy_eval::check(cx, expr, recv, arg, "get_or_insert"),
2550 ("is_file", []) => filetype_is_file::check(cx, expr, recv),
2551 ("is_digit", [radix]) => is_digit_ascii_radix::check(cx, expr, recv, radix, msrv),
2552 ("is_none", []) => check_is_some_is_none(cx, expr, recv, false),
2553 ("is_some", []) => check_is_some_is_none(cx, expr, recv, true),
2554 ("join", [join_arg]) => {
2555 if let Some(("collect", _, span)) = method_call(recv) {
2556 unnecessary_join::check(cx, expr, recv, join_arg, span);
2559 ("last", args @ []) | ("skip", args @ [_]) => {
2560 if let Some((name2, [recv2, args2 @ ..], _span2)) = method_call(recv) {
2561 if let ("cloned", []) = (name2, args2) {
2562 iter_overeager_cloned::check(cx, expr, recv2, name, args);
2566 (name @ ("map" | "map_err"), [m_arg]) => {
2567 if let Some((name, [recv2, args @ ..], span2)) = method_call(recv) {
2568 match (name, args) {
2569 ("as_mut", []) => option_as_ref_deref::check(cx, expr, recv2, m_arg, true, msrv),
2570 ("as_ref", []) => option_as_ref_deref::check(cx, expr, recv2, m_arg, false, msrv),
2571 ("filter", [f_arg]) => {
2572 filter_map::check(cx, expr, recv2, f_arg, span2, recv, m_arg, span, false);
2574 ("find", [f_arg]) => filter_map::check(cx, expr, recv2, f_arg, span2, recv, m_arg, span, true),
2578 map_identity::check(cx, expr, recv, m_arg, name, span);
2580 ("map_or", [def, map]) => option_map_or_none::check(cx, expr, recv, def, map),
2581 (name @ "next", args @ []) => {
2582 if let Some((name2, [recv2, args2 @ ..], _)) = method_call(recv) {
2583 match (name2, args2) {
2584 ("cloned", []) => iter_overeager_cloned::check(cx, expr, recv2, name, args),
2585 ("filter", [arg]) => filter_next::check(cx, expr, recv2, arg),
2586 ("filter_map", [arg]) => filter_map_next::check(cx, expr, recv2, arg, msrv),
2587 ("iter", []) => iter_next_slice::check(cx, expr, recv2),
2588 ("skip", [arg]) => iter_skip_next::check(cx, expr, recv2, arg),
2589 ("skip_while", [_]) => skip_while_next::check(cx, expr),
2594 ("nth", args @ [n_arg]) => match method_call(recv) {
2595 Some(("bytes", [recv2], _)) => bytes_nth::check(cx, expr, recv2, n_arg),
2596 Some(("cloned", [recv2], _)) => iter_overeager_cloned::check(cx, expr, recv2, name, args),
2597 Some(("iter", [recv2], _)) => iter_nth::check(cx, expr, recv2, recv, n_arg, false),
2598 Some(("iter_mut", [recv2], _)) => iter_nth::check(cx, expr, recv2, recv, n_arg, true),
2599 _ => iter_nth_zero::check(cx, expr, recv, n_arg),
2601 ("ok_or_else", [arg]) => unnecessary_lazy_eval::check(cx, expr, recv, arg, "ok_or"),
2602 ("or_else", [arg]) => {
2603 if !bind_instead_of_map::ResultOrElseErrInfo::check(cx, expr, recv, arg) {
2604 unnecessary_lazy_eval::check(cx, expr, recv, arg, "or");
2607 ("splitn" | "rsplitn", [count_arg, pat_arg]) => {
2608 if let Some((Constant::Int(count), _)) = constant(cx, cx.typeck_results(), count_arg) {
2609 suspicious_splitn::check(cx, name, expr, recv, count);
2610 str_splitn::check(cx, name, expr, recv, pat_arg, count, msrv);
2613 ("splitn_mut" | "rsplitn_mut", [count_arg, _]) => {
2614 if let Some((Constant::Int(count), _)) = constant(cx, cx.typeck_results(), count_arg) {
2615 suspicious_splitn::check(cx, name, expr, recv, count);
2618 ("step_by", [arg]) => iterator_step_by_zero::check(cx, expr, arg),
2619 ("take", args @ [_arg]) => {
2620 if let Some((name2, [recv2, args2 @ ..], _span2)) = method_call(recv) {
2621 if let ("cloned", []) = (name2, args2) {
2622 iter_overeager_cloned::check(cx, expr, recv2, name, args);
2626 ("to_os_string" | "to_owned" | "to_path_buf" | "to_vec", []) => {
2627 implicit_clone::check(cx, name, expr, recv);
2630 match method_call(recv) {
2631 Some(("get", [recv, get_arg], _)) => {
2632 get_unwrap::check(cx, expr, recv, get_arg, false);
2634 Some(("get_mut", [recv, get_arg], _)) => {
2635 get_unwrap::check(cx, expr, recv, get_arg, true);
2637 Some(("or", [recv, or_arg], or_span)) => {
2638 or_then_unwrap::check(cx, expr, recv, or_arg, or_span);
2642 unwrap_used::check(cx, expr, recv);
2644 ("unwrap_or", [u_arg]) => match method_call(recv) {
2645 Some((arith @ ("checked_add" | "checked_sub" | "checked_mul"), [lhs, rhs], _)) => {
2646 manual_saturating_arithmetic::check(cx, expr, lhs, rhs, u_arg, &arith["checked_".len()..]);
2648 Some(("map", [m_recv, m_arg], span)) => {
2649 option_map_unwrap_or::check(cx, expr, m_recv, m_arg, recv, u_arg, span);
2653 ("unwrap_or_else", [u_arg]) => match method_call(recv) {
2654 Some(("map", [recv, map_arg], _)) if map_unwrap_or::check(cx, expr, recv, map_arg, u_arg, msrv) => {},
2656 unwrap_or_else_default::check(cx, expr, recv, u_arg);
2657 unnecessary_lazy_eval::check(cx, expr, recv, u_arg, "unwrap_or");
2665 fn check_is_some_is_none(cx: &LateContext<'_>, expr: &Expr<'_>, recv: &Expr<'_>, is_some: bool) {
2666 if let Some((name @ ("find" | "position" | "rposition"), [f_recv, arg], span)) = method_call(recv) {
2667 search_is_some::check(cx, expr, name, is_some, f_recv, arg, recv, span);
2671 /// Used for `lint_binary_expr_with_method_call`.
2672 #[derive(Copy, Clone)]
2673 struct BinaryExprInfo<'a> {
2674 expr: &'a hir::Expr<'a>,
2675 chain: &'a hir::Expr<'a>,
2676 other: &'a hir::Expr<'a>,
2680 /// Checks for the `CHARS_NEXT_CMP` and `CHARS_LAST_CMP` lints.
2681 fn lint_binary_expr_with_method_call(cx: &LateContext<'_>, info: &mut BinaryExprInfo<'_>) {
2682 macro_rules! lint_with_both_lhs_and_rhs {
2683 ($func:expr, $cx:expr, $info:ident) => {
2684 if !$func($cx, $info) {
2685 ::std::mem::swap(&mut $info.chain, &mut $info.other);
2686 if $func($cx, $info) {
2693 lint_with_both_lhs_and_rhs!(chars_next_cmp::check, cx, info);
2694 lint_with_both_lhs_and_rhs!(chars_last_cmp::check, cx, info);
2695 lint_with_both_lhs_and_rhs!(chars_next_cmp_with_unwrap::check, cx, info);
2696 lint_with_both_lhs_and_rhs!(chars_last_cmp_with_unwrap::check, cx, info);
2699 const FN_HEADER: hir::FnHeader = hir::FnHeader {
2700 unsafety: hir::Unsafety::Normal,
2701 constness: hir::Constness::NotConst,
2702 asyncness: hir::IsAsync::NotAsync,
2703 abi: rustc_target::spec::abi::Abi::Rust,
2706 struct ShouldImplTraitCase {
2707 trait_name: &'static str,
2708 method_name: &'static str,
2710 fn_header: hir::FnHeader,
2711 // implicit self kind expected (none, self, &self, ...)
2712 self_kind: SelfKind,
2713 // checks against the output type
2714 output_type: OutType,
2715 // certain methods with explicit lifetimes can't implement the equivalent trait method
2716 lint_explicit_lifetime: bool,
2718 impl ShouldImplTraitCase {
2720 trait_name: &'static str,
2721 method_name: &'static str,
2723 fn_header: hir::FnHeader,
2724 self_kind: SelfKind,
2725 output_type: OutType,
2726 lint_explicit_lifetime: bool,
2727 ) -> ShouldImplTraitCase {
2728 ShouldImplTraitCase {
2735 lint_explicit_lifetime,
2739 fn lifetime_param_cond(&self, impl_item: &hir::ImplItem<'_>) -> bool {
2740 self.lint_explicit_lifetime
2741 || !impl_item.generics.params.iter().any(|p| {
2744 hir::GenericParamKind::Lifetime {
2745 kind: hir::LifetimeParamKind::Explicit
2753 const TRAIT_METHODS: [ShouldImplTraitCase; 30] = [
2754 ShouldImplTraitCase::new("std::ops::Add", "add", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
2755 ShouldImplTraitCase::new("std::convert::AsMut", "as_mut", 1, FN_HEADER, SelfKind::RefMut, OutType::Ref, true),
2756 ShouldImplTraitCase::new("std::convert::AsRef", "as_ref", 1, FN_HEADER, SelfKind::Ref, OutType::Ref, true),
2757 ShouldImplTraitCase::new("std::ops::BitAnd", "bitand", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
2758 ShouldImplTraitCase::new("std::ops::BitOr", "bitor", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
2759 ShouldImplTraitCase::new("std::ops::BitXor", "bitxor", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
2760 ShouldImplTraitCase::new("std::borrow::Borrow", "borrow", 1, FN_HEADER, SelfKind::Ref, OutType::Ref, true),
2761 ShouldImplTraitCase::new("std::borrow::BorrowMut", "borrow_mut", 1, FN_HEADER, SelfKind::RefMut, OutType::Ref, true),
2762 ShouldImplTraitCase::new("std::clone::Clone", "clone", 1, FN_HEADER, SelfKind::Ref, OutType::Any, true),
2763 ShouldImplTraitCase::new("std::cmp::Ord", "cmp", 2, FN_HEADER, SelfKind::Ref, OutType::Any, true),
2764 // FIXME: default doesn't work
2765 ShouldImplTraitCase::new("std::default::Default", "default", 0, FN_HEADER, SelfKind::No, OutType::Any, true),
2766 ShouldImplTraitCase::new("std::ops::Deref", "deref", 1, FN_HEADER, SelfKind::Ref, OutType::Ref, true),
2767 ShouldImplTraitCase::new("std::ops::DerefMut", "deref_mut", 1, FN_HEADER, SelfKind::RefMut, OutType::Ref, true),
2768 ShouldImplTraitCase::new("std::ops::Div", "div", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
2769 ShouldImplTraitCase::new("std::ops::Drop", "drop", 1, FN_HEADER, SelfKind::RefMut, OutType::Unit, true),
2770 ShouldImplTraitCase::new("std::cmp::PartialEq", "eq", 2, FN_HEADER, SelfKind::Ref, OutType::Bool, true),
2771 ShouldImplTraitCase::new("std::iter::FromIterator", "from_iter", 1, FN_HEADER, SelfKind::No, OutType::Any, true),
2772 ShouldImplTraitCase::new("std::str::FromStr", "from_str", 1, FN_HEADER, SelfKind::No, OutType::Any, true),
2773 ShouldImplTraitCase::new("std::hash::Hash", "hash", 2, FN_HEADER, SelfKind::Ref, OutType::Unit, true),
2774 ShouldImplTraitCase::new("std::ops::Index", "index", 2, FN_HEADER, SelfKind::Ref, OutType::Ref, true),
2775 ShouldImplTraitCase::new("std::ops::IndexMut", "index_mut", 2, FN_HEADER, SelfKind::RefMut, OutType::Ref, true),
2776 ShouldImplTraitCase::new("std::iter::IntoIterator", "into_iter", 1, FN_HEADER, SelfKind::Value, OutType::Any, true),
2777 ShouldImplTraitCase::new("std::ops::Mul", "mul", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
2778 ShouldImplTraitCase::new("std::ops::Neg", "neg", 1, FN_HEADER, SelfKind::Value, OutType::Any, true),
2779 ShouldImplTraitCase::new("std::iter::Iterator", "next", 1, FN_HEADER, SelfKind::RefMut, OutType::Any, false),
2780 ShouldImplTraitCase::new("std::ops::Not", "not", 1, FN_HEADER, SelfKind::Value, OutType::Any, true),
2781 ShouldImplTraitCase::new("std::ops::Rem", "rem", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
2782 ShouldImplTraitCase::new("std::ops::Shl", "shl", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
2783 ShouldImplTraitCase::new("std::ops::Shr", "shr", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
2784 ShouldImplTraitCase::new("std::ops::Sub", "sub", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
2787 #[derive(Clone, Copy, PartialEq, Debug)]
2796 fn matches<'a>(self, cx: &LateContext<'a>, parent_ty: Ty<'a>, ty: Ty<'a>) -> bool {
2797 fn matches_value<'a>(cx: &LateContext<'a>, parent_ty: Ty<'_>, ty: Ty<'_>) -> bool {
2798 if ty == parent_ty {
2800 } else if ty.is_box() {
2801 ty.boxed_ty() == parent_ty
2802 } else if is_type_diagnostic_item(cx, ty, sym::Rc) || is_type_diagnostic_item(cx, ty, sym::Arc) {
2803 if let ty::Adt(_, substs) = ty.kind() {
2804 substs.types().next().map_or(false, |t| t == parent_ty)
2813 fn matches_ref<'a>(cx: &LateContext<'a>, mutability: hir::Mutability, parent_ty: Ty<'a>, ty: Ty<'a>) -> bool {
2814 if let ty::Ref(_, t, m) = *ty.kind() {
2815 return m == mutability && t == parent_ty;
2818 let trait_path = match mutability {
2819 hir::Mutability::Not => &paths::ASREF_TRAIT,
2820 hir::Mutability::Mut => &paths::ASMUT_TRAIT,
2823 let trait_def_id = match get_trait_def_id(cx, trait_path) {
2825 None => return false,
2827 implements_trait(cx, ty, trait_def_id, &[parent_ty.into()])
2830 fn matches_none<'a>(cx: &LateContext<'a>, parent_ty: Ty<'a>, ty: Ty<'a>) -> bool {
2831 !matches_value(cx, parent_ty, ty)
2832 && !matches_ref(cx, hir::Mutability::Not, parent_ty, ty)
2833 && !matches_ref(cx, hir::Mutability::Mut, parent_ty, ty)
2837 Self::Value => matches_value(cx, parent_ty, ty),
2838 Self::Ref => matches_ref(cx, hir::Mutability::Not, parent_ty, ty) || ty == parent_ty && is_copy(cx, ty),
2839 Self::RefMut => matches_ref(cx, hir::Mutability::Mut, parent_ty, ty),
2840 Self::No => matches_none(cx, parent_ty, ty),
2845 fn description(self) -> &'static str {
2847 Self::Value => "`self` by value",
2848 Self::Ref => "`self` by reference",
2849 Self::RefMut => "`self` by mutable reference",
2850 Self::No => "no `self`",
2855 #[derive(Clone, Copy)]
2864 fn matches(self, ty: &hir::FnRetTy<'_>) -> bool {
2865 let is_unit = |ty: &hir::Ty<'_>| matches!(ty.kind, hir::TyKind::Tup(&[]));
2867 (Self::Unit, &hir::FnRetTy::DefaultReturn(_)) => true,
2868 (Self::Unit, &hir::FnRetTy::Return(ty)) if is_unit(ty) => true,
2869 (Self::Bool, &hir::FnRetTy::Return(ty)) if is_bool(ty) => true,
2870 (Self::Any, &hir::FnRetTy::Return(ty)) if !is_unit(ty) => true,
2871 (Self::Ref, &hir::FnRetTy::Return(ty)) => matches!(ty.kind, hir::TyKind::Rptr(_, _)),
2877 fn is_bool(ty: &hir::Ty<'_>) -> bool {
2878 if let hir::TyKind::Path(QPath::Resolved(_, path)) = ty.kind {
2879 matches!(path.res, Res::PrimTy(PrimTy::Bool))
2885 fn fn_header_equals(expected: hir::FnHeader, actual: hir::FnHeader) -> bool {
2886 expected.constness == actual.constness
2887 && expected.unsafety == actual.unsafety
2888 && expected.asyncness == actual.asyncness