1 mod bind_instead_of_map;
3 mod bytes_count_to_len;
5 mod case_sensitive_file_extension_comparisons;
7 mod chars_cmp_with_unwrap;
9 mod chars_last_cmp_with_unwrap;
11 mod chars_next_cmp_with_unwrap;
14 mod cloned_instead_of_copied;
18 mod extend_with_drain;
21 mod filter_map_identity;
24 mod flat_map_identity;
26 mod from_iter_instead_of_collect;
28 mod get_last_with_len;
31 mod inefficient_to_string;
34 mod is_digit_ascii_radix;
35 mod iter_cloned_collect;
40 mod iter_on_single_or_empty_collections;
41 mod iter_overeager_cloned;
44 mod iterator_step_by_zero;
46 mod manual_saturating_arithmetic;
47 mod manual_str_repeat;
49 mod map_collect_result_unit;
55 mod needless_option_as_deref;
56 mod needless_option_take;
57 mod no_effect_replace;
58 mod obfuscated_if_else;
60 mod option_as_ref_deref;
61 mod option_map_or_none;
62 mod option_map_unwrap_or;
66 mod single_char_add_str;
67 mod single_char_insert_string;
68 mod single_char_pattern;
69 mod single_char_push_string;
72 mod string_extend_chars;
74 mod suspicious_splitn;
75 mod uninit_assumed_init;
76 mod unnecessary_filter_map;
78 mod unnecessary_iter_cloned;
80 mod unnecessary_lazy_eval;
81 mod unnecessary_to_owned;
82 mod unwrap_or_else_default;
86 mod wrong_self_convention;
89 use bind_instead_of_map::BindInsteadOfMap;
90 use clippy_utils::consts::{constant, Constant};
91 use clippy_utils::diagnostics::{span_lint, span_lint_and_help};
92 use clippy_utils::ty::{contains_adt_constructor, contains_ty, implements_trait, is_copy, is_type_diagnostic_item};
94 contains_return, get_trait_def_id, is_trait_method, iter_input_pats, meets_msrv, msrvs, paths, return_ty,
96 use if_chain::if_chain;
98 use rustc_hir::def::Res;
99 use rustc_hir::{Expr, ExprKind, PrimTy, QPath, TraitItem, TraitItemKind};
100 use rustc_lint::{LateContext, LateLintPass, LintContext};
101 use rustc_middle::lint::in_external_macro;
102 use rustc_middle::ty::{self, TraitRef, Ty};
103 use rustc_semver::RustcVersion;
104 use rustc_session::{declare_tool_lint, impl_lint_pass};
105 use rustc_span::{sym, Span};
106 use rustc_typeck::hir_ty_to_ty;
108 declare_clippy_lint! {
110 /// Checks for usages of `cloned()` on an `Iterator` or `Option` where
111 /// `copied()` could be used instead.
113 /// ### Why is this bad?
114 /// `copied()` is better because it guarantees that the type being cloned
115 /// implements `Copy`.
119 /// [1, 2, 3].iter().cloned();
123 /// [1, 2, 3].iter().copied();
125 #[clippy::version = "1.53.0"]
126 pub CLONED_INSTEAD_OF_COPIED,
128 "used `cloned` where `copied` could be used instead"
131 declare_clippy_lint! {
133 /// Checks for usage of `_.cloned().<func>()` where call to `.cloned()` can be postponed.
135 /// ### Why is this bad?
136 /// It's often inefficient to clone all elements of an iterator, when eventually, only some
137 /// of them will be consumed.
139 /// ### Known Problems
140 /// This `lint` removes the side of effect of cloning items in the iterator.
141 /// A code that relies on that side-effect could fail.
145 /// # let vec = vec!["string".to_string()];
146 /// vec.iter().cloned().take(10);
147 /// vec.iter().cloned().last();
152 /// # let vec = vec!["string".to_string()];
153 /// vec.iter().take(10).cloned();
154 /// vec.iter().last().cloned();
156 #[clippy::version = "1.60.0"]
157 pub ITER_OVEREAGER_CLONED,
159 "using `cloned()` early with `Iterator::iter()` can lead to some performance inefficiencies"
162 declare_clippy_lint! {
164 /// Checks for usages of `Iterator::flat_map()` where `filter_map()` could be
167 /// ### Why is this bad?
168 /// When applicable, `filter_map()` is more clear since it shows that
169 /// `Option` is used to produce 0 or 1 items.
173 /// let nums: Vec<i32> = ["1", "2", "whee!"].iter().flat_map(|x| x.parse().ok()).collect();
177 /// let nums: Vec<i32> = ["1", "2", "whee!"].iter().filter_map(|x| x.parse().ok()).collect();
179 #[clippy::version = "1.53.0"]
182 "used `flat_map` where `filter_map` could be used instead"
185 declare_clippy_lint! {
187 /// Checks for `.unwrap()` or `.unwrap_err()` calls on `Result`s and `.unwrap()` call on `Option`s.
189 /// ### Why is this bad?
190 /// It is better to handle the `None` or `Err` case,
191 /// or at least call `.expect(_)` with a more helpful message. Still, for a lot of
192 /// quick-and-dirty code, `unwrap` is a good choice, which is why this lint is
193 /// `Allow` by default.
195 /// `result.unwrap()` will let the thread panic on `Err` values.
196 /// Normally, you want to implement more sophisticated error handling,
197 /// and propagate errors upwards with `?` operator.
199 /// Even if you want to panic on errors, not all `Error`s implement good
200 /// messages on display. Therefore, it may be beneficial to look at the places
201 /// where they may get displayed. Activate this lint to do just that.
205 /// # let option = Some(1);
206 /// # let result: Result<usize, ()> = Ok(1);
213 /// # let option = Some(1);
214 /// # let result: Result<usize, ()> = Ok(1);
215 /// option.expect("more helpful message");
216 /// result.expect("more helpful message");
219 /// If [expect_used](#expect_used) is enabled, instead:
221 /// # let option = Some(1);
222 /// # let result: Result<usize, ()> = Ok(1);
229 #[clippy::version = "1.45.0"]
232 "using `.unwrap()` on `Result` or `Option`, which should at least get a better message using `expect()`"
235 declare_clippy_lint! {
237 /// Checks for `.expect()` or `.expect_err()` calls on `Result`s and `.expect()` call on `Option`s.
239 /// ### Why is this bad?
240 /// Usually it is better to handle the `None` or `Err` case.
241 /// Still, for a lot of quick-and-dirty code, `expect` is a good choice, which is why
242 /// this lint is `Allow` by default.
244 /// `result.expect()` will let the thread panic on `Err`
245 /// values. Normally, you want to implement more sophisticated error handling,
246 /// and propagate errors upwards with `?` operator.
250 /// # let option = Some(1);
251 /// # let result: Result<usize, ()> = Ok(1);
252 /// option.expect("one");
253 /// result.expect("one");
258 /// # let option = Some(1);
259 /// # let result: Result<usize, ()> = Ok(1);
266 #[clippy::version = "1.45.0"]
269 "using `.expect()` on `Result` or `Option`, which might be better handled"
272 declare_clippy_lint! {
274 /// Checks for methods that should live in a trait
275 /// implementation of a `std` trait (see [llogiq's blog
276 /// post](http://llogiq.github.io/2015/07/30/traits.html) for further
277 /// information) instead of an inherent implementation.
279 /// ### Why is this bad?
280 /// Implementing the traits improve ergonomics for users of
281 /// the code, often with very little cost. Also people seeing a `mul(...)`
283 /// may expect `*` to work equally, so you should have good reason to disappoint
290 /// fn add(&self, other: &X) -> X {
296 #[clippy::version = "pre 1.29.0"]
297 pub SHOULD_IMPLEMENT_TRAIT,
299 "defining a method that should be implementing a std trait"
302 declare_clippy_lint! {
304 /// Checks for methods with certain name prefixes and which
305 /// doesn't match how self is taken. The actual rules are:
307 /// |Prefix |Postfix |`self` taken | `self` type |
308 /// |-------|------------|-------------------------------|--------------|
309 /// |`as_` | none |`&self` or `&mut self` | any |
310 /// |`from_`| none | none | any |
311 /// |`into_`| none |`self` | any |
312 /// |`is_` | none |`&mut self` or `&self` or none | any |
313 /// |`to_` | `_mut` |`&mut self` | any |
314 /// |`to_` | not `_mut` |`self` | `Copy` |
315 /// |`to_` | not `_mut` |`&self` | not `Copy` |
317 /// Note: Clippy doesn't trigger methods with `to_` prefix in:
318 /// - Traits definition.
319 /// Clippy can not tell if a type that implements a trait is `Copy` or not.
320 /// - Traits implementation, when `&self` is taken.
321 /// The method signature is controlled by the trait and often `&self` is required for all types that implement the trait
322 /// (see e.g. the `std::string::ToString` trait).
324 /// Clippy allows `Pin<&Self>` and `Pin<&mut Self>` if `&self` and `&mut self` is required.
326 /// Please find more info here:
327 /// https://rust-lang.github.io/api-guidelines/naming.html#ad-hoc-conversions-follow-as_-to_-into_-conventions-c-conv
329 /// ### Why is this bad?
330 /// Consistency breeds readability. If you follow the
331 /// conventions, your users won't be surprised that they, e.g., need to supply a
332 /// mutable reference to a `as_..` function.
338 /// fn as_str(self) -> &'static str {
344 #[clippy::version = "pre 1.29.0"]
345 pub WRONG_SELF_CONVENTION,
347 "defining a method named with an established prefix (like \"into_\") that takes `self` with the wrong convention"
350 declare_clippy_lint! {
352 /// Checks for usage of `ok().expect(..)`.
354 /// ### Why is this bad?
355 /// Because you usually call `expect()` on the `Result`
356 /// directly to get a better error message.
358 /// ### Known problems
359 /// The error type needs to implement `Debug`
363 /// # let x = Ok::<_, ()>(());
364 /// x.ok().expect("why did I do this again?");
369 /// # let x = Ok::<_, ()>(());
370 /// x.expect("why did I do this again?");
372 #[clippy::version = "pre 1.29.0"]
375 "using `ok().expect()`, which gives worse error messages than calling `expect` directly on the Result"
378 declare_clippy_lint! {
380 /// Checks for `.err().expect()` calls on the `Result` type.
382 /// ### Why is this bad?
383 /// `.expect_err()` can be called directly to avoid the extra type conversion from `err()`.
387 /// let x: Result<u32, &str> = Ok(10);
388 /// x.err().expect("Testing err().expect()");
392 /// let x: Result<u32, &str> = Ok(10);
393 /// x.expect_err("Testing expect_err");
395 #[clippy::version = "1.62.0"]
398 r#"using `.err().expect("")` when `.expect_err("")` can be used"#
401 declare_clippy_lint! {
403 /// Checks for usages of `_.unwrap_or_else(Default::default)` on `Option` and
406 /// ### Why is this bad?
407 /// Readability, these can be written as `_.unwrap_or_default`, which is
408 /// simpler and more concise.
412 /// # let x = Some(1);
413 /// x.unwrap_or_else(Default::default);
414 /// x.unwrap_or_else(u32::default);
419 /// # let x = Some(1);
420 /// x.unwrap_or_default();
422 #[clippy::version = "1.56.0"]
423 pub UNWRAP_OR_ELSE_DEFAULT,
425 "using `.unwrap_or_else(Default::default)`, which is more succinctly expressed as `.unwrap_or_default()`"
428 declare_clippy_lint! {
430 /// Checks for usage of `option.map(_).unwrap_or(_)` or `option.map(_).unwrap_or_else(_)` or
431 /// `result.map(_).unwrap_or_else(_)`.
433 /// ### Why is this bad?
434 /// Readability, these can be written more concisely (resp.) as
435 /// `option.map_or(_, _)`, `option.map_or_else(_, _)` and `result.map_or_else(_, _)`.
437 /// ### Known problems
438 /// The order of the arguments is not in execution order
442 /// # let option = Some(1);
443 /// # let result: Result<usize, ()> = Ok(1);
444 /// # fn some_function(foo: ()) -> usize { 1 }
445 /// option.map(|a| a + 1).unwrap_or(0);
446 /// result.map(|a| a + 1).unwrap_or_else(some_function);
451 /// # let option = Some(1);
452 /// # let result: Result<usize, ()> = Ok(1);
453 /// # fn some_function(foo: ()) -> usize { 1 }
454 /// option.map_or(0, |a| a + 1);
455 /// result.map_or_else(some_function, |a| a + 1);
457 #[clippy::version = "1.45.0"]
460 "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)`"
463 declare_clippy_lint! {
465 /// Checks for usage of `_.map_or(None, _)`.
467 /// ### Why is this bad?
468 /// Readability, this can be written more concisely as
471 /// ### Known problems
472 /// The order of the arguments is not in execution order.
476 /// # let opt = Some(1);
477 /// opt.map_or(None, |a| Some(a + 1));
482 /// # let opt = Some(1);
483 /// opt.and_then(|a| Some(a + 1));
485 #[clippy::version = "pre 1.29.0"]
486 pub OPTION_MAP_OR_NONE,
488 "using `Option.map_or(None, f)`, which is more succinctly expressed as `and_then(f)`"
491 declare_clippy_lint! {
493 /// Checks for usage of `_.map_or(None, Some)`.
495 /// ### Why is this bad?
496 /// Readability, this can be written more concisely as
501 /// # let r: Result<u32, &str> = Ok(1);
502 /// assert_eq!(Some(1), r.map_or(None, Some));
507 /// # let r: Result<u32, &str> = Ok(1);
508 /// assert_eq!(Some(1), r.ok());
510 #[clippy::version = "1.44.0"]
511 pub RESULT_MAP_OR_INTO_OPTION,
513 "using `Result.map_or(None, Some)`, which is more succinctly expressed as `ok()`"
516 declare_clippy_lint! {
518 /// Checks for usage of `_.and_then(|x| Some(y))`, `_.and_then(|x| Ok(y))` or
519 /// `_.or_else(|x| Err(y))`.
521 /// ### Why is this bad?
522 /// Readability, this can be written more concisely as
523 /// `_.map(|x| y)` or `_.map_err(|x| y)`.
527 /// # fn opt() -> Option<&'static str> { Some("42") }
528 /// # fn res() -> Result<&'static str, &'static str> { Ok("42") }
529 /// let _ = opt().and_then(|s| Some(s.len()));
530 /// let _ = res().and_then(|s| if s.len() == 42 { Ok(10) } else { Ok(20) });
531 /// let _ = res().or_else(|s| if s.len() == 42 { Err(10) } else { Err(20) });
534 /// The correct use would be:
537 /// # fn opt() -> Option<&'static str> { Some("42") }
538 /// # fn res() -> Result<&'static str, &'static str> { Ok("42") }
539 /// let _ = opt().map(|s| s.len());
540 /// let _ = res().map(|s| if s.len() == 42 { 10 } else { 20 });
541 /// let _ = res().map_err(|s| if s.len() == 42 { 10 } else { 20 });
543 #[clippy::version = "1.45.0"]
544 pub BIND_INSTEAD_OF_MAP,
546 "using `Option.and_then(|x| Some(y))`, which is more succinctly expressed as `map(|x| y)`"
549 declare_clippy_lint! {
551 /// Checks for usage of `_.filter(_).next()`.
553 /// ### Why is this bad?
554 /// Readability, this can be written more concisely as
559 /// # let vec = vec![1];
560 /// vec.iter().filter(|x| **x == 0).next();
565 /// # let vec = vec![1];
566 /// vec.iter().find(|x| **x == 0);
568 #[clippy::version = "pre 1.29.0"]
571 "using `filter(p).next()`, which is more succinctly expressed as `.find(p)`"
574 declare_clippy_lint! {
576 /// Checks for usage of `_.skip_while(condition).next()`.
578 /// ### Why is this bad?
579 /// Readability, this can be written more concisely as
580 /// `_.find(!condition)`.
584 /// # let vec = vec![1];
585 /// vec.iter().skip_while(|x| **x == 0).next();
590 /// # let vec = vec![1];
591 /// vec.iter().find(|x| **x != 0);
593 #[clippy::version = "1.42.0"]
596 "using `skip_while(p).next()`, which is more succinctly expressed as `.find(!p)`"
599 declare_clippy_lint! {
601 /// Checks for usage of `_.map(_).flatten(_)` on `Iterator` and `Option`
603 /// ### Why is this bad?
604 /// Readability, this can be written more concisely as
605 /// `_.flat_map(_)` for `Iterator` or `_.and_then(_)` for `Option`
609 /// let vec = vec![vec![1]];
610 /// let opt = Some(5);
612 /// vec.iter().map(|x| x.iter()).flatten();
613 /// opt.map(|x| Some(x * 2)).flatten();
618 /// # let vec = vec![vec![1]];
619 /// # let opt = Some(5);
620 /// vec.iter().flat_map(|x| x.iter());
621 /// opt.and_then(|x| Some(x * 2));
623 #[clippy::version = "1.31.0"]
626 "using combinations of `flatten` and `map` which can usually be written as a single method call"
629 declare_clippy_lint! {
631 /// Checks for usage of `_.filter(_).map(_)` that can be written more simply
632 /// as `filter_map(_)`.
634 /// ### Why is this bad?
635 /// Redundant code in the `filter` and `map` operations is poor style and
640 /// # #![allow(unused)]
642 /// .filter(|n| n.checked_add(1).is_some())
643 /// .map(|n| n.checked_add(1).unwrap());
648 /// # #[allow(unused)]
649 /// (0_i32..10).filter_map(|n| n.checked_add(1));
651 #[clippy::version = "1.51.0"]
652 pub MANUAL_FILTER_MAP,
654 "using `_.filter(_).map(_)` in a way that can be written more simply as `filter_map(_)`"
657 declare_clippy_lint! {
659 /// Checks for usage of `_.find(_).map(_)` that can be written more simply
660 /// as `find_map(_)`.
662 /// ### Why is this bad?
663 /// Redundant code in the `find` and `map` operations is poor style and
669 /// .find(|n| n.checked_add(1).is_some())
670 /// .map(|n| n.checked_add(1).unwrap());
675 /// (0_i32..10).find_map(|n| n.checked_add(1));
677 #[clippy::version = "1.51.0"]
680 "using `_.find(_).map(_)` in a way that can be written more simply as `find_map(_)`"
683 declare_clippy_lint! {
685 /// Checks for usage of `_.filter_map(_).next()`.
687 /// ### Why is this bad?
688 /// Readability, this can be written more concisely as
693 /// (0..3).filter_map(|x| if x == 2 { Some(x) } else { None }).next();
695 /// Can be written as
698 /// (0..3).find_map(|x| if x == 2 { Some(x) } else { None });
700 #[clippy::version = "1.36.0"]
703 "using combination of `filter_map` and `next` which can usually be written as a single method call"
706 declare_clippy_lint! {
708 /// Checks for usage of `flat_map(|x| x)`.
710 /// ### Why is this bad?
711 /// Readability, this can be written more concisely by using `flatten`.
715 /// # let iter = vec![vec![0]].into_iter();
716 /// iter.flat_map(|x| x);
718 /// Can be written as
720 /// # let iter = vec![vec![0]].into_iter();
723 #[clippy::version = "1.39.0"]
724 pub FLAT_MAP_IDENTITY,
726 "call to `flat_map` where `flatten` is sufficient"
729 declare_clippy_lint! {
731 /// Checks for an iterator or string search (such as `find()`,
732 /// `position()`, or `rposition()`) followed by a call to `is_some()` or `is_none()`.
734 /// ### Why is this bad?
735 /// Readability, this can be written more concisely as:
736 /// * `_.any(_)`, or `_.contains(_)` for `is_some()`,
737 /// * `!_.any(_)`, or `!_.contains(_)` for `is_none()`.
741 /// # #![allow(unused)]
742 /// let vec = vec![1];
743 /// vec.iter().find(|x| **x == 0).is_some();
745 /// "hello world".find("world").is_none();
750 /// let vec = vec![1];
751 /// vec.iter().any(|x| *x == 0);
753 /// # #[allow(unused)]
754 /// !"hello world".contains("world");
756 #[clippy::version = "pre 1.29.0"]
759 "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()`)"
762 declare_clippy_lint! {
764 /// Checks for usage of `.chars().next()` on a `str` to check
765 /// if it starts with a given char.
767 /// ### Why is this bad?
768 /// Readability, this can be written more concisely as
769 /// `_.starts_with(_)`.
773 /// let name = "foo";
774 /// if name.chars().next() == Some('_') {};
779 /// let name = "foo";
780 /// if name.starts_with('_') {};
782 #[clippy::version = "pre 1.29.0"]
785 "using `.chars().next()` to check if a string starts with a char"
788 declare_clippy_lint! {
790 /// Checks for calls to `.or(foo(..))`, `.unwrap_or(foo(..))`,
791 /// etc., and suggests to use `or_else`, `unwrap_or_else`, etc., or
792 /// `unwrap_or_default` instead.
794 /// ### Why is this bad?
795 /// The function will always be called and potentially
796 /// allocate an object acting as the default.
798 /// ### Known problems
799 /// If the function has side-effects, not calling it will
800 /// change the semantic of the program, but you shouldn't rely on that anyway.
804 /// # let foo = Some(String::new());
805 /// foo.unwrap_or(String::new());
810 /// # let foo = Some(String::new());
811 /// foo.unwrap_or_else(String::new);
815 /// # let foo = Some(String::new());
816 /// foo.unwrap_or_default();
818 #[clippy::version = "pre 1.29.0"]
821 "using any `*or` method with a function call, which suggests `*or_else`"
824 declare_clippy_lint! {
826 /// Checks for `.or(…).unwrap()` calls to Options and Results.
828 /// ### Why is this bad?
829 /// You should use `.unwrap_or(…)` instead for clarity.
833 /// # let fallback = "fallback";
835 /// # type Error = &'static str;
836 /// # let result: Result<&str, Error> = Err("error");
837 /// let value = result.or::<Error>(Ok(fallback)).unwrap();
840 /// # let option: Option<&str> = None;
841 /// let value = option.or(Some(fallback)).unwrap();
845 /// # let fallback = "fallback";
847 /// # let result: Result<&str, &str> = Err("error");
848 /// let value = result.unwrap_or(fallback);
851 /// # let option: Option<&str> = None;
852 /// let value = option.unwrap_or(fallback);
854 #[clippy::version = "1.61.0"]
857 "checks for `.or(…).unwrap()` calls to Options and Results."
860 declare_clippy_lint! {
862 /// Checks for calls to `.expect(&format!(...))`, `.expect(foo(..))`,
863 /// etc., and suggests to use `unwrap_or_else` instead
865 /// ### Why is this bad?
866 /// The function will always be called.
868 /// ### Known problems
869 /// If the function has side-effects, not calling it will
870 /// change the semantics of the program, but you shouldn't rely on that anyway.
874 /// # let foo = Some(String::new());
875 /// # let err_code = "418";
876 /// # let err_msg = "I'm a teapot";
877 /// foo.expect(&format!("Err {}: {}", err_code, err_msg));
881 /// # let foo = Some(String::new());
882 /// foo.expect(format!("Err {}: {}", err_code, err_msg).as_str());
887 /// # let foo = Some(String::new());
888 /// # let err_code = "418";
889 /// # let err_msg = "I'm a teapot";
890 /// foo.unwrap_or_else(|| panic!("Err {}: {}", err_code, err_msg));
892 #[clippy::version = "pre 1.29.0"]
895 "using any `expect` method with a function call"
898 declare_clippy_lint! {
900 /// Checks for usage of `.clone()` on a `Copy` type.
902 /// ### Why is this bad?
903 /// The only reason `Copy` types implement `Clone` is for
904 /// generics, not for using the `clone` method on a concrete type.
910 #[clippy::version = "pre 1.29.0"]
913 "using `clone` on a `Copy` type"
916 declare_clippy_lint! {
918 /// Checks for usage of `.clone()` on a ref-counted pointer,
919 /// (`Rc`, `Arc`, `rc::Weak`, or `sync::Weak`), and suggests calling Clone via unified
920 /// function syntax instead (e.g., `Rc::clone(foo)`).
922 /// ### Why is this bad?
923 /// Calling '.clone()' on an Rc, Arc, or Weak
924 /// can obscure the fact that only the pointer is being cloned, not the underlying
929 /// # use std::rc::Rc;
930 /// let x = Rc::new(1);
937 /// # use std::rc::Rc;
938 /// # let x = Rc::new(1);
941 #[clippy::version = "pre 1.29.0"]
942 pub CLONE_ON_REF_PTR,
944 "using 'clone' on a ref-counted pointer"
947 declare_clippy_lint! {
949 /// Checks for usage of `.clone()` on an `&&T`.
951 /// ### Why is this bad?
952 /// Cloning an `&&T` copies the inner `&T`, instead of
953 /// cloning the underlying `T`.
960 /// let z = y.clone();
961 /// println!("{:p} {:p}", *y, z); // prints out the same pointer
964 #[clippy::version = "pre 1.29.0"]
965 pub CLONE_DOUBLE_REF,
967 "using `clone` on `&&T`"
970 declare_clippy_lint! {
972 /// Checks for usage of `.to_string()` on an `&&T` where
973 /// `T` implements `ToString` directly (like `&&str` or `&&String`).
975 /// ### Why is this bad?
976 /// This bypasses the specialized implementation of
977 /// `ToString` and instead goes through the more expensive string formatting
982 /// // Generic implementation for `T: Display` is used (slow)
983 /// ["foo", "bar"].iter().map(|s| s.to_string());
985 /// // OK, the specialized impl is used
986 /// ["foo", "bar"].iter().map(|&s| s.to_string());
988 #[clippy::version = "1.40.0"]
989 pub INEFFICIENT_TO_STRING,
991 "using `to_string` on `&&T` where `T: ToString`"
994 declare_clippy_lint! {
996 /// Checks for `new` not returning a type that contains `Self`.
998 /// ### Why is this bad?
999 /// As a convention, `new` methods are used to make a new
1000 /// instance of a type.
1003 /// In an impl block:
1006 /// # struct NotAFoo;
1008 /// fn new() -> NotAFoo {
1016 /// struct Bar(Foo);
1018 /// // Bad. The type name must contain `Self`
1019 /// fn new() -> Bar {
1027 /// # struct FooError;
1029 /// // Good. Return type contains `Self`
1030 /// fn new() -> Result<Foo, FooError> {
1036 /// Or in a trait definition:
1038 /// pub trait Trait {
1039 /// // Bad. The type name must contain `Self`
1045 /// pub trait Trait {
1046 /// // Good. Return type contains `Self`
1047 /// fn new() -> Self;
1050 #[clippy::version = "pre 1.29.0"]
1051 pub NEW_RET_NO_SELF,
1053 "not returning type containing `Self` in a `new` method"
1056 declare_clippy_lint! {
1057 /// ### What it does
1058 /// Checks for string methods that receive a single-character
1059 /// `str` as an argument, e.g., `_.split("x")`.
1061 /// ### Why is this bad?
1062 /// Performing these methods using a `char` is faster than
1065 /// ### Known problems
1066 /// Does not catch multi-byte unicode characters.
1077 #[clippy::version = "pre 1.29.0"]
1078 pub SINGLE_CHAR_PATTERN,
1080 "using a single-character str where a char could be used, e.g., `_.split(\"x\")`"
1083 declare_clippy_lint! {
1084 /// ### What it does
1085 /// Checks for calling `.step_by(0)` on iterators which panics.
1087 /// ### Why is this bad?
1088 /// This very much looks like an oversight. Use `panic!()` instead if you
1089 /// actually intend to panic.
1092 /// ```rust,should_panic
1093 /// for x in (0..100).step_by(0) {
1097 #[clippy::version = "pre 1.29.0"]
1098 pub ITERATOR_STEP_BY_ZERO,
1100 "using `Iterator::step_by(0)`, which will panic at runtime"
1103 declare_clippy_lint! {
1104 /// ### What it does
1105 /// Checks for indirect collection of populated `Option`
1107 /// ### Why is this bad?
1108 /// `Option` is like a collection of 0-1 things, so `flatten`
1109 /// automatically does this without suspicious-looking `unwrap` calls.
1113 /// let _ = std::iter::empty::<Option<i32>>().filter(Option::is_some).map(Option::unwrap);
1117 /// let _ = std::iter::empty::<Option<i32>>().flatten();
1119 #[clippy::version = "1.53.0"]
1120 pub OPTION_FILTER_MAP,
1122 "filtering `Option` for `Some` then force-unwrapping, which can be one type-safe operation"
1125 declare_clippy_lint! {
1126 /// ### What it does
1127 /// Checks for the use of `iter.nth(0)`.
1129 /// ### Why is this bad?
1130 /// `iter.next()` is equivalent to
1131 /// `iter.nth(0)`, as they both consume the next element,
1132 /// but is more readable.
1136 /// # use std::collections::HashSet;
1137 /// # let mut s = HashSet::new();
1139 /// let x = s.iter().nth(0);
1144 /// # use std::collections::HashSet;
1145 /// # let mut s = HashSet::new();
1147 /// let x = s.iter().next();
1149 #[clippy::version = "1.42.0"]
1152 "replace `iter.nth(0)` with `iter.next()`"
1155 declare_clippy_lint! {
1156 /// ### What it does
1157 /// Checks for use of `.iter().nth()` (and the related
1158 /// `.iter_mut().nth()`) on standard library types with *O*(1) element access.
1160 /// ### Why is this bad?
1161 /// `.get()` and `.get_mut()` are more efficient and more
1166 /// let some_vec = vec![0, 1, 2, 3];
1167 /// let bad_vec = some_vec.iter().nth(3);
1168 /// let bad_slice = &some_vec[..].iter().nth(3);
1170 /// The correct use would be:
1172 /// let some_vec = vec![0, 1, 2, 3];
1173 /// let bad_vec = some_vec.get(3);
1174 /// let bad_slice = &some_vec[..].get(3);
1176 #[clippy::version = "pre 1.29.0"]
1179 "using `.iter().nth()` on a standard library type with O(1) element access"
1182 declare_clippy_lint! {
1183 /// ### What it does
1184 /// Checks for use of `.skip(x).next()` on iterators.
1186 /// ### Why is this bad?
1187 /// `.nth(x)` is cleaner
1191 /// let some_vec = vec![0, 1, 2, 3];
1192 /// let bad_vec = some_vec.iter().skip(3).next();
1193 /// let bad_slice = &some_vec[..].iter().skip(3).next();
1195 /// The correct use would be:
1197 /// let some_vec = vec![0, 1, 2, 3];
1198 /// let bad_vec = some_vec.iter().nth(3);
1199 /// let bad_slice = &some_vec[..].iter().nth(3);
1201 #[clippy::version = "pre 1.29.0"]
1204 "using `.skip(x).next()` on an iterator"
1207 declare_clippy_lint! {
1208 /// ### What it does
1209 /// Checks for use of `.drain(..)` on `Vec` and `VecDeque` for iteration.
1211 /// ### Why is this bad?
1212 /// `.into_iter()` is simpler with better performance.
1216 /// # use std::collections::HashSet;
1217 /// let mut foo = vec![0, 1, 2, 3];
1218 /// let bar: HashSet<usize> = foo.drain(..).collect();
1222 /// # use std::collections::HashSet;
1223 /// let foo = vec![0, 1, 2, 3];
1224 /// let bar: HashSet<usize> = foo.into_iter().collect();
1226 #[clippy::version = "1.61.0"]
1227 pub ITER_WITH_DRAIN,
1229 "replace `.drain(..)` with `.into_iter()`"
1232 declare_clippy_lint! {
1233 /// ### What it does
1234 /// Checks for using `x.get(x.len() - 1)` instead of
1237 /// ### Why is this bad?
1238 /// Using `x.last()` is easier to read and has the same
1241 /// Note that using `x[x.len() - 1]` is semantically different from
1242 /// `x.last()`. Indexing into the array will panic on out-of-bounds
1243 /// accesses, while `x.get()` and `x.last()` will return `None`.
1245 /// There is another lint (get_unwrap) that covers the case of using
1246 /// `x.get(index).unwrap()` instead of `x[index]`.
1250 /// let x = vec![2, 3, 5];
1251 /// let last_element = x.get(x.len() - 1);
1256 /// let x = vec![2, 3, 5];
1257 /// let last_element = x.last();
1259 #[clippy::version = "1.37.0"]
1260 pub GET_LAST_WITH_LEN,
1262 "Using `x.get(x.len() - 1)` when `x.last()` is correct and simpler"
1265 declare_clippy_lint! {
1266 /// ### What it does
1267 /// Checks for use of `.get().unwrap()` (or
1268 /// `.get_mut().unwrap`) on a standard library type which implements `Index`
1270 /// ### Why is this bad?
1271 /// Using the Index trait (`[]`) is more clear and more
1274 /// ### Known problems
1275 /// Not a replacement for error handling: Using either
1276 /// `.unwrap()` or the Index trait (`[]`) carries the risk of causing a `panic`
1277 /// if the value being accessed is `None`. If the use of `.get().unwrap()` is a
1278 /// temporary placeholder for dealing with the `Option` type, then this does
1279 /// not mitigate the need for error handling. If there is a chance that `.get()`
1280 /// will be `None` in your program, then it is advisable that the `None` case
1281 /// is handled in a future refactor instead of using `.unwrap()` or the Index
1286 /// let mut some_vec = vec![0, 1, 2, 3];
1287 /// let last = some_vec.get(3).unwrap();
1288 /// *some_vec.get_mut(0).unwrap() = 1;
1290 /// The correct use would be:
1292 /// let mut some_vec = vec![0, 1, 2, 3];
1293 /// let last = some_vec[3];
1294 /// some_vec[0] = 1;
1296 #[clippy::version = "pre 1.29.0"]
1299 "using `.get().unwrap()` or `.get_mut().unwrap()` when using `[]` would work instead"
1302 declare_clippy_lint! {
1303 /// ### What it does
1304 /// Checks for occurrences where one vector gets extended instead of append
1306 /// ### Why is this bad?
1307 /// Using `append` instead of `extend` is more concise and faster
1311 /// let mut a = vec![1, 2, 3];
1312 /// let mut b = vec![4, 5, 6];
1314 /// a.extend(b.drain(..));
1319 /// let mut a = vec![1, 2, 3];
1320 /// let mut b = vec![4, 5, 6];
1322 /// a.append(&mut b);
1324 #[clippy::version = "1.55.0"]
1325 pub EXTEND_WITH_DRAIN,
1327 "using vec.append(&mut vec) to move the full range of a vector to another"
1330 declare_clippy_lint! {
1331 /// ### What it does
1332 /// Checks for the use of `.extend(s.chars())` where s is a
1333 /// `&str` or `String`.
1335 /// ### Why is this bad?
1336 /// `.push_str(s)` is clearer
1340 /// let abc = "abc";
1341 /// let def = String::from("def");
1342 /// let mut s = String::new();
1343 /// s.extend(abc.chars());
1344 /// s.extend(def.chars());
1346 /// The correct use would be:
1348 /// let abc = "abc";
1349 /// let def = String::from("def");
1350 /// let mut s = String::new();
1351 /// s.push_str(abc);
1352 /// s.push_str(&def);
1354 #[clippy::version = "pre 1.29.0"]
1355 pub STRING_EXTEND_CHARS,
1357 "using `x.extend(s.chars())` where s is a `&str` or `String`"
1360 declare_clippy_lint! {
1361 /// ### What it does
1362 /// Checks for the use of `.cloned().collect()` on slice to
1365 /// ### Why is this bad?
1366 /// `.to_vec()` is clearer
1370 /// let s = [1, 2, 3, 4, 5];
1371 /// let s2: Vec<isize> = s[..].iter().cloned().collect();
1373 /// The better use would be:
1375 /// let s = [1, 2, 3, 4, 5];
1376 /// let s2: Vec<isize> = s.to_vec();
1378 #[clippy::version = "pre 1.29.0"]
1379 pub ITER_CLONED_COLLECT,
1381 "using `.cloned().collect()` on slice to create a `Vec`"
1384 declare_clippy_lint! {
1385 /// ### What it does
1386 /// Checks for usage of `_.chars().last()` or
1387 /// `_.chars().next_back()` on a `str` to check if it ends with a given char.
1389 /// ### Why is this bad?
1390 /// Readability, this can be written more concisely as
1391 /// `_.ends_with(_)`.
1395 /// # let name = "_";
1396 /// name.chars().last() == Some('_') || name.chars().next_back() == Some('-');
1401 /// # let name = "_";
1402 /// name.ends_with('_') || name.ends_with('-');
1404 #[clippy::version = "pre 1.29.0"]
1407 "using `.chars().last()` or `.chars().next_back()` to check if a string ends with a char"
1410 declare_clippy_lint! {
1411 /// ### What it does
1412 /// Checks for usage of `.as_ref()` or `.as_mut()` where the
1413 /// types before and after the call are the same.
1415 /// ### Why is this bad?
1416 /// The call is unnecessary.
1420 /// # fn do_stuff(x: &[i32]) {}
1421 /// let x: &[i32] = &[1, 2, 3, 4, 5];
1422 /// do_stuff(x.as_ref());
1424 /// The correct use would be:
1426 /// # fn do_stuff(x: &[i32]) {}
1427 /// let x: &[i32] = &[1, 2, 3, 4, 5];
1430 #[clippy::version = "pre 1.29.0"]
1433 "using `as_ref` where the types before and after the call are the same"
1436 declare_clippy_lint! {
1437 /// ### What it does
1438 /// Checks for using `fold` when a more succinct alternative exists.
1439 /// Specifically, this checks for `fold`s which could be replaced by `any`, `all`,
1440 /// `sum` or `product`.
1442 /// ### Why is this bad?
1447 /// # #[allow(unused)]
1448 /// (0..3).fold(false, |acc, x| acc || x > 2);
1453 /// (0..3).any(|x| x > 2);
1455 #[clippy::version = "pre 1.29.0"]
1456 pub UNNECESSARY_FOLD,
1458 "using `fold` when a more succinct alternative exists"
1461 declare_clippy_lint! {
1462 /// ### What it does
1463 /// Checks for `filter_map` calls that could be replaced by `filter` or `map`.
1464 /// More specifically it checks if the closure provided is only performing one of the
1465 /// filter or map operations and suggests the appropriate option.
1467 /// ### Why is this bad?
1468 /// Complexity. The intent is also clearer if only a single
1469 /// operation is being performed.
1473 /// let _ = (0..3).filter_map(|x| if x > 2 { Some(x) } else { None });
1475 /// // As there is no transformation of the argument this could be written as:
1476 /// let _ = (0..3).filter(|&x| x > 2);
1480 /// let _ = (0..4).filter_map(|x| Some(x + 1));
1482 /// // As there is no conditional check on the argument this could be written as:
1483 /// let _ = (0..4).map(|x| x + 1);
1485 #[clippy::version = "1.31.0"]
1486 pub UNNECESSARY_FILTER_MAP,
1488 "using `filter_map` when a more succinct alternative exists"
1491 declare_clippy_lint! {
1492 /// ### What it does
1493 /// Checks for `find_map` calls that could be replaced by `find` or `map`. More
1494 /// specifically it checks if the closure provided is only performing one of the
1495 /// find or map operations and suggests the appropriate option.
1497 /// ### Why is this bad?
1498 /// Complexity. The intent is also clearer if only a single
1499 /// operation is being performed.
1503 /// let _ = (0..3).find_map(|x| if x > 2 { Some(x) } else { None });
1505 /// // As there is no transformation of the argument this could be written as:
1506 /// let _ = (0..3).find(|&x| x > 2);
1510 /// let _ = (0..4).find_map(|x| Some(x + 1));
1512 /// // As there is no conditional check on the argument this could be written as:
1513 /// let _ = (0..4).map(|x| x + 1).next();
1515 #[clippy::version = "1.61.0"]
1516 pub UNNECESSARY_FIND_MAP,
1518 "using `find_map` when a more succinct alternative exists"
1521 declare_clippy_lint! {
1522 /// ### What it does
1523 /// Checks for `into_iter` calls on references which should be replaced by `iter`
1526 /// ### Why is this bad?
1527 /// Readability. Calling `into_iter` on a reference will not move out its
1528 /// content into the resulting iterator, which is confusing. It is better just call `iter` or
1529 /// `iter_mut` directly.
1533 /// # let vec = vec![3, 4, 5];
1534 /// (&vec).into_iter();
1539 /// # let vec = vec![3, 4, 5];
1542 #[clippy::version = "1.32.0"]
1543 pub INTO_ITER_ON_REF,
1545 "using `.into_iter()` on a reference"
1548 declare_clippy_lint! {
1549 /// ### What it does
1550 /// Checks for calls to `map` followed by a `count`.
1552 /// ### Why is this bad?
1553 /// It looks suspicious. Maybe `map` was confused with `filter`.
1554 /// If the `map` call is intentional, this should be rewritten
1555 /// using `inspect`. Or, if you intend to drive the iterator to
1556 /// completion, you can just use `for_each` instead.
1560 /// let _ = (0..3).map(|x| x + 2).count();
1562 #[clippy::version = "1.39.0"]
1565 "suspicious usage of map"
1568 declare_clippy_lint! {
1569 /// ### What it does
1570 /// Checks for `MaybeUninit::uninit().assume_init()`.
1572 /// ### Why is this bad?
1573 /// For most types, this is undefined behavior.
1575 /// ### Known problems
1576 /// For now, we accept empty tuples and tuples / arrays
1577 /// of `MaybeUninit`. There may be other types that allow uninitialized
1578 /// data, but those are not yet rigorously defined.
1582 /// // Beware the UB
1583 /// use std::mem::MaybeUninit;
1585 /// let _: usize = unsafe { MaybeUninit::uninit().assume_init() };
1588 /// Note that the following is OK:
1591 /// use std::mem::MaybeUninit;
1593 /// let _: [MaybeUninit<bool>; 5] = unsafe {
1594 /// MaybeUninit::uninit().assume_init()
1597 #[clippy::version = "1.39.0"]
1598 pub UNINIT_ASSUMED_INIT,
1600 "`MaybeUninit::uninit().assume_init()`"
1603 declare_clippy_lint! {
1604 /// ### What it does
1605 /// Checks for `.checked_add/sub(x).unwrap_or(MAX/MIN)`.
1607 /// ### Why is this bad?
1608 /// These can be written simply with `saturating_add/sub` methods.
1612 /// # let y: u32 = 0;
1613 /// # let x: u32 = 100;
1614 /// let add = x.checked_add(y).unwrap_or(u32::MAX);
1615 /// let sub = x.checked_sub(y).unwrap_or(u32::MIN);
1618 /// can be written using dedicated methods for saturating addition/subtraction as:
1621 /// # let y: u32 = 0;
1622 /// # let x: u32 = 100;
1623 /// let add = x.saturating_add(y);
1624 /// let sub = x.saturating_sub(y);
1626 #[clippy::version = "1.39.0"]
1627 pub MANUAL_SATURATING_ARITHMETIC,
1629 "`.checked_add/sub(x).unwrap_or(MAX/MIN)`"
1632 declare_clippy_lint! {
1633 /// ### What it does
1634 /// Checks for `offset(_)`, `wrapping_`{`add`, `sub`}, etc. on raw pointers to
1635 /// zero-sized types
1637 /// ### Why is this bad?
1638 /// This is a no-op, and likely unintended
1642 /// unsafe { (&() as *const ()).offset(1) };
1644 #[clippy::version = "1.41.0"]
1647 "Check for offset calculations on raw pointers to zero-sized types"
1650 declare_clippy_lint! {
1651 /// ### What it does
1652 /// Checks for `FileType::is_file()`.
1654 /// ### Why is this bad?
1655 /// When people testing a file type with `FileType::is_file`
1656 /// they are testing whether a path is something they can get bytes from. But
1657 /// `is_file` doesn't cover special file types in unix-like systems, and doesn't cover
1658 /// symlink in windows. Using `!FileType::is_dir()` is a better way to that intention.
1663 /// let metadata = std::fs::metadata("foo.txt")?;
1664 /// let filetype = metadata.file_type();
1666 /// if filetype.is_file() {
1669 /// # Ok::<_, std::io::Error>(())
1673 /// should be written as:
1677 /// let metadata = std::fs::metadata("foo.txt")?;
1678 /// let filetype = metadata.file_type();
1680 /// if !filetype.is_dir() {
1683 /// # Ok::<_, std::io::Error>(())
1686 #[clippy::version = "1.42.0"]
1687 pub FILETYPE_IS_FILE,
1689 "`FileType::is_file` is not recommended to test for readable file type"
1692 declare_clippy_lint! {
1693 /// ### What it does
1694 /// Checks for usage of `_.as_ref().map(Deref::deref)` or it's aliases (such as String::as_str).
1696 /// ### Why is this bad?
1697 /// Readability, this can be written more concisely as
1702 /// # let opt = Some("".to_string());
1703 /// opt.as_ref().map(String::as_str)
1706 /// Can be written as
1708 /// # let opt = Some("".to_string());
1712 #[clippy::version = "1.42.0"]
1713 pub OPTION_AS_REF_DEREF,
1715 "using `as_ref().map(Deref::deref)`, which is more succinctly expressed as `as_deref()`"
1718 declare_clippy_lint! {
1719 /// ### What it does
1720 /// Checks for usage of `iter().next()` on a Slice or an Array
1722 /// ### Why is this bad?
1723 /// These can be shortened into `.get()`
1727 /// # let a = [1, 2, 3];
1728 /// # let b = vec![1, 2, 3];
1729 /// a[2..].iter().next();
1730 /// b.iter().next();
1732 /// should be written as:
1734 /// # let a = [1, 2, 3];
1735 /// # let b = vec![1, 2, 3];
1739 #[clippy::version = "1.46.0"]
1740 pub ITER_NEXT_SLICE,
1742 "using `.iter().next()` on a sliced array, which can be shortened to just `.get()`"
1745 declare_clippy_lint! {
1746 /// ### What it does
1747 /// Warns when using `push_str`/`insert_str` with a single-character string literal
1748 /// where `push`/`insert` with a `char` would work fine.
1750 /// ### Why is this bad?
1751 /// It's less clear that we are pushing a single character.
1755 /// # let mut string = String::new();
1756 /// string.insert_str(0, "R");
1757 /// string.push_str("R");
1762 /// # let mut string = String::new();
1763 /// string.insert(0, 'R');
1764 /// string.push('R');
1766 #[clippy::version = "1.49.0"]
1767 pub SINGLE_CHAR_ADD_STR,
1769 "`push_str()` or `insert_str()` used with a single-character string literal as parameter"
1772 declare_clippy_lint! {
1773 /// ### What it does
1774 /// As the counterpart to `or_fun_call`, this lint looks for unnecessary
1775 /// lazily evaluated closures on `Option` and `Result`.
1777 /// This lint suggests changing the following functions, when eager evaluation results in
1779 /// - `unwrap_or_else` to `unwrap_or`
1780 /// - `and_then` to `and`
1781 /// - `or_else` to `or`
1782 /// - `get_or_insert_with` to `get_or_insert`
1783 /// - `ok_or_else` to `ok_or`
1785 /// ### Why is this bad?
1786 /// Using eager evaluation is shorter and simpler in some cases.
1788 /// ### Known problems
1789 /// It is possible, but not recommended for `Deref` and `Index` to have
1790 /// side effects. Eagerly evaluating them can change the semantics of the program.
1794 /// // example code where clippy issues a warning
1795 /// let opt: Option<u32> = None;
1797 /// opt.unwrap_or_else(|| 42);
1801 /// let opt: Option<u32> = None;
1803 /// opt.unwrap_or(42);
1805 #[clippy::version = "1.48.0"]
1806 pub UNNECESSARY_LAZY_EVALUATIONS,
1808 "using unnecessary lazy evaluation, which can be replaced with simpler eager evaluation"
1811 declare_clippy_lint! {
1812 /// ### What it does
1813 /// Checks for usage of `_.map(_).collect::<Result<(), _>()`.
1815 /// ### Why is this bad?
1816 /// Using `try_for_each` instead is more readable and idiomatic.
1820 /// (0..3).map(|t| Err(t)).collect::<Result<(), _>>();
1824 /// (0..3).try_for_each(|t| Err(t));
1826 #[clippy::version = "1.49.0"]
1827 pub MAP_COLLECT_RESULT_UNIT,
1829 "using `.map(_).collect::<Result<(),_>()`, which can be replaced with `try_for_each`"
1832 declare_clippy_lint! {
1833 /// ### What it does
1834 /// Checks for `from_iter()` function calls on types that implement the `FromIterator`
1837 /// ### Why is this bad?
1838 /// It is recommended style to use collect. See
1839 /// [FromIterator documentation](https://doc.rust-lang.org/std/iter/trait.FromIterator.html)
1843 /// let five_fives = std::iter::repeat(5).take(5);
1845 /// let v = Vec::from_iter(five_fives);
1847 /// assert_eq!(v, vec![5, 5, 5, 5, 5]);
1851 /// let five_fives = std::iter::repeat(5).take(5);
1853 /// let v: Vec<i32> = five_fives.collect();
1855 /// assert_eq!(v, vec![5, 5, 5, 5, 5]);
1857 #[clippy::version = "1.49.0"]
1858 pub FROM_ITER_INSTEAD_OF_COLLECT,
1860 "use `.collect()` instead of `::from_iter()`"
1863 declare_clippy_lint! {
1864 /// ### What it does
1865 /// Checks for usage of `inspect().for_each()`.
1867 /// ### Why is this bad?
1868 /// It is the same as performing the computation
1869 /// inside `inspect` at the beginning of the closure in `for_each`.
1873 /// [1,2,3,4,5].iter()
1874 /// .inspect(|&x| println!("inspect the number: {}", x))
1875 /// .for_each(|&x| {
1876 /// assert!(x >= 0);
1879 /// Can be written as
1881 /// [1,2,3,4,5].iter()
1882 /// .for_each(|&x| {
1883 /// println!("inspect the number: {}", x);
1884 /// assert!(x >= 0);
1887 #[clippy::version = "1.51.0"]
1888 pub INSPECT_FOR_EACH,
1890 "using `.inspect().for_each()`, which can be replaced with `.for_each()`"
1893 declare_clippy_lint! {
1894 /// ### What it does
1895 /// Checks for usage of `filter_map(|x| x)`.
1897 /// ### Why is this bad?
1898 /// Readability, this can be written more concisely by using `flatten`.
1902 /// # let iter = vec![Some(1)].into_iter();
1903 /// iter.filter_map(|x| x);
1907 /// # let iter = vec![Some(1)].into_iter();
1910 #[clippy::version = "1.52.0"]
1911 pub FILTER_MAP_IDENTITY,
1913 "call to `filter_map` where `flatten` is sufficient"
1916 declare_clippy_lint! {
1917 /// ### What it does
1918 /// Checks for instances of `map(f)` where `f` is the identity function.
1920 /// ### Why is this bad?
1921 /// It can be written more concisely without the call to `map`.
1925 /// let x = [1, 2, 3];
1926 /// let y: Vec<_> = x.iter().map(|x| x).map(|x| 2*x).collect();
1930 /// let x = [1, 2, 3];
1931 /// let y: Vec<_> = x.iter().map(|x| 2*x).collect();
1933 #[clippy::version = "1.47.0"]
1936 "using iterator.map(|x| x)"
1939 declare_clippy_lint! {
1940 /// ### What it does
1941 /// Checks for the use of `.bytes().nth()`.
1943 /// ### Why is this bad?
1944 /// `.as_bytes().get()` is more efficient and more
1949 /// # #[allow(unused)]
1950 /// "Hello".bytes().nth(3);
1955 /// # #[allow(unused)]
1956 /// "Hello".as_bytes().get(3);
1958 #[clippy::version = "1.52.0"]
1961 "replace `.bytes().nth()` with `.as_bytes().get()`"
1964 declare_clippy_lint! {
1965 /// ### What it does
1966 /// Checks for the usage of `_.to_owned()`, `vec.to_vec()`, or similar when calling `_.clone()` would be clearer.
1968 /// ### Why is this bad?
1969 /// These methods do the same thing as `_.clone()` but may be confusing as
1970 /// to why we are calling `to_vec` on something that is already a `Vec` or calling `to_owned` on something that is already owned.
1974 /// let a = vec![1, 2, 3];
1975 /// let b = a.to_vec();
1976 /// let c = a.to_owned();
1980 /// let a = vec![1, 2, 3];
1981 /// let b = a.clone();
1982 /// let c = a.clone();
1984 #[clippy::version = "1.52.0"]
1987 "implicitly cloning a value by invoking a function on its dereferenced type"
1990 declare_clippy_lint! {
1991 /// ### What it does
1992 /// Checks for the use of `.iter().count()`.
1994 /// ### Why is this bad?
1995 /// `.len()` is more efficient and more
2000 /// # #![allow(unused)]
2001 /// let some_vec = vec![0, 1, 2, 3];
2003 /// some_vec.iter().count();
2004 /// &some_vec[..].iter().count();
2009 /// let some_vec = vec![0, 1, 2, 3];
2012 /// &some_vec[..].len();
2014 #[clippy::version = "1.52.0"]
2017 "replace `.iter().count()` with `.len()`"
2020 declare_clippy_lint! {
2021 /// ### What it does
2022 /// Checks for calls to [`splitn`]
2023 /// (https://doc.rust-lang.org/std/primitive.str.html#method.splitn) and
2024 /// related functions with either zero or one splits.
2026 /// ### Why is this bad?
2027 /// These calls don't actually split the value and are
2028 /// likely to be intended as a different number.
2033 /// for x in s.splitn(1, ":") {
2041 /// for x in s.splitn(2, ":") {
2045 #[clippy::version = "1.54.0"]
2046 pub SUSPICIOUS_SPLITN,
2048 "checks for `.splitn(0, ..)` and `.splitn(1, ..)`"
2051 declare_clippy_lint! {
2052 /// ### What it does
2053 /// Checks for manual implementations of `str::repeat`
2055 /// ### Why is this bad?
2056 /// These are both harder to read, as well as less performant.
2060 /// let x: String = std::iter::repeat('x').take(10).collect();
2065 /// let x: String = "x".repeat(10);
2067 #[clippy::version = "1.54.0"]
2068 pub MANUAL_STR_REPEAT,
2070 "manual implementation of `str::repeat`"
2073 declare_clippy_lint! {
2074 /// ### What it does
2075 /// Checks for usages of `str::splitn(2, _)`
2077 /// ### Why is this bad?
2078 /// `split_once` is both clearer in intent and slightly more efficient.
2082 /// let s = "key=value=add";
2083 /// let (key, value) = s.splitn(2, '=').next_tuple()?;
2084 /// let value = s.splitn(2, '=').nth(1)?;
2086 /// let mut parts = s.splitn(2, '=');
2087 /// let key = parts.next()?;
2088 /// let value = parts.next()?;
2093 /// let s = "key=value=add";
2094 /// let (key, value) = s.split_once('=')?;
2095 /// let value = s.split_once('=')?.1;
2097 /// let (key, value) = s.split_once('=')?;
2101 /// The multiple statement variant currently only detects `iter.next()?`/`iter.next().unwrap()`
2102 /// in two separate `let` statements that immediately follow the `splitn()`
2103 #[clippy::version = "1.57.0"]
2104 pub MANUAL_SPLIT_ONCE,
2106 "replace `.splitn(2, pat)` with `.split_once(pat)`"
2109 declare_clippy_lint! {
2110 /// ### What it does
2111 /// Checks for usages of `str::splitn` (or `str::rsplitn`) where using `str::split` would be the same.
2112 /// ### Why is this bad?
2113 /// The function `split` is simpler and there is no performance difference in these cases, considering
2114 /// that both functions return a lazy iterator.
2117 /// let str = "key=value=add";
2118 /// let _ = str.splitn(3, '=').next().unwrap();
2123 /// let str = "key=value=add";
2124 /// let _ = str.split('=').next().unwrap();
2126 #[clippy::version = "1.59.0"]
2127 pub NEEDLESS_SPLITN,
2129 "usages of `str::splitn` that can be replaced with `str::split`"
2132 declare_clippy_lint! {
2133 /// ### What it does
2134 /// Checks for unnecessary calls to [`ToOwned::to_owned`](https://doc.rust-lang.org/std/borrow/trait.ToOwned.html#tymethod.to_owned)
2135 /// and other `to_owned`-like functions.
2137 /// ### Why is this bad?
2138 /// The unnecessary calls result in useless allocations.
2140 /// ### Known problems
2141 /// `unnecessary_to_owned` can falsely trigger if `IntoIterator::into_iter` is applied to an
2142 /// owned copy of a resource and the resource is later used mutably. See
2143 /// [#8148](https://github.com/rust-lang/rust-clippy/issues/8148).
2147 /// let path = std::path::Path::new("x");
2148 /// foo(&path.to_string_lossy().to_string());
2149 /// fn foo(s: &str) {}
2153 /// let path = std::path::Path::new("x");
2154 /// foo(&path.to_string_lossy());
2155 /// fn foo(s: &str) {}
2157 #[clippy::version = "1.59.0"]
2158 pub UNNECESSARY_TO_OWNED,
2160 "unnecessary calls to `to_owned`-like functions"
2163 declare_clippy_lint! {
2164 /// ### What it does
2165 /// Checks for use of `.collect::<Vec<String>>().join("")` on iterators.
2167 /// ### Why is this bad?
2168 /// `.collect::<String>()` is more concise and might be more performant
2172 /// let vector = vec!["hello", "world"];
2173 /// let output = vector.iter().map(|item| item.to_uppercase()).collect::<Vec<String>>().join("");
2174 /// println!("{}", output);
2176 /// The correct use would be:
2178 /// let vector = vec!["hello", "world"];
2179 /// let output = vector.iter().map(|item| item.to_uppercase()).collect::<String>();
2180 /// println!("{}", output);
2182 /// ### Known problems
2183 /// While `.collect::<String>()` is sometimes more performant, there are cases where
2184 /// using `.collect::<String>()` over `.collect::<Vec<String>>().join("")`
2185 /// will prevent loop unrolling and will result in a negative performance impact.
2187 /// Additionally, differences have been observed between aarch64 and x86_64 assembly output,
2188 /// with aarch64 tending to producing faster assembly in more cases when using `.collect::<String>()`
2189 #[clippy::version = "1.61.0"]
2190 pub UNNECESSARY_JOIN,
2192 "using `.collect::<Vec<String>>().join(\"\")` on an iterator"
2195 declare_clippy_lint! {
2196 /// ### What it does
2197 /// Checks for no-op uses of `Option::{as_deref, as_deref_mut}`,
2198 /// for example, `Option<&T>::as_deref()` returns the same type.
2200 /// ### Why is this bad?
2201 /// Redundant code and improving readability.
2205 /// let a = Some(&1);
2206 /// let b = a.as_deref(); // goes from Option<&i32> to Option<&i32>
2211 /// let a = Some(&1);
2214 #[clippy::version = "1.57.0"]
2215 pub NEEDLESS_OPTION_AS_DEREF,
2217 "no-op use of `deref` or `deref_mut` method to `Option`."
2220 declare_clippy_lint! {
2221 /// ### What it does
2222 /// Finds usages of [`char::is_digit`](https://doc.rust-lang.org/stable/std/primitive.char.html#method.is_digit) that
2223 /// can be replaced with [`is_ascii_digit`](https://doc.rust-lang.org/stable/std/primitive.char.html#method.is_ascii_digit) or
2224 /// [`is_ascii_hexdigit`](https://doc.rust-lang.org/stable/std/primitive.char.html#method.is_ascii_hexdigit).
2226 /// ### Why is this bad?
2227 /// `is_digit(..)` is slower and requires specifying the radix.
2231 /// let c: char = '6';
2237 /// let c: char = '6';
2238 /// c.is_ascii_digit();
2239 /// c.is_ascii_hexdigit();
2241 #[clippy::version = "1.62.0"]
2242 pub IS_DIGIT_ASCII_RADIX,
2244 "use of `char::is_digit(..)` with literal radix of 10 or 16"
2247 declare_clippy_lint! {
2248 /// ### What it does
2249 /// Checks for calling `take` function after `as_ref`.
2251 /// ### Why is this bad?
2252 /// Redundant code. `take` writes `None` to its argument.
2253 /// In this case the modification is useless as it's a temporary that cannot be read from afterwards.
2257 /// let x = Some(3);
2258 /// x.as_ref().take();
2262 /// let x = Some(3);
2265 #[clippy::version = "1.62.0"]
2266 pub NEEDLESS_OPTION_TAKE,
2268 "using `.as_ref().take()` on a temporary value"
2271 declare_clippy_lint! {
2272 /// ### What it does
2273 /// Checks for `replace` statements which have no effect.
2275 /// ### Why is this bad?
2276 /// It's either a mistake or confusing.
2280 /// "1234".replace("12", "12");
2281 /// "1234".replacen("12", "12", 1);
2283 #[clippy::version = "1.63.0"]
2284 pub NO_EFFECT_REPLACE,
2286 "replace with no effect"
2289 declare_clippy_lint! {
2290 /// ### What it does
2291 /// Checks for usages of `.then_some(..).unwrap_or(..)`
2293 /// ### Why is this bad?
2294 /// This can be written more clearly with `if .. else ..`
2297 /// This lint currently only looks for usages of
2298 /// `.then_some(..).unwrap_or(..)`, but will be expanded
2299 /// to account for similar patterns.
2304 /// x.then_some("a").unwrap_or("b");
2309 /// if x { "a" } else { "b" };
2311 #[clippy::version = "1.64.0"]
2312 pub OBFUSCATED_IF_ELSE,
2314 "use of `.then_some(..).unwrap_or(..)` can be written \
2315 more clearly with `if .. else ..`"
2318 declare_clippy_lint! {
2319 /// ### What it does
2321 /// Checks for calls to `iter`, `iter_mut` or `into_iter` on collections containing a single item
2323 /// ### Why is this bad?
2325 /// It is simpler to use the once function from the standard library:
2330 /// let a = [123].iter();
2331 /// let b = Some(123).into_iter();
2336 /// let a = iter::once(&123);
2337 /// let b = iter::once(123);
2340 /// ### Known problems
2342 /// The type of the resulting iterator might become incompatible with its usage
2343 #[clippy::version = "1.64.0"]
2344 pub ITER_ON_SINGLE_ITEMS,
2346 "Iterator for array of length 1"
2349 declare_clippy_lint! {
2350 /// ### What it does
2352 /// Checks for calls to `iter`, `iter_mut` or `into_iter` on empty collections
2354 /// ### Why is this bad?
2356 /// It is simpler to use the empty function from the standard library:
2361 /// use std::{slice, option};
2362 /// let a: slice::Iter<i32> = [].iter();
2363 /// let f: option::IntoIter<i32> = None.into_iter();
2368 /// let a: iter::Empty<i32> = iter::empty();
2369 /// let b: iter::Empty<i32> = iter::empty();
2372 /// ### Known problems
2374 /// The type of the resulting iterator might become incompatible with its usage
2375 #[clippy::version = "1.64.0"]
2376 pub ITER_ON_EMPTY_COLLECTIONS,
2378 "Iterator for empty array"
2381 declare_clippy_lint! {
2382 /// ### What it does
2383 /// Checks for naive byte counts
2385 /// ### Why is this bad?
2386 /// The [`bytecount`](https://crates.io/crates/bytecount)
2387 /// crate has methods to count your bytes faster, especially for large slices.
2389 /// ### Known problems
2390 /// If you have predominantly small slices, the
2391 /// `bytecount::count(..)` method may actually be slower. However, if you can
2392 /// ensure that less than 2³²-1 matches arise, the `naive_count_32(..)` can be
2393 /// faster in those cases.
2397 /// # let vec = vec![1_u8];
2398 /// let count = vec.iter().filter(|x| **x == 0u8).count();
2403 /// # let vec = vec![1_u8];
2404 /// let count = bytecount::count(&vec, 0u8);
2406 #[clippy::version = "pre 1.29.0"]
2407 pub NAIVE_BYTECOUNT,
2409 "use of naive `<slice>.filter(|&x| x == y).count()` to count byte values"
2412 declare_clippy_lint! {
2413 /// ### What it does
2414 /// It checks for `str::bytes().count()` and suggests replacing it with
2417 /// ### Why is this bad?
2418 /// `str::bytes().count()` is longer and may not be as performant as using
2423 /// "hello".bytes().count();
2424 /// String::from("hello").bytes().count();
2429 /// String::from("hello").len();
2431 #[clippy::version = "1.62.0"]
2432 pub BYTES_COUNT_TO_LEN,
2434 "Using `bytes().count()` when `len()` performs the same functionality"
2437 declare_clippy_lint! {
2438 /// ### What it does
2439 /// Checks for calls to `ends_with` with possible file extensions
2440 /// and suggests to use a case-insensitive approach instead.
2442 /// ### Why is this bad?
2443 /// `ends_with` is case-sensitive and may not detect files with a valid extension.
2447 /// fn is_rust_file(filename: &str) -> bool {
2448 /// filename.ends_with(".rs")
2453 /// fn is_rust_file(filename: &str) -> bool {
2454 /// let filename = std::path::Path::new(filename);
2455 /// filename.extension()
2456 /// .map_or(false, |ext| ext.eq_ignore_ascii_case("rs"))
2459 #[clippy::version = "1.51.0"]
2460 pub CASE_SENSITIVE_FILE_EXTENSION_COMPARISONS,
2462 "Checks for calls to ends_with with case-sensitive file extensions"
2465 declare_clippy_lint! {
2466 /// ### What it does
2467 /// Checks for using `x.get(0)` instead of
2470 /// ### Why is this bad?
2471 /// Using `x.first()` is easier to read and has the same
2476 /// let x = vec![2, 3, 5];
2477 /// let first_element = x.get(0);
2482 /// let x = vec![2, 3, 5];
2483 /// let first_element = x.first();
2485 #[clippy::version = "1.63.0"]
2488 "Using `x.get(0)` when `x.first()` is simpler"
2491 declare_clippy_lint! {
2492 /// ### What it does
2494 /// Finds patterns that reimplement `Option::ok_or`.
2496 /// ### Why is this bad?
2498 /// Concise code helps focusing on behavior instead of boilerplate.
2502 /// let foo: Option<i32> = None;
2503 /// foo.map_or(Err("error"), |v| Ok(v));
2508 /// let foo: Option<i32> = None;
2509 /// foo.ok_or("error");
2511 #[clippy::version = "1.49.0"]
2514 "finds patterns that can be encoded more concisely with `Option::ok_or`"
2517 declare_clippy_lint! {
2518 /// ### What it does
2519 /// Checks for usage of `map(|x| x.clone())` or
2520 /// dereferencing closures for `Copy` types, on `Iterator` or `Option`,
2521 /// and suggests `cloned()` or `copied()` instead
2523 /// ### Why is this bad?
2524 /// Readability, this can be written more concisely
2528 /// let x = vec![42, 43];
2529 /// let y = x.iter();
2530 /// let z = y.map(|i| *i);
2533 /// The correct use would be:
2536 /// let x = vec![42, 43];
2537 /// let y = x.iter();
2538 /// let z = y.cloned();
2540 #[clippy::version = "pre 1.29.0"]
2543 "using `iterator.map(|x| x.clone())`, or dereferencing closures for `Copy` types"
2546 declare_clippy_lint! {
2547 /// ### What it does
2548 /// Checks for instances of `map_err(|_| Some::Enum)`
2550 /// ### Why is this bad?
2551 /// This `map_err` throws away the original error rather than allowing the enum to contain and report the cause of the error
2558 /// #[derive(Debug)]
2564 /// impl fmt::Display for Error {
2565 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2567 /// Error::Indivisible => write!(f, "could not divide input by three"),
2568 /// Error::Remainder(remainder) => write!(
2570 /// "input is not divisible by three, remainder = {}",
2577 /// impl std::error::Error for Error {}
2579 /// fn divisible_by_3(input: &str) -> Result<(), Error> {
2582 /// .map_err(|_| Error::Indivisible)
2584 /// .and_then(|remainder| {
2585 /// if remainder == 0 {
2588 /// Err(Error::Remainder(remainder as u8))
2596 /// use std::{fmt, num::ParseIntError};
2598 /// #[derive(Debug)]
2600 /// Indivisible(ParseIntError),
2604 /// impl fmt::Display for Error {
2605 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2607 /// Error::Indivisible(_) => write!(f, "could not divide input by three"),
2608 /// Error::Remainder(remainder) => write!(
2610 /// "input is not divisible by three, remainder = {}",
2617 /// impl std::error::Error for Error {
2618 /// fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
2620 /// Error::Indivisible(source) => Some(source),
2626 /// fn divisible_by_3(input: &str) -> Result<(), Error> {
2629 /// .map_err(Error::Indivisible)
2631 /// .and_then(|remainder| {
2632 /// if remainder == 0 {
2635 /// Err(Error::Remainder(remainder as u8))
2640 #[clippy::version = "1.48.0"]
2643 "`map_err` should not ignore the original error"
2646 declare_clippy_lint! {
2647 /// ### What it does
2648 /// Checks for `&mut Mutex::lock` calls
2650 /// ### Why is this bad?
2651 /// `Mutex::lock` is less efficient than
2652 /// calling `Mutex::get_mut`. In addition you also have a statically
2653 /// guarantee that the mutex isn't locked, instead of just a runtime
2658 /// use std::sync::{Arc, Mutex};
2660 /// let mut value_rc = Arc::new(Mutex::new(42_u8));
2661 /// let value_mutex = Arc::get_mut(&mut value_rc).unwrap();
2663 /// let mut value = value_mutex.lock().unwrap();
2668 /// use std::sync::{Arc, Mutex};
2670 /// let mut value_rc = Arc::new(Mutex::new(42_u8));
2671 /// let value_mutex = Arc::get_mut(&mut value_rc).unwrap();
2673 /// let value = value_mutex.get_mut().unwrap();
2676 #[clippy::version = "1.49.0"]
2679 "`&mut Mutex::lock` does unnecessary locking"
2682 pub struct Methods {
2683 avoid_breaking_exported_api: bool,
2684 msrv: Option<RustcVersion>,
2685 allow_expect_in_tests: bool,
2686 allow_unwrap_in_tests: bool,
2692 avoid_breaking_exported_api: bool,
2693 msrv: Option<RustcVersion>,
2694 allow_expect_in_tests: bool,
2695 allow_unwrap_in_tests: bool,
2698 avoid_breaking_exported_api,
2700 allow_expect_in_tests,
2701 allow_unwrap_in_tests,
2706 impl_lint_pass!(Methods => [
2709 SHOULD_IMPLEMENT_TRAIT,
2710 WRONG_SELF_CONVENTION,
2712 UNWRAP_OR_ELSE_DEFAULT,
2714 RESULT_MAP_OR_INTO_OPTION,
2716 BIND_INSTEAD_OF_MAP,
2725 ITER_OVEREAGER_CLONED,
2726 CLONED_INSTEAD_OF_COPIED,
2728 INEFFICIENT_TO_STRING,
2730 SINGLE_CHAR_PATTERN,
2731 SINGLE_CHAR_ADD_STR,
2735 FILTER_MAP_IDENTITY,
2743 ITERATOR_STEP_BY_ZERO,
2752 STRING_EXTEND_CHARS,
2753 ITER_CLONED_COLLECT,
2757 UNNECESSARY_FILTER_MAP,
2758 UNNECESSARY_FIND_MAP,
2761 UNINIT_ASSUMED_INIT,
2762 MANUAL_SATURATING_ARITHMETIC,
2765 OPTION_AS_REF_DEREF,
2766 UNNECESSARY_LAZY_EVALUATIONS,
2767 MAP_COLLECT_RESULT_UNIT,
2768 FROM_ITER_INSTEAD_OF_COLLECT,
2776 UNNECESSARY_TO_OWNED,
2779 NEEDLESS_OPTION_AS_DEREF,
2780 IS_DIGIT_ASCII_RADIX,
2781 NEEDLESS_OPTION_TAKE,
2784 ITER_ON_SINGLE_ITEMS,
2785 ITER_ON_EMPTY_COLLECTIONS,
2788 CASE_SENSITIVE_FILE_EXTENSION_COMPARISONS,
2796 /// Extracts a method call name, args, and `Span` of the method name.
2797 fn method_call<'tcx>(recv: &'tcx hir::Expr<'tcx>) -> Option<(&'tcx str, &'tcx [hir::Expr<'tcx>], Span)> {
2798 if let ExprKind::MethodCall(path, args, _) = recv.kind {
2799 if !args.iter().any(|e| e.span.from_expansion()) {
2800 let name = path.ident.name.as_str();
2801 return Some((name, args, path.ident.span));
2807 impl<'tcx> LateLintPass<'tcx> for Methods {
2808 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) {
2809 if expr.span.from_expansion() {
2813 self.check_methods(cx, expr);
2816 hir::ExprKind::Call(func, args) => {
2817 from_iter_instead_of_collect::check(cx, expr, args, func);
2819 hir::ExprKind::MethodCall(method_call, args, _) => {
2820 let method_span = method_call.ident.span;
2821 or_fun_call::check(cx, expr, method_span, method_call.ident.as_str(), args);
2822 expect_fun_call::check(cx, expr, method_span, method_call.ident.as_str(), args);
2823 clone_on_copy::check(cx, expr, method_call.ident.name, args);
2824 clone_on_ref_ptr::check(cx, expr, method_call.ident.name, args);
2825 inefficient_to_string::check(cx, expr, method_call.ident.name, args);
2826 single_char_add_str::check(cx, expr, args);
2827 into_iter_on_ref::check(cx, expr, method_span, method_call.ident.name, args);
2828 single_char_pattern::check(cx, expr, method_call.ident.name, args);
2829 unnecessary_to_owned::check(cx, expr, method_call.ident.name, args, self.msrv);
2831 hir::ExprKind::Binary(op, lhs, rhs) if op.node == hir::BinOpKind::Eq || op.node == hir::BinOpKind::Ne => {
2832 let mut info = BinaryExprInfo {
2836 eq: op.node == hir::BinOpKind::Eq,
2838 lint_binary_expr_with_method_call(cx, &mut info);
2844 #[allow(clippy::too_many_lines)]
2845 fn check_impl_item(&mut self, cx: &LateContext<'tcx>, impl_item: &'tcx hir::ImplItem<'_>) {
2846 if in_external_macro(cx.sess(), impl_item.span) {
2849 let name = impl_item.ident.name.as_str();
2850 let parent = cx.tcx.hir().get_parent_item(impl_item.hir_id());
2851 let item = cx.tcx.hir().expect_item(parent);
2852 let self_ty = cx.tcx.type_of(item.def_id);
2854 let implements_trait = matches!(item.kind, hir::ItemKind::Impl(hir::Impl { of_trait: Some(_), .. }));
2856 if let hir::ImplItemKind::Fn(ref sig, id) = impl_item.kind;
2857 if let Some(first_arg) = iter_input_pats(sig.decl, cx.tcx.hir().body(id)).next();
2859 let method_sig = cx.tcx.fn_sig(impl_item.def_id);
2860 let method_sig = cx.tcx.erase_late_bound_regions(method_sig);
2862 let first_arg_ty = method_sig.inputs().iter().next();
2864 // check conventions w.r.t. conversion method names and predicates
2865 if let Some(first_arg_ty) = first_arg_ty;
2868 // if this impl block implements a trait, lint in trait definition instead
2869 if !implements_trait && cx.access_levels.is_exported(impl_item.def_id) {
2870 // check missing trait implementations
2871 for method_config in &TRAIT_METHODS {
2872 if name == method_config.method_name &&
2873 sig.decl.inputs.len() == method_config.param_count &&
2874 method_config.output_type.matches(&sig.decl.output) &&
2875 method_config.self_kind.matches(cx, self_ty, *first_arg_ty) &&
2876 fn_header_equals(method_config.fn_header, sig.header) &&
2877 method_config.lifetime_param_cond(impl_item)
2881 SHOULD_IMPLEMENT_TRAIT,
2884 "method `{}` can be confused for the standard trait method `{}::{}`",
2885 method_config.method_name,
2886 method_config.trait_name,
2887 method_config.method_name
2891 "consider implementing the trait `{}` or choosing a less ambiguous method name",
2892 method_config.trait_name
2899 if sig.decl.implicit_self.has_implicit_self()
2900 && !(self.avoid_breaking_exported_api
2901 && cx.access_levels.is_exported(impl_item.def_id))
2903 wrong_self_convention::check(
2916 // if this impl block implements a trait, lint in trait definition instead
2917 if implements_trait {
2921 if let hir::ImplItemKind::Fn(_, _) = impl_item.kind {
2922 let ret_ty = return_ty(cx, impl_item.hir_id());
2924 // walk the return type and check for Self (this does not check associated types)
2925 if let Some(self_adt) = self_ty.ty_adt_def() {
2926 if contains_adt_constructor(ret_ty, self_adt) {
2929 } else if contains_ty(ret_ty, self_ty) {
2933 // if return type is impl trait, check the associated types
2934 if let ty::Opaque(def_id, _) = *ret_ty.kind() {
2935 // one of the associated types must be Self
2936 for &(predicate, _span) in cx.tcx.explicit_item_bounds(def_id) {
2937 if let ty::PredicateKind::Projection(projection_predicate) = predicate.kind().skip_binder() {
2938 let assoc_ty = match projection_predicate.term {
2939 ty::Term::Ty(ty) => ty,
2940 ty::Term::Const(_c) => continue,
2942 // walk the associated type and check for Self
2943 if let Some(self_adt) = self_ty.ty_adt_def() {
2944 if contains_adt_constructor(assoc_ty, self_adt) {
2947 } else if contains_ty(assoc_ty, self_ty) {
2954 if name == "new" && ret_ty != self_ty {
2959 "methods called `new` usually return `Self`",
2965 fn check_trait_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx TraitItem<'_>) {
2966 if in_external_macro(cx.tcx.sess, item.span) {
2971 if let TraitItemKind::Fn(ref sig, _) = item.kind;
2972 if sig.decl.implicit_self.has_implicit_self();
2973 if let Some(first_arg_ty) = sig.decl.inputs.iter().next();
2976 let first_arg_span = first_arg_ty.span;
2977 let first_arg_ty = hir_ty_to_ty(cx.tcx, first_arg_ty);
2978 let self_ty = TraitRef::identity(cx.tcx, item.def_id.to_def_id()).self_ty().skip_binder();
2979 wrong_self_convention::check(
2981 item.ident.name.as_str(),
2992 if item.ident.name == sym::new;
2993 if let TraitItemKind::Fn(_, _) = item.kind;
2994 let ret_ty = return_ty(cx, item.hir_id());
2995 let self_ty = TraitRef::identity(cx.tcx, item.def_id.to_def_id()).self_ty().skip_binder();
2996 if !contains_ty(ret_ty, self_ty);
3003 "methods called `new` usually return `Self`",
3009 extract_msrv_attr!(LateContext);
3013 #[allow(clippy::too_many_lines)]
3014 fn check_methods<'tcx>(&self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
3015 if let Some((name, [recv, args @ ..], span)) = method_call(expr) {
3016 match (name, args) {
3017 ("add" | "offset" | "sub" | "wrapping_offset" | "wrapping_add" | "wrapping_sub", [_arg]) => {
3018 zst_offset::check(cx, expr, recv);
3020 ("and_then", [arg]) => {
3021 let biom_option_linted = bind_instead_of_map::OptionAndThenSome::check(cx, expr, recv, arg);
3022 let biom_result_linted = bind_instead_of_map::ResultAndThenOk::check(cx, expr, recv, arg);
3023 if !biom_option_linted && !biom_result_linted {
3024 unnecessary_lazy_eval::check(cx, expr, recv, arg, "and");
3027 ("as_deref" | "as_deref_mut", []) => {
3028 needless_option_as_deref::check(cx, expr, recv, name);
3030 ("as_mut", []) => useless_asref::check(cx, expr, "as_mut", recv),
3031 ("as_ref", []) => useless_asref::check(cx, expr, "as_ref", recv),
3032 ("assume_init", []) => uninit_assumed_init::check(cx, expr, recv),
3033 ("cloned", []) => cloned_instead_of_copied::check(cx, expr, recv, span, self.msrv),
3034 ("collect", []) => match method_call(recv) {
3035 Some((name @ ("cloned" | "copied"), [recv2], _)) => {
3036 iter_cloned_collect::check(cx, name, expr, recv2);
3038 Some(("map", [m_recv, m_arg], _)) => {
3039 map_collect_result_unit::check(cx, expr, m_recv, m_arg, recv);
3041 Some(("take", [take_self_arg, take_arg], _)) => {
3042 if meets_msrv(self.msrv, msrvs::STR_REPEAT) {
3043 manual_str_repeat::check(cx, expr, recv, take_self_arg, take_arg);
3048 ("count", []) if is_trait_method(cx, expr, sym::Iterator) => match method_call(recv) {
3049 Some(("cloned", [recv2], _)) => iter_overeager_cloned::check(cx, expr, recv, recv2, true, false),
3050 Some((name2 @ ("into_iter" | "iter" | "iter_mut"), [recv2], _)) => {
3051 iter_count::check(cx, expr, recv2, name2);
3053 Some(("map", [_, arg], _)) => suspicious_map::check(cx, expr, recv, arg),
3054 Some(("filter", [recv2, arg], _)) => bytecount::check(cx, expr, recv2, arg),
3055 Some(("bytes", [recv2], _)) => bytes_count_to_len::check(cx, expr, recv, recv2),
3058 ("drain", [arg]) => {
3059 iter_with_drain::check(cx, expr, recv, span, arg);
3061 ("ends_with", [arg]) => {
3062 if let ExprKind::MethodCall(_, _, span) = expr.kind {
3063 case_sensitive_file_extension_comparisons::check(cx, expr, span, recv, arg);
3066 ("expect", [_]) => match method_call(recv) {
3067 Some(("ok", [recv], _)) => ok_expect::check(cx, expr, recv),
3068 Some(("err", [recv], err_span)) => err_expect::check(cx, expr, recv, self.msrv, span, err_span),
3069 _ => expect_used::check(cx, expr, recv, false, self.allow_expect_in_tests),
3071 ("expect_err", [_]) => expect_used::check(cx, expr, recv, true, self.allow_expect_in_tests),
3072 ("extend", [arg]) => {
3073 string_extend_chars::check(cx, expr, recv, arg);
3074 extend_with_drain::check(cx, expr, recv, arg);
3076 ("filter_map", [arg]) => {
3077 unnecessary_filter_map::check(cx, expr, arg, name);
3078 filter_map_identity::check(cx, expr, arg, span);
3080 ("find_map", [arg]) => {
3081 unnecessary_filter_map::check(cx, expr, arg, name);
3083 ("flat_map", [arg]) => {
3084 flat_map_identity::check(cx, expr, arg, span);
3085 flat_map_option::check(cx, expr, arg, span);
3087 ("flatten", []) => match method_call(recv) {
3088 Some(("map", [recv, map_arg], map_span)) => map_flatten::check(cx, expr, recv, map_arg, map_span),
3089 Some(("cloned", [recv2], _)) => iter_overeager_cloned::check(cx, expr, recv, recv2, false, true),
3092 ("fold", [init, acc]) => unnecessary_fold::check(cx, expr, init, acc, span),
3093 ("for_each", [_]) => {
3094 if let Some(("inspect", [_, _], span2)) = method_call(recv) {
3095 inspect_for_each::check(cx, expr, span2);
3099 get_first::check(cx, expr, recv, arg);
3100 get_last_with_len::check(cx, expr, recv, arg);
3102 ("get_or_insert_with", [arg]) => unnecessary_lazy_eval::check(cx, expr, recv, arg, "get_or_insert"),
3103 ("is_file", []) => filetype_is_file::check(cx, expr, recv),
3104 ("is_digit", [radix]) => is_digit_ascii_radix::check(cx, expr, recv, radix, self.msrv),
3105 ("is_none", []) => check_is_some_is_none(cx, expr, recv, false),
3106 ("is_some", []) => check_is_some_is_none(cx, expr, recv, true),
3107 ("iter" | "iter_mut" | "into_iter", []) => {
3108 iter_on_single_or_empty_collections::check(cx, expr, name, recv);
3110 ("join", [join_arg]) => {
3111 if let Some(("collect", _, span)) = method_call(recv) {
3112 unnecessary_join::check(cx, expr, recv, join_arg, span);
3115 ("last", []) | ("skip", [_]) => {
3116 if let Some((name2, [recv2, args2 @ ..], _span2)) = method_call(recv) {
3117 if let ("cloned", []) = (name2, args2) {
3118 iter_overeager_cloned::check(cx, expr, recv, recv2, false, false);
3123 mut_mutex_lock::check(cx, expr, recv, span);
3125 (name @ ("map" | "map_err"), [m_arg]) => {
3127 map_clone::check(cx, expr, recv, m_arg, self.msrv);
3129 map_err_ignore::check(cx, expr, m_arg);
3131 if let Some((name, [recv2, args @ ..], span2)) = method_call(recv) {
3132 match (name, args) {
3133 ("as_mut", []) => option_as_ref_deref::check(cx, expr, recv2, m_arg, true, self.msrv),
3134 ("as_ref", []) => option_as_ref_deref::check(cx, expr, recv2, m_arg, false, self.msrv),
3135 ("filter", [f_arg]) => {
3136 filter_map::check(cx, expr, recv2, f_arg, span2, recv, m_arg, span, false);
3138 ("find", [f_arg]) => {
3139 filter_map::check(cx, expr, recv2, f_arg, span2, recv, m_arg, span, true);
3144 map_identity::check(cx, expr, recv, m_arg, name, span);
3146 ("map_or", [def, map]) => {
3147 option_map_or_none::check(cx, expr, recv, def, map);
3148 manual_ok_or::check(cx, expr, recv, def, map);
3151 if let Some((name2, [recv2, args2 @ ..], _)) = method_call(recv) {
3152 match (name2, args2) {
3153 ("cloned", []) => iter_overeager_cloned::check(cx, expr, recv, recv2, false, false),
3154 ("filter", [arg]) => filter_next::check(cx, expr, recv2, arg),
3155 ("filter_map", [arg]) => filter_map_next::check(cx, expr, recv2, arg, self.msrv),
3156 ("iter", []) => iter_next_slice::check(cx, expr, recv2),
3157 ("skip", [arg]) => iter_skip_next::check(cx, expr, recv2, arg),
3158 ("skip_while", [_]) => skip_while_next::check(cx, expr),
3163 ("nth", [n_arg]) => match method_call(recv) {
3164 Some(("bytes", [recv2], _)) => bytes_nth::check(cx, expr, recv2, n_arg),
3165 Some(("cloned", [recv2], _)) => iter_overeager_cloned::check(cx, expr, recv, recv2, false, false),
3166 Some(("iter", [recv2], _)) => iter_nth::check(cx, expr, recv2, recv, n_arg, false),
3167 Some(("iter_mut", [recv2], _)) => iter_nth::check(cx, expr, recv2, recv, n_arg, true),
3168 _ => iter_nth_zero::check(cx, expr, recv, n_arg),
3170 ("ok_or_else", [arg]) => unnecessary_lazy_eval::check(cx, expr, recv, arg, "ok_or"),
3171 ("or_else", [arg]) => {
3172 if !bind_instead_of_map::ResultOrElseErrInfo::check(cx, expr, recv, arg) {
3173 unnecessary_lazy_eval::check(cx, expr, recv, arg, "or");
3176 ("splitn" | "rsplitn", [count_arg, pat_arg]) => {
3177 if let Some((Constant::Int(count), _)) = constant(cx, cx.typeck_results(), count_arg) {
3178 suspicious_splitn::check(cx, name, expr, recv, count);
3179 str_splitn::check(cx, name, expr, recv, pat_arg, count, self.msrv);
3182 ("splitn_mut" | "rsplitn_mut", [count_arg, _]) => {
3183 if let Some((Constant::Int(count), _)) = constant(cx, cx.typeck_results(), count_arg) {
3184 suspicious_splitn::check(cx, name, expr, recv, count);
3187 ("step_by", [arg]) => iterator_step_by_zero::check(cx, expr, arg),
3188 ("take", [_arg]) => {
3189 if let Some((name2, [recv2, args2 @ ..], _span2)) = method_call(recv) {
3190 if let ("cloned", []) = (name2, args2) {
3191 iter_overeager_cloned::check(cx, expr, recv, recv2, false, false);
3195 ("take", []) => needless_option_take::check(cx, expr, recv),
3196 ("then", [arg]) => {
3197 if !meets_msrv(self.msrv, msrvs::BOOL_THEN_SOME) {
3200 unnecessary_lazy_eval::check(cx, expr, recv, arg, "then_some");
3202 ("to_os_string" | "to_owned" | "to_path_buf" | "to_vec", []) => {
3203 implicit_clone::check(cx, name, expr, recv);
3206 match method_call(recv) {
3207 Some(("get", [recv, get_arg], _)) => {
3208 get_unwrap::check(cx, expr, recv, get_arg, false);
3210 Some(("get_mut", [recv, get_arg], _)) => {
3211 get_unwrap::check(cx, expr, recv, get_arg, true);
3213 Some(("or", [recv, or_arg], or_span)) => {
3214 or_then_unwrap::check(cx, expr, recv, or_arg, or_span);
3218 unwrap_used::check(cx, expr, recv, false, self.allow_unwrap_in_tests);
3220 ("unwrap_err", []) => unwrap_used::check(cx, expr, recv, true, self.allow_unwrap_in_tests),
3221 ("unwrap_or", [u_arg]) => match method_call(recv) {
3222 Some((arith @ ("checked_add" | "checked_sub" | "checked_mul"), [lhs, rhs], _)) => {
3223 manual_saturating_arithmetic::check(cx, expr, lhs, rhs, u_arg, &arith["checked_".len()..]);
3225 Some(("map", [m_recv, m_arg], span)) => {
3226 option_map_unwrap_or::check(cx, expr, m_recv, m_arg, recv, u_arg, span);
3228 Some(("then_some", [t_recv, t_arg], _)) => {
3229 obfuscated_if_else::check(cx, expr, t_recv, t_arg, u_arg);
3233 ("unwrap_or_else", [u_arg]) => match method_call(recv) {
3234 Some(("map", [recv, map_arg], _))
3235 if map_unwrap_or::check(cx, expr, recv, map_arg, u_arg, self.msrv) => {},
3237 unwrap_or_else_default::check(cx, expr, recv, u_arg);
3238 unnecessary_lazy_eval::check(cx, expr, recv, u_arg, "unwrap_or");
3241 ("replace" | "replacen", [arg1, arg2] | [arg1, arg2, _]) => {
3242 no_effect_replace::check(cx, expr, arg1, arg2);
3250 fn check_is_some_is_none(cx: &LateContext<'_>, expr: &Expr<'_>, recv: &Expr<'_>, is_some: bool) {
3251 if let Some((name @ ("find" | "position" | "rposition"), [f_recv, arg], span)) = method_call(recv) {
3252 search_is_some::check(cx, expr, name, is_some, f_recv, arg, recv, span);
3256 /// Used for `lint_binary_expr_with_method_call`.
3257 #[derive(Copy, Clone)]
3258 struct BinaryExprInfo<'a> {
3259 expr: &'a hir::Expr<'a>,
3260 chain: &'a hir::Expr<'a>,
3261 other: &'a hir::Expr<'a>,
3265 /// Checks for the `CHARS_NEXT_CMP` and `CHARS_LAST_CMP` lints.
3266 fn lint_binary_expr_with_method_call(cx: &LateContext<'_>, info: &mut BinaryExprInfo<'_>) {
3267 macro_rules! lint_with_both_lhs_and_rhs {
3268 ($func:expr, $cx:expr, $info:ident) => {
3269 if !$func($cx, $info) {
3270 ::std::mem::swap(&mut $info.chain, &mut $info.other);
3271 if $func($cx, $info) {
3278 lint_with_both_lhs_and_rhs!(chars_next_cmp::check, cx, info);
3279 lint_with_both_lhs_and_rhs!(chars_last_cmp::check, cx, info);
3280 lint_with_both_lhs_and_rhs!(chars_next_cmp_with_unwrap::check, cx, info);
3281 lint_with_both_lhs_and_rhs!(chars_last_cmp_with_unwrap::check, cx, info);
3284 const FN_HEADER: hir::FnHeader = hir::FnHeader {
3285 unsafety: hir::Unsafety::Normal,
3286 constness: hir::Constness::NotConst,
3287 asyncness: hir::IsAsync::NotAsync,
3288 abi: rustc_target::spec::abi::Abi::Rust,
3291 struct ShouldImplTraitCase {
3292 trait_name: &'static str,
3293 method_name: &'static str,
3295 fn_header: hir::FnHeader,
3296 // implicit self kind expected (none, self, &self, ...)
3297 self_kind: SelfKind,
3298 // checks against the output type
3299 output_type: OutType,
3300 // certain methods with explicit lifetimes can't implement the equivalent trait method
3301 lint_explicit_lifetime: bool,
3303 impl ShouldImplTraitCase {
3305 trait_name: &'static str,
3306 method_name: &'static str,
3308 fn_header: hir::FnHeader,
3309 self_kind: SelfKind,
3310 output_type: OutType,
3311 lint_explicit_lifetime: bool,
3312 ) -> ShouldImplTraitCase {
3313 ShouldImplTraitCase {
3320 lint_explicit_lifetime,
3324 fn lifetime_param_cond(&self, impl_item: &hir::ImplItem<'_>) -> bool {
3325 self.lint_explicit_lifetime
3326 || !impl_item.generics.params.iter().any(|p| {
3329 hir::GenericParamKind::Lifetime {
3330 kind: hir::LifetimeParamKind::Explicit
3338 const TRAIT_METHODS: [ShouldImplTraitCase; 30] = [
3339 ShouldImplTraitCase::new("std::ops::Add", "add", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3340 ShouldImplTraitCase::new("std::convert::AsMut", "as_mut", 1, FN_HEADER, SelfKind::RefMut, OutType::Ref, true),
3341 ShouldImplTraitCase::new("std::convert::AsRef", "as_ref", 1, FN_HEADER, SelfKind::Ref, OutType::Ref, true),
3342 ShouldImplTraitCase::new("std::ops::BitAnd", "bitand", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3343 ShouldImplTraitCase::new("std::ops::BitOr", "bitor", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3344 ShouldImplTraitCase::new("std::ops::BitXor", "bitxor", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3345 ShouldImplTraitCase::new("std::borrow::Borrow", "borrow", 1, FN_HEADER, SelfKind::Ref, OutType::Ref, true),
3346 ShouldImplTraitCase::new("std::borrow::BorrowMut", "borrow_mut", 1, FN_HEADER, SelfKind::RefMut, OutType::Ref, true),
3347 ShouldImplTraitCase::new("std::clone::Clone", "clone", 1, FN_HEADER, SelfKind::Ref, OutType::Any, true),
3348 ShouldImplTraitCase::new("std::cmp::Ord", "cmp", 2, FN_HEADER, SelfKind::Ref, OutType::Any, true),
3349 // FIXME: default doesn't work
3350 ShouldImplTraitCase::new("std::default::Default", "default", 0, FN_HEADER, SelfKind::No, OutType::Any, true),
3351 ShouldImplTraitCase::new("std::ops::Deref", "deref", 1, FN_HEADER, SelfKind::Ref, OutType::Ref, true),
3352 ShouldImplTraitCase::new("std::ops::DerefMut", "deref_mut", 1, FN_HEADER, SelfKind::RefMut, OutType::Ref, true),
3353 ShouldImplTraitCase::new("std::ops::Div", "div", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3354 ShouldImplTraitCase::new("std::ops::Drop", "drop", 1, FN_HEADER, SelfKind::RefMut, OutType::Unit, true),
3355 ShouldImplTraitCase::new("std::cmp::PartialEq", "eq", 2, FN_HEADER, SelfKind::Ref, OutType::Bool, true),
3356 ShouldImplTraitCase::new("std::iter::FromIterator", "from_iter", 1, FN_HEADER, SelfKind::No, OutType::Any, true),
3357 ShouldImplTraitCase::new("std::str::FromStr", "from_str", 1, FN_HEADER, SelfKind::No, OutType::Any, true),
3358 ShouldImplTraitCase::new("std::hash::Hash", "hash", 2, FN_HEADER, SelfKind::Ref, OutType::Unit, true),
3359 ShouldImplTraitCase::new("std::ops::Index", "index", 2, FN_HEADER, SelfKind::Ref, OutType::Ref, true),
3360 ShouldImplTraitCase::new("std::ops::IndexMut", "index_mut", 2, FN_HEADER, SelfKind::RefMut, OutType::Ref, true),
3361 ShouldImplTraitCase::new("std::iter::IntoIterator", "into_iter", 1, FN_HEADER, SelfKind::Value, OutType::Any, true),
3362 ShouldImplTraitCase::new("std::ops::Mul", "mul", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3363 ShouldImplTraitCase::new("std::ops::Neg", "neg", 1, FN_HEADER, SelfKind::Value, OutType::Any, true),
3364 ShouldImplTraitCase::new("std::iter::Iterator", "next", 1, FN_HEADER, SelfKind::RefMut, OutType::Any, false),
3365 ShouldImplTraitCase::new("std::ops::Not", "not", 1, FN_HEADER, SelfKind::Value, OutType::Any, true),
3366 ShouldImplTraitCase::new("std::ops::Rem", "rem", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3367 ShouldImplTraitCase::new("std::ops::Shl", "shl", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3368 ShouldImplTraitCase::new("std::ops::Shr", "shr", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3369 ShouldImplTraitCase::new("std::ops::Sub", "sub", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3372 #[derive(Clone, Copy, PartialEq, Eq, Debug)]
3381 fn matches<'a>(self, cx: &LateContext<'a>, parent_ty: Ty<'a>, ty: Ty<'a>) -> bool {
3382 fn matches_value<'a>(cx: &LateContext<'a>, parent_ty: Ty<'a>, ty: Ty<'a>) -> bool {
3383 if ty == parent_ty {
3385 } else if ty.is_box() {
3386 ty.boxed_ty() == parent_ty
3387 } else if is_type_diagnostic_item(cx, ty, sym::Rc) || is_type_diagnostic_item(cx, ty, sym::Arc) {
3388 if let ty::Adt(_, substs) = ty.kind() {
3389 substs.types().next().map_or(false, |t| t == parent_ty)
3398 fn matches_ref<'a>(cx: &LateContext<'a>, mutability: hir::Mutability, parent_ty: Ty<'a>, ty: Ty<'a>) -> bool {
3399 if let ty::Ref(_, t, m) = *ty.kind() {
3400 return m == mutability && t == parent_ty;
3403 let trait_path = match mutability {
3404 hir::Mutability::Not => &paths::ASREF_TRAIT,
3405 hir::Mutability::Mut => &paths::ASMUT_TRAIT,
3408 let trait_def_id = match get_trait_def_id(cx, trait_path) {
3410 None => return false,
3412 implements_trait(cx, ty, trait_def_id, &[parent_ty.into()])
3415 fn matches_none<'a>(cx: &LateContext<'a>, parent_ty: Ty<'a>, ty: Ty<'a>) -> bool {
3416 !matches_value(cx, parent_ty, ty)
3417 && !matches_ref(cx, hir::Mutability::Not, parent_ty, ty)
3418 && !matches_ref(cx, hir::Mutability::Mut, parent_ty, ty)
3422 Self::Value => matches_value(cx, parent_ty, ty),
3423 Self::Ref => matches_ref(cx, hir::Mutability::Not, parent_ty, ty) || ty == parent_ty && is_copy(cx, ty),
3424 Self::RefMut => matches_ref(cx, hir::Mutability::Mut, parent_ty, ty),
3425 Self::No => matches_none(cx, parent_ty, ty),
3430 fn description(self) -> &'static str {
3432 Self::Value => "`self` by value",
3433 Self::Ref => "`self` by reference",
3434 Self::RefMut => "`self` by mutable reference",
3435 Self::No => "no `self`",
3440 #[derive(Clone, Copy)]
3449 fn matches(self, ty: &hir::FnRetTy<'_>) -> bool {
3450 let is_unit = |ty: &hir::Ty<'_>| matches!(ty.kind, hir::TyKind::Tup(&[]));
3452 (Self::Unit, &hir::FnRetTy::DefaultReturn(_)) => true,
3453 (Self::Unit, &hir::FnRetTy::Return(ty)) if is_unit(ty) => true,
3454 (Self::Bool, &hir::FnRetTy::Return(ty)) if is_bool(ty) => true,
3455 (Self::Any, &hir::FnRetTy::Return(ty)) if !is_unit(ty) => true,
3456 (Self::Ref, &hir::FnRetTy::Return(ty)) => matches!(ty.kind, hir::TyKind::Rptr(_, _)),
3462 fn is_bool(ty: &hir::Ty<'_>) -> bool {
3463 if let hir::TyKind::Path(QPath::Resolved(_, path)) = ty.kind {
3464 matches!(path.res, Res::PrimTy(PrimTy::Bool))
3470 fn fn_header_equals(expected: hir::FnHeader, actual: hir::FnHeader) -> bool {
3471 expected.constness == actual.constness
3472 && expected.unsafety == actual.unsafety
3473 && expected.asyncness == actual.asyncness