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;
54 mod needless_option_as_deref;
55 mod needless_option_take;
56 mod no_effect_replace;
57 mod obfuscated_if_else;
59 mod option_as_ref_deref;
60 mod option_map_or_none;
61 mod option_map_unwrap_or;
65 mod single_char_add_str;
66 mod single_char_insert_string;
67 mod single_char_pattern;
68 mod single_char_push_string;
71 mod string_extend_chars;
73 mod suspicious_splitn;
74 mod uninit_assumed_init;
75 mod unnecessary_filter_map;
77 mod unnecessary_iter_cloned;
79 mod unnecessary_lazy_eval;
80 mod unnecessary_to_owned;
81 mod unwrap_or_else_default;
85 mod wrong_self_convention;
88 use bind_instead_of_map::BindInsteadOfMap;
89 use clippy_utils::consts::{constant, Constant};
90 use clippy_utils::diagnostics::{span_lint, span_lint_and_help};
91 use clippy_utils::ty::{contains_adt_constructor, contains_ty, implements_trait, is_copy, is_type_diagnostic_item};
93 contains_return, get_trait_def_id, is_trait_method, iter_input_pats, meets_msrv, msrvs, paths, return_ty,
95 use if_chain::if_chain;
97 use rustc_hir::def::Res;
98 use rustc_hir::{Expr, ExprKind, PrimTy, QPath, TraitItem, TraitItemKind};
99 use rustc_lint::{LateContext, LateLintPass, LintContext};
100 use rustc_middle::lint::in_external_macro;
101 use rustc_middle::ty::{self, TraitRef, Ty};
102 use rustc_semver::RustcVersion;
103 use rustc_session::{declare_tool_lint, impl_lint_pass};
104 use rustc_span::{sym, Span};
105 use rustc_typeck::hir_ty_to_ty;
107 declare_clippy_lint! {
109 /// Checks for usages of `cloned()` on an `Iterator` or `Option` where
110 /// `copied()` could be used instead.
112 /// ### Why is this bad?
113 /// `copied()` is better because it guarantees that the type being cloned
114 /// implements `Copy`.
118 /// [1, 2, 3].iter().cloned();
122 /// [1, 2, 3].iter().copied();
124 #[clippy::version = "1.53.0"]
125 pub CLONED_INSTEAD_OF_COPIED,
127 "used `cloned` where `copied` could be used instead"
130 declare_clippy_lint! {
132 /// Checks for usage of `_.cloned().<func>()` where call to `.cloned()` can be postponed.
134 /// ### Why is this bad?
135 /// It's often inefficient to clone all elements of an iterator, when eventually, only some
136 /// of them will be consumed.
138 /// ### Known Problems
139 /// This `lint` removes the side of effect of cloning items in the iterator.
140 /// A code that relies on that side-effect could fail.
144 /// # let vec = vec!["string".to_string()];
145 /// vec.iter().cloned().take(10);
146 /// vec.iter().cloned().last();
151 /// # let vec = vec!["string".to_string()];
152 /// vec.iter().take(10).cloned();
153 /// vec.iter().last().cloned();
155 #[clippy::version = "1.60.0"]
156 pub ITER_OVEREAGER_CLONED,
158 "using `cloned()` early with `Iterator::iter()` can lead to some performance inefficiencies"
161 declare_clippy_lint! {
163 /// Checks for usages of `Iterator::flat_map()` where `filter_map()` could be
166 /// ### Why is this bad?
167 /// When applicable, `filter_map()` is more clear since it shows that
168 /// `Option` is used to produce 0 or 1 items.
172 /// let nums: Vec<i32> = ["1", "2", "whee!"].iter().flat_map(|x| x.parse().ok()).collect();
176 /// let nums: Vec<i32> = ["1", "2", "whee!"].iter().filter_map(|x| x.parse().ok()).collect();
178 #[clippy::version = "1.53.0"]
181 "used `flat_map` where `filter_map` could be used instead"
184 declare_clippy_lint! {
186 /// Checks for `.unwrap()` or `.unwrap_err()` calls on `Result`s and `.unwrap()` call on `Option`s.
188 /// ### Why is this bad?
189 /// It is better to handle the `None` or `Err` case,
190 /// or at least call `.expect(_)` with a more helpful message. Still, for a lot of
191 /// quick-and-dirty code, `unwrap` is a good choice, which is why this lint is
192 /// `Allow` by default.
194 /// `result.unwrap()` will let the thread panic on `Err` values.
195 /// Normally, you want to implement more sophisticated error handling,
196 /// and propagate errors upwards with `?` operator.
198 /// Even if you want to panic on errors, not all `Error`s implement good
199 /// messages on display. Therefore, it may be beneficial to look at the places
200 /// where they may get displayed. Activate this lint to do just that.
204 /// # let option = Some(1);
205 /// # let result: Result<usize, ()> = Ok(1);
212 /// # let option = Some(1);
213 /// # let result: Result<usize, ()> = Ok(1);
214 /// option.expect("more helpful message");
215 /// result.expect("more helpful message");
218 /// If [expect_used](#expect_used) is enabled, instead:
220 /// # let option = Some(1);
221 /// # let result: Result<usize, ()> = Ok(1);
228 #[clippy::version = "1.45.0"]
231 "using `.unwrap()` on `Result` or `Option`, which should at least get a better message using `expect()`"
234 declare_clippy_lint! {
236 /// Checks for `.expect()` or `.expect_err()` calls on `Result`s and `.expect()` call on `Option`s.
238 /// ### Why is this bad?
239 /// Usually it is better to handle the `None` or `Err` case.
240 /// Still, for a lot of quick-and-dirty code, `expect` is a good choice, which is why
241 /// this lint is `Allow` by default.
243 /// `result.expect()` will let the thread panic on `Err`
244 /// values. Normally, you want to implement more sophisticated error handling,
245 /// and propagate errors upwards with `?` operator.
249 /// # let option = Some(1);
250 /// # let result: Result<usize, ()> = Ok(1);
251 /// option.expect("one");
252 /// result.expect("one");
257 /// # let option = Some(1);
258 /// # let result: Result<usize, ()> = Ok(1);
265 #[clippy::version = "1.45.0"]
268 "using `.expect()` on `Result` or `Option`, which might be better handled"
271 declare_clippy_lint! {
273 /// Checks for methods that should live in a trait
274 /// implementation of a `std` trait (see [llogiq's blog
275 /// post](http://llogiq.github.io/2015/07/30/traits.html) for further
276 /// information) instead of an inherent implementation.
278 /// ### Why is this bad?
279 /// Implementing the traits improve ergonomics for users of
280 /// the code, often with very little cost. Also people seeing a `mul(...)`
282 /// may expect `*` to work equally, so you should have good reason to disappoint
289 /// fn add(&self, other: &X) -> X {
295 #[clippy::version = "pre 1.29.0"]
296 pub SHOULD_IMPLEMENT_TRAIT,
298 "defining a method that should be implementing a std trait"
301 declare_clippy_lint! {
303 /// Checks for methods with certain name prefixes and which
304 /// doesn't match how self is taken. The actual rules are:
306 /// |Prefix |Postfix |`self` taken | `self` type |
307 /// |-------|------------|-------------------------------|--------------|
308 /// |`as_` | none |`&self` or `&mut self` | any |
309 /// |`from_`| none | none | any |
310 /// |`into_`| none |`self` | any |
311 /// |`is_` | none |`&mut self` or `&self` or none | any |
312 /// |`to_` | `_mut` |`&mut self` | any |
313 /// |`to_` | not `_mut` |`self` | `Copy` |
314 /// |`to_` | not `_mut` |`&self` | not `Copy` |
316 /// Note: Clippy doesn't trigger methods with `to_` prefix in:
317 /// - Traits definition.
318 /// Clippy can not tell if a type that implements a trait is `Copy` or not.
319 /// - Traits implementation, when `&self` is taken.
320 /// The method signature is controlled by the trait and often `&self` is required for all types that implement the trait
321 /// (see e.g. the `std::string::ToString` trait).
323 /// Clippy allows `Pin<&Self>` and `Pin<&mut Self>` if `&self` and `&mut self` is required.
325 /// Please find more info here:
326 /// https://rust-lang.github.io/api-guidelines/naming.html#ad-hoc-conversions-follow-as_-to_-into_-conventions-c-conv
328 /// ### Why is this bad?
329 /// Consistency breeds readability. If you follow the
330 /// conventions, your users won't be surprised that they, e.g., need to supply a
331 /// mutable reference to a `as_..` function.
337 /// fn as_str(self) -> &'static str {
343 #[clippy::version = "pre 1.29.0"]
344 pub WRONG_SELF_CONVENTION,
346 "defining a method named with an established prefix (like \"into_\") that takes `self` with the wrong convention"
349 declare_clippy_lint! {
351 /// Checks for usage of `ok().expect(..)`.
353 /// ### Why is this bad?
354 /// Because you usually call `expect()` on the `Result`
355 /// directly to get a better error message.
357 /// ### Known problems
358 /// The error type needs to implement `Debug`
362 /// # let x = Ok::<_, ()>(());
363 /// x.ok().expect("why did I do this again?");
368 /// # let x = Ok::<_, ()>(());
369 /// x.expect("why did I do this again?");
371 #[clippy::version = "pre 1.29.0"]
374 "using `ok().expect()`, which gives worse error messages than calling `expect` directly on the Result"
377 declare_clippy_lint! {
379 /// Checks for `.err().expect()` calls on the `Result` type.
381 /// ### Why is this bad?
382 /// `.expect_err()` can be called directly to avoid the extra type conversion from `err()`.
386 /// let x: Result<u32, &str> = Ok(10);
387 /// x.err().expect("Testing err().expect()");
391 /// let x: Result<u32, &str> = Ok(10);
392 /// x.expect_err("Testing expect_err");
394 #[clippy::version = "1.62.0"]
397 r#"using `.err().expect("")` when `.expect_err("")` can be used"#
400 declare_clippy_lint! {
402 /// Checks for usages of `_.unwrap_or_else(Default::default)` on `Option` and
405 /// ### Why is this bad?
406 /// Readability, these can be written as `_.unwrap_or_default`, which is
407 /// simpler and more concise.
411 /// # let x = Some(1);
412 /// x.unwrap_or_else(Default::default);
413 /// x.unwrap_or_else(u32::default);
418 /// # let x = Some(1);
419 /// x.unwrap_or_default();
421 #[clippy::version = "1.56.0"]
422 pub UNWRAP_OR_ELSE_DEFAULT,
424 "using `.unwrap_or_else(Default::default)`, which is more succinctly expressed as `.unwrap_or_default()`"
427 declare_clippy_lint! {
429 /// Checks for usage of `option.map(_).unwrap_or(_)` or `option.map(_).unwrap_or_else(_)` or
430 /// `result.map(_).unwrap_or_else(_)`.
432 /// ### Why is this bad?
433 /// Readability, these can be written more concisely (resp.) as
434 /// `option.map_or(_, _)`, `option.map_or_else(_, _)` and `result.map_or_else(_, _)`.
436 /// ### Known problems
437 /// The order of the arguments is not in execution order
441 /// # let option = Some(1);
442 /// # let result: Result<usize, ()> = Ok(1);
443 /// # fn some_function(foo: ()) -> usize { 1 }
444 /// option.map(|a| a + 1).unwrap_or(0);
445 /// result.map(|a| a + 1).unwrap_or_else(some_function);
450 /// # let option = Some(1);
451 /// # let result: Result<usize, ()> = Ok(1);
452 /// # fn some_function(foo: ()) -> usize { 1 }
453 /// option.map_or(0, |a| a + 1);
454 /// result.map_or_else(some_function, |a| a + 1);
456 #[clippy::version = "1.45.0"]
459 "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)`"
462 declare_clippy_lint! {
464 /// Checks for usage of `_.map_or(None, _)`.
466 /// ### Why is this bad?
467 /// Readability, this can be written more concisely as
470 /// ### Known problems
471 /// The order of the arguments is not in execution order.
475 /// # let opt = Some(1);
476 /// opt.map_or(None, |a| Some(a + 1));
481 /// # let opt = Some(1);
482 /// opt.and_then(|a| Some(a + 1));
484 #[clippy::version = "pre 1.29.0"]
485 pub OPTION_MAP_OR_NONE,
487 "using `Option.map_or(None, f)`, which is more succinctly expressed as `and_then(f)`"
490 declare_clippy_lint! {
492 /// Checks for usage of `_.map_or(None, Some)`.
494 /// ### Why is this bad?
495 /// Readability, this can be written more concisely as
500 /// # let r: Result<u32, &str> = Ok(1);
501 /// assert_eq!(Some(1), r.map_or(None, Some));
506 /// # let r: Result<u32, &str> = Ok(1);
507 /// assert_eq!(Some(1), r.ok());
509 #[clippy::version = "1.44.0"]
510 pub RESULT_MAP_OR_INTO_OPTION,
512 "using `Result.map_or(None, Some)`, which is more succinctly expressed as `ok()`"
515 declare_clippy_lint! {
517 /// Checks for usage of `_.and_then(|x| Some(y))`, `_.and_then(|x| Ok(y))` or
518 /// `_.or_else(|x| Err(y))`.
520 /// ### Why is this bad?
521 /// Readability, this can be written more concisely as
522 /// `_.map(|x| y)` or `_.map_err(|x| y)`.
526 /// # fn opt() -> Option<&'static str> { Some("42") }
527 /// # fn res() -> Result<&'static str, &'static str> { Ok("42") }
528 /// let _ = opt().and_then(|s| Some(s.len()));
529 /// let _ = res().and_then(|s| if s.len() == 42 { Ok(10) } else { Ok(20) });
530 /// let _ = res().or_else(|s| if s.len() == 42 { Err(10) } else { Err(20) });
533 /// The correct use would be:
536 /// # fn opt() -> Option<&'static str> { Some("42") }
537 /// # fn res() -> Result<&'static str, &'static str> { Ok("42") }
538 /// let _ = opt().map(|s| s.len());
539 /// let _ = res().map(|s| if s.len() == 42 { 10 } else { 20 });
540 /// let _ = res().map_err(|s| if s.len() == 42 { 10 } else { 20 });
542 #[clippy::version = "1.45.0"]
543 pub BIND_INSTEAD_OF_MAP,
545 "using `Option.and_then(|x| Some(y))`, which is more succinctly expressed as `map(|x| y)`"
548 declare_clippy_lint! {
550 /// Checks for usage of `_.filter(_).next()`.
552 /// ### Why is this bad?
553 /// Readability, this can be written more concisely as
558 /// # let vec = vec![1];
559 /// vec.iter().filter(|x| **x == 0).next();
564 /// # let vec = vec![1];
565 /// vec.iter().find(|x| **x == 0);
567 #[clippy::version = "pre 1.29.0"]
570 "using `filter(p).next()`, which is more succinctly expressed as `.find(p)`"
573 declare_clippy_lint! {
575 /// Checks for usage of `_.skip_while(condition).next()`.
577 /// ### Why is this bad?
578 /// Readability, this can be written more concisely as
579 /// `_.find(!condition)`.
583 /// # let vec = vec![1];
584 /// vec.iter().skip_while(|x| **x == 0).next();
589 /// # let vec = vec![1];
590 /// vec.iter().find(|x| **x != 0);
592 #[clippy::version = "1.42.0"]
595 "using `skip_while(p).next()`, which is more succinctly expressed as `.find(!p)`"
598 declare_clippy_lint! {
600 /// Checks for usage of `_.map(_).flatten(_)` on `Iterator` and `Option`
602 /// ### Why is this bad?
603 /// Readability, this can be written more concisely as
604 /// `_.flat_map(_)` for `Iterator` or `_.and_then(_)` for `Option`
608 /// let vec = vec![vec![1]];
609 /// let opt = Some(5);
611 /// vec.iter().map(|x| x.iter()).flatten();
612 /// opt.map(|x| Some(x * 2)).flatten();
617 /// # let vec = vec![vec![1]];
618 /// # let opt = Some(5);
619 /// vec.iter().flat_map(|x| x.iter());
620 /// opt.and_then(|x| Some(x * 2));
622 #[clippy::version = "1.31.0"]
625 "using combinations of `flatten` and `map` which can usually be written as a single method call"
628 declare_clippy_lint! {
630 /// Checks for usage of `_.filter(_).map(_)` that can be written more simply
631 /// as `filter_map(_)`.
633 /// ### Why is this bad?
634 /// Redundant code in the `filter` and `map` operations is poor style and
639 /// # #![allow(unused)]
641 /// .filter(|n| n.checked_add(1).is_some())
642 /// .map(|n| n.checked_add(1).unwrap());
647 /// # #[allow(unused)]
648 /// (0_i32..10).filter_map(|n| n.checked_add(1));
650 #[clippy::version = "1.51.0"]
651 pub MANUAL_FILTER_MAP,
653 "using `_.filter(_).map(_)` in a way that can be written more simply as `filter_map(_)`"
656 declare_clippy_lint! {
658 /// Checks for usage of `_.find(_).map(_)` that can be written more simply
659 /// as `find_map(_)`.
661 /// ### Why is this bad?
662 /// Redundant code in the `find` and `map` operations is poor style and
668 /// .find(|n| n.checked_add(1).is_some())
669 /// .map(|n| n.checked_add(1).unwrap());
674 /// (0_i32..10).find_map(|n| n.checked_add(1));
676 #[clippy::version = "1.51.0"]
679 "using `_.find(_).map(_)` in a way that can be written more simply as `find_map(_)`"
682 declare_clippy_lint! {
684 /// Checks for usage of `_.filter_map(_).next()`.
686 /// ### Why is this bad?
687 /// Readability, this can be written more concisely as
692 /// (0..3).filter_map(|x| if x == 2 { Some(x) } else { None }).next();
694 /// Can be written as
697 /// (0..3).find_map(|x| if x == 2 { Some(x) } else { None });
699 #[clippy::version = "1.36.0"]
702 "using combination of `filter_map` and `next` which can usually be written as a single method call"
705 declare_clippy_lint! {
707 /// Checks for usage of `flat_map(|x| x)`.
709 /// ### Why is this bad?
710 /// Readability, this can be written more concisely by using `flatten`.
714 /// # let iter = vec![vec![0]].into_iter();
715 /// iter.flat_map(|x| x);
717 /// Can be written as
719 /// # let iter = vec![vec![0]].into_iter();
722 #[clippy::version = "1.39.0"]
723 pub FLAT_MAP_IDENTITY,
725 "call to `flat_map` where `flatten` is sufficient"
728 declare_clippy_lint! {
730 /// Checks for an iterator or string search (such as `find()`,
731 /// `position()`, or `rposition()`) followed by a call to `is_some()` or `is_none()`.
733 /// ### Why is this bad?
734 /// Readability, this can be written more concisely as:
735 /// * `_.any(_)`, or `_.contains(_)` for `is_some()`,
736 /// * `!_.any(_)`, or `!_.contains(_)` for `is_none()`.
740 /// # #![allow(unused)]
741 /// let vec = vec![1];
742 /// vec.iter().find(|x| **x == 0).is_some();
744 /// "hello world".find("world").is_none();
749 /// let vec = vec![1];
750 /// vec.iter().any(|x| *x == 0);
752 /// # #[allow(unused)]
753 /// !"hello world".contains("world");
755 #[clippy::version = "pre 1.29.0"]
758 "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()`)"
761 declare_clippy_lint! {
763 /// Checks for usage of `.chars().next()` on a `str` to check
764 /// if it starts with a given char.
766 /// ### Why is this bad?
767 /// Readability, this can be written more concisely as
768 /// `_.starts_with(_)`.
772 /// let name = "foo";
773 /// if name.chars().next() == Some('_') {};
778 /// let name = "foo";
779 /// if name.starts_with('_') {};
781 #[clippy::version = "pre 1.29.0"]
784 "using `.chars().next()` to check if a string starts with a char"
787 declare_clippy_lint! {
789 /// Checks for calls to `.or(foo(..))`, `.unwrap_or(foo(..))`,
790 /// etc., and suggests to use `or_else`, `unwrap_or_else`, etc., or
791 /// `unwrap_or_default` instead.
793 /// ### Why is this bad?
794 /// The function will always be called and potentially
795 /// allocate an object acting as the default.
797 /// ### Known problems
798 /// If the function has side-effects, not calling it will
799 /// change the semantic of the program, but you shouldn't rely on that anyway.
803 /// # let foo = Some(String::new());
804 /// foo.unwrap_or(String::new());
809 /// # let foo = Some(String::new());
810 /// foo.unwrap_or_else(String::new);
814 /// # let foo = Some(String::new());
815 /// foo.unwrap_or_default();
817 #[clippy::version = "pre 1.29.0"]
820 "using any `*or` method with a function call, which suggests `*or_else`"
823 declare_clippy_lint! {
825 /// Checks for `.or(…).unwrap()` calls to Options and Results.
827 /// ### Why is this bad?
828 /// You should use `.unwrap_or(…)` instead for clarity.
832 /// # let fallback = "fallback";
834 /// # type Error = &'static str;
835 /// # let result: Result<&str, Error> = Err("error");
836 /// let value = result.or::<Error>(Ok(fallback)).unwrap();
839 /// # let option: Option<&str> = None;
840 /// let value = option.or(Some(fallback)).unwrap();
844 /// # let fallback = "fallback";
846 /// # let result: Result<&str, &str> = Err("error");
847 /// let value = result.unwrap_or(fallback);
850 /// # let option: Option<&str> = None;
851 /// let value = option.unwrap_or(fallback);
853 #[clippy::version = "1.61.0"]
856 "checks for `.or(…).unwrap()` calls to Options and Results."
859 declare_clippy_lint! {
861 /// Checks for calls to `.expect(&format!(...))`, `.expect(foo(..))`,
862 /// etc., and suggests to use `unwrap_or_else` instead
864 /// ### Why is this bad?
865 /// The function will always be called.
867 /// ### Known problems
868 /// If the function has side-effects, not calling it will
869 /// change the semantics of the program, but you shouldn't rely on that anyway.
873 /// # let foo = Some(String::new());
874 /// # let err_code = "418";
875 /// # let err_msg = "I'm a teapot";
876 /// foo.expect(&format!("Err {}: {}", err_code, err_msg));
880 /// # let foo = Some(String::new());
881 /// foo.expect(format!("Err {}: {}", err_code, err_msg).as_str());
886 /// # let foo = Some(String::new());
887 /// # let err_code = "418";
888 /// # let err_msg = "I'm a teapot";
889 /// foo.unwrap_or_else(|| panic!("Err {}: {}", err_code, err_msg));
891 #[clippy::version = "pre 1.29.0"]
894 "using any `expect` method with a function call"
897 declare_clippy_lint! {
899 /// Checks for usage of `.clone()` on a `Copy` type.
901 /// ### Why is this bad?
902 /// The only reason `Copy` types implement `Clone` is for
903 /// generics, not for using the `clone` method on a concrete type.
909 #[clippy::version = "pre 1.29.0"]
912 "using `clone` on a `Copy` type"
915 declare_clippy_lint! {
917 /// Checks for usage of `.clone()` on a ref-counted pointer,
918 /// (`Rc`, `Arc`, `rc::Weak`, or `sync::Weak`), and suggests calling Clone via unified
919 /// function syntax instead (e.g., `Rc::clone(foo)`).
921 /// ### Why is this bad?
922 /// Calling '.clone()' on an Rc, Arc, or Weak
923 /// can obscure the fact that only the pointer is being cloned, not the underlying
928 /// # use std::rc::Rc;
929 /// let x = Rc::new(1);
936 /// # use std::rc::Rc;
937 /// # let x = Rc::new(1);
940 #[clippy::version = "pre 1.29.0"]
941 pub CLONE_ON_REF_PTR,
943 "using 'clone' on a ref-counted pointer"
946 declare_clippy_lint! {
948 /// Checks for usage of `.clone()` on an `&&T`.
950 /// ### Why is this bad?
951 /// Cloning an `&&T` copies the inner `&T`, instead of
952 /// cloning the underlying `T`.
959 /// let z = y.clone();
960 /// println!("{:p} {:p}", *y, z); // prints out the same pointer
963 #[clippy::version = "pre 1.29.0"]
964 pub CLONE_DOUBLE_REF,
966 "using `clone` on `&&T`"
969 declare_clippy_lint! {
971 /// Checks for usage of `.to_string()` on an `&&T` where
972 /// `T` implements `ToString` directly (like `&&str` or `&&String`).
974 /// ### Why is this bad?
975 /// This bypasses the specialized implementation of
976 /// `ToString` and instead goes through the more expensive string formatting
981 /// // Generic implementation for `T: Display` is used (slow)
982 /// ["foo", "bar"].iter().map(|s| s.to_string());
984 /// // OK, the specialized impl is used
985 /// ["foo", "bar"].iter().map(|&s| s.to_string());
987 #[clippy::version = "1.40.0"]
988 pub INEFFICIENT_TO_STRING,
990 "using `to_string` on `&&T` where `T: ToString`"
993 declare_clippy_lint! {
995 /// Checks for `new` not returning a type that contains `Self`.
997 /// ### Why is this bad?
998 /// As a convention, `new` methods are used to make a new
999 /// instance of a type.
1002 /// In an impl block:
1005 /// # struct NotAFoo;
1007 /// fn new() -> NotAFoo {
1015 /// struct Bar(Foo);
1017 /// // Bad. The type name must contain `Self`
1018 /// fn new() -> Bar {
1026 /// # struct FooError;
1028 /// // Good. Return type contains `Self`
1029 /// fn new() -> Result<Foo, FooError> {
1035 /// Or in a trait definition:
1037 /// pub trait Trait {
1038 /// // Bad. The type name must contain `Self`
1044 /// pub trait Trait {
1045 /// // Good. Return type contains `Self`
1046 /// fn new() -> Self;
1049 #[clippy::version = "pre 1.29.0"]
1050 pub NEW_RET_NO_SELF,
1052 "not returning type containing `Self` in a `new` method"
1055 declare_clippy_lint! {
1056 /// ### What it does
1057 /// Checks for string methods that receive a single-character
1058 /// `str` as an argument, e.g., `_.split("x")`.
1060 /// ### Why is this bad?
1061 /// Performing these methods using a `char` is faster than
1064 /// ### Known problems
1065 /// Does not catch multi-byte unicode characters.
1076 #[clippy::version = "pre 1.29.0"]
1077 pub SINGLE_CHAR_PATTERN,
1079 "using a single-character str where a char could be used, e.g., `_.split(\"x\")`"
1082 declare_clippy_lint! {
1083 /// ### What it does
1084 /// Checks for calling `.step_by(0)` on iterators which panics.
1086 /// ### Why is this bad?
1087 /// This very much looks like an oversight. Use `panic!()` instead if you
1088 /// actually intend to panic.
1091 /// ```rust,should_panic
1092 /// for x in (0..100).step_by(0) {
1096 #[clippy::version = "pre 1.29.0"]
1097 pub ITERATOR_STEP_BY_ZERO,
1099 "using `Iterator::step_by(0)`, which will panic at runtime"
1102 declare_clippy_lint! {
1103 /// ### What it does
1104 /// Checks for indirect collection of populated `Option`
1106 /// ### Why is this bad?
1107 /// `Option` is like a collection of 0-1 things, so `flatten`
1108 /// automatically does this without suspicious-looking `unwrap` calls.
1112 /// let _ = std::iter::empty::<Option<i32>>().filter(Option::is_some).map(Option::unwrap);
1116 /// let _ = std::iter::empty::<Option<i32>>().flatten();
1118 #[clippy::version = "1.53.0"]
1119 pub OPTION_FILTER_MAP,
1121 "filtering `Option` for `Some` then force-unwrapping, which can be one type-safe operation"
1124 declare_clippy_lint! {
1125 /// ### What it does
1126 /// Checks for the use of `iter.nth(0)`.
1128 /// ### Why is this bad?
1129 /// `iter.next()` is equivalent to
1130 /// `iter.nth(0)`, as they both consume the next element,
1131 /// but is more readable.
1135 /// # use std::collections::HashSet;
1136 /// # let mut s = HashSet::new();
1138 /// let x = s.iter().nth(0);
1143 /// # use std::collections::HashSet;
1144 /// # let mut s = HashSet::new();
1146 /// let x = s.iter().next();
1148 #[clippy::version = "1.42.0"]
1151 "replace `iter.nth(0)` with `iter.next()`"
1154 declare_clippy_lint! {
1155 /// ### What it does
1156 /// Checks for use of `.iter().nth()` (and the related
1157 /// `.iter_mut().nth()`) on standard library types with *O*(1) element access.
1159 /// ### Why is this bad?
1160 /// `.get()` and `.get_mut()` are more efficient and more
1165 /// let some_vec = vec![0, 1, 2, 3];
1166 /// let bad_vec = some_vec.iter().nth(3);
1167 /// let bad_slice = &some_vec[..].iter().nth(3);
1169 /// The correct use would be:
1171 /// let some_vec = vec![0, 1, 2, 3];
1172 /// let bad_vec = some_vec.get(3);
1173 /// let bad_slice = &some_vec[..].get(3);
1175 #[clippy::version = "pre 1.29.0"]
1178 "using `.iter().nth()` on a standard library type with O(1) element access"
1181 declare_clippy_lint! {
1182 /// ### What it does
1183 /// Checks for use of `.skip(x).next()` on iterators.
1185 /// ### Why is this bad?
1186 /// `.nth(x)` is cleaner
1190 /// let some_vec = vec![0, 1, 2, 3];
1191 /// let bad_vec = some_vec.iter().skip(3).next();
1192 /// let bad_slice = &some_vec[..].iter().skip(3).next();
1194 /// The correct use would be:
1196 /// let some_vec = vec![0, 1, 2, 3];
1197 /// let bad_vec = some_vec.iter().nth(3);
1198 /// let bad_slice = &some_vec[..].iter().nth(3);
1200 #[clippy::version = "pre 1.29.0"]
1203 "using `.skip(x).next()` on an iterator"
1206 declare_clippy_lint! {
1207 /// ### What it does
1208 /// Checks for use of `.drain(..)` on `Vec` and `VecDeque` for iteration.
1210 /// ### Why is this bad?
1211 /// `.into_iter()` is simpler with better performance.
1215 /// # use std::collections::HashSet;
1216 /// let mut foo = vec![0, 1, 2, 3];
1217 /// let bar: HashSet<usize> = foo.drain(..).collect();
1221 /// # use std::collections::HashSet;
1222 /// let foo = vec![0, 1, 2, 3];
1223 /// let bar: HashSet<usize> = foo.into_iter().collect();
1225 #[clippy::version = "1.61.0"]
1226 pub ITER_WITH_DRAIN,
1228 "replace `.drain(..)` with `.into_iter()`"
1231 declare_clippy_lint! {
1232 /// ### What it does
1233 /// Checks for using `x.get(x.len() - 1)` instead of
1236 /// ### Why is this bad?
1237 /// Using `x.last()` is easier to read and has the same
1240 /// Note that using `x[x.len() - 1]` is semantically different from
1241 /// `x.last()`. Indexing into the array will panic on out-of-bounds
1242 /// accesses, while `x.get()` and `x.last()` will return `None`.
1244 /// There is another lint (get_unwrap) that covers the case of using
1245 /// `x.get(index).unwrap()` instead of `x[index]`.
1249 /// let x = vec![2, 3, 5];
1250 /// let last_element = x.get(x.len() - 1);
1255 /// let x = vec![2, 3, 5];
1256 /// let last_element = x.last();
1258 #[clippy::version = "1.37.0"]
1259 pub GET_LAST_WITH_LEN,
1261 "Using `x.get(x.len() - 1)` when `x.last()` is correct and simpler"
1264 declare_clippy_lint! {
1265 /// ### What it does
1266 /// Checks for use of `.get().unwrap()` (or
1267 /// `.get_mut().unwrap`) on a standard library type which implements `Index`
1269 /// ### Why is this bad?
1270 /// Using the Index trait (`[]`) is more clear and more
1273 /// ### Known problems
1274 /// Not a replacement for error handling: Using either
1275 /// `.unwrap()` or the Index trait (`[]`) carries the risk of causing a `panic`
1276 /// if the value being accessed is `None`. If the use of `.get().unwrap()` is a
1277 /// temporary placeholder for dealing with the `Option` type, then this does
1278 /// not mitigate the need for error handling. If there is a chance that `.get()`
1279 /// will be `None` in your program, then it is advisable that the `None` case
1280 /// is handled in a future refactor instead of using `.unwrap()` or the Index
1285 /// let mut some_vec = vec![0, 1, 2, 3];
1286 /// let last = some_vec.get(3).unwrap();
1287 /// *some_vec.get_mut(0).unwrap() = 1;
1289 /// The correct use would be:
1291 /// let mut some_vec = vec![0, 1, 2, 3];
1292 /// let last = some_vec[3];
1293 /// some_vec[0] = 1;
1295 #[clippy::version = "pre 1.29.0"]
1298 "using `.get().unwrap()` or `.get_mut().unwrap()` when using `[]` would work instead"
1301 declare_clippy_lint! {
1302 /// ### What it does
1303 /// Checks for occurrences where one vector gets extended instead of append
1305 /// ### Why is this bad?
1306 /// Using `append` instead of `extend` is more concise and faster
1310 /// let mut a = vec![1, 2, 3];
1311 /// let mut b = vec![4, 5, 6];
1313 /// a.extend(b.drain(..));
1318 /// let mut a = vec![1, 2, 3];
1319 /// let mut b = vec![4, 5, 6];
1321 /// a.append(&mut b);
1323 #[clippy::version = "1.55.0"]
1324 pub EXTEND_WITH_DRAIN,
1326 "using vec.append(&mut vec) to move the full range of a vector to another"
1329 declare_clippy_lint! {
1330 /// ### What it does
1331 /// Checks for the use of `.extend(s.chars())` where s is a
1332 /// `&str` or `String`.
1334 /// ### Why is this bad?
1335 /// `.push_str(s)` is clearer
1339 /// let abc = "abc";
1340 /// let def = String::from("def");
1341 /// let mut s = String::new();
1342 /// s.extend(abc.chars());
1343 /// s.extend(def.chars());
1345 /// The correct use would be:
1347 /// let abc = "abc";
1348 /// let def = String::from("def");
1349 /// let mut s = String::new();
1350 /// s.push_str(abc);
1351 /// s.push_str(&def);
1353 #[clippy::version = "pre 1.29.0"]
1354 pub STRING_EXTEND_CHARS,
1356 "using `x.extend(s.chars())` where s is a `&str` or `String`"
1359 declare_clippy_lint! {
1360 /// ### What it does
1361 /// Checks for the use of `.cloned().collect()` on slice to
1364 /// ### Why is this bad?
1365 /// `.to_vec()` is clearer
1369 /// let s = [1, 2, 3, 4, 5];
1370 /// let s2: Vec<isize> = s[..].iter().cloned().collect();
1372 /// The better use would be:
1374 /// let s = [1, 2, 3, 4, 5];
1375 /// let s2: Vec<isize> = s.to_vec();
1377 #[clippy::version = "pre 1.29.0"]
1378 pub ITER_CLONED_COLLECT,
1380 "using `.cloned().collect()` on slice to create a `Vec`"
1383 declare_clippy_lint! {
1384 /// ### What it does
1385 /// Checks for usage of `_.chars().last()` or
1386 /// `_.chars().next_back()` on a `str` to check if it ends with a given char.
1388 /// ### Why is this bad?
1389 /// Readability, this can be written more concisely as
1390 /// `_.ends_with(_)`.
1394 /// # let name = "_";
1395 /// name.chars().last() == Some('_') || name.chars().next_back() == Some('-');
1400 /// # let name = "_";
1401 /// name.ends_with('_') || name.ends_with('-');
1403 #[clippy::version = "pre 1.29.0"]
1406 "using `.chars().last()` or `.chars().next_back()` to check if a string ends with a char"
1409 declare_clippy_lint! {
1410 /// ### What it does
1411 /// Checks for usage of `.as_ref()` or `.as_mut()` where the
1412 /// types before and after the call are the same.
1414 /// ### Why is this bad?
1415 /// The call is unnecessary.
1419 /// # fn do_stuff(x: &[i32]) {}
1420 /// let x: &[i32] = &[1, 2, 3, 4, 5];
1421 /// do_stuff(x.as_ref());
1423 /// The correct use would be:
1425 /// # fn do_stuff(x: &[i32]) {}
1426 /// let x: &[i32] = &[1, 2, 3, 4, 5];
1429 #[clippy::version = "pre 1.29.0"]
1432 "using `as_ref` where the types before and after the call are the same"
1435 declare_clippy_lint! {
1436 /// ### What it does
1437 /// Checks for using `fold` when a more succinct alternative exists.
1438 /// Specifically, this checks for `fold`s which could be replaced by `any`, `all`,
1439 /// `sum` or `product`.
1441 /// ### Why is this bad?
1446 /// # #[allow(unused)]
1447 /// (0..3).fold(false, |acc, x| acc || x > 2);
1452 /// (0..3).any(|x| x > 2);
1454 #[clippy::version = "pre 1.29.0"]
1455 pub UNNECESSARY_FOLD,
1457 "using `fold` when a more succinct alternative exists"
1460 declare_clippy_lint! {
1461 /// ### What it does
1462 /// Checks for `filter_map` calls that could be replaced by `filter` or `map`.
1463 /// More specifically it checks if the closure provided is only performing one of the
1464 /// filter or map operations and suggests the appropriate option.
1466 /// ### Why is this bad?
1467 /// Complexity. The intent is also clearer if only a single
1468 /// operation is being performed.
1472 /// let _ = (0..3).filter_map(|x| if x > 2 { Some(x) } else { None });
1474 /// // As there is no transformation of the argument this could be written as:
1475 /// let _ = (0..3).filter(|&x| x > 2);
1479 /// let _ = (0..4).filter_map(|x| Some(x + 1));
1481 /// // As there is no conditional check on the argument this could be written as:
1482 /// let _ = (0..4).map(|x| x + 1);
1484 #[clippy::version = "1.31.0"]
1485 pub UNNECESSARY_FILTER_MAP,
1487 "using `filter_map` when a more succinct alternative exists"
1490 declare_clippy_lint! {
1491 /// ### What it does
1492 /// Checks for `find_map` calls that could be replaced by `find` or `map`. More
1493 /// specifically it checks if the closure provided is only performing one of the
1494 /// find or map operations and suggests the appropriate option.
1496 /// ### Why is this bad?
1497 /// Complexity. The intent is also clearer if only a single
1498 /// operation is being performed.
1502 /// let _ = (0..3).find_map(|x| if x > 2 { Some(x) } else { None });
1504 /// // As there is no transformation of the argument this could be written as:
1505 /// let _ = (0..3).find(|&x| x > 2);
1509 /// let _ = (0..4).find_map(|x| Some(x + 1));
1511 /// // As there is no conditional check on the argument this could be written as:
1512 /// let _ = (0..4).map(|x| x + 1).next();
1514 #[clippy::version = "1.61.0"]
1515 pub UNNECESSARY_FIND_MAP,
1517 "using `find_map` when a more succinct alternative exists"
1520 declare_clippy_lint! {
1521 /// ### What it does
1522 /// Checks for `into_iter` calls on references which should be replaced by `iter`
1525 /// ### Why is this bad?
1526 /// Readability. Calling `into_iter` on a reference will not move out its
1527 /// content into the resulting iterator, which is confusing. It is better just call `iter` or
1528 /// `iter_mut` directly.
1532 /// # let vec = vec![3, 4, 5];
1533 /// (&vec).into_iter();
1538 /// # let vec = vec![3, 4, 5];
1541 #[clippy::version = "1.32.0"]
1542 pub INTO_ITER_ON_REF,
1544 "using `.into_iter()` on a reference"
1547 declare_clippy_lint! {
1548 /// ### What it does
1549 /// Checks for calls to `map` followed by a `count`.
1551 /// ### Why is this bad?
1552 /// It looks suspicious. Maybe `map` was confused with `filter`.
1553 /// If the `map` call is intentional, this should be rewritten
1554 /// using `inspect`. Or, if you intend to drive the iterator to
1555 /// completion, you can just use `for_each` instead.
1559 /// let _ = (0..3).map(|x| x + 2).count();
1561 #[clippy::version = "1.39.0"]
1564 "suspicious usage of map"
1567 declare_clippy_lint! {
1568 /// ### What it does
1569 /// Checks for `MaybeUninit::uninit().assume_init()`.
1571 /// ### Why is this bad?
1572 /// For most types, this is undefined behavior.
1574 /// ### Known problems
1575 /// For now, we accept empty tuples and tuples / arrays
1576 /// of `MaybeUninit`. There may be other types that allow uninitialized
1577 /// data, but those are not yet rigorously defined.
1581 /// // Beware the UB
1582 /// use std::mem::MaybeUninit;
1584 /// let _: usize = unsafe { MaybeUninit::uninit().assume_init() };
1587 /// Note that the following is OK:
1590 /// use std::mem::MaybeUninit;
1592 /// let _: [MaybeUninit<bool>; 5] = unsafe {
1593 /// MaybeUninit::uninit().assume_init()
1596 #[clippy::version = "1.39.0"]
1597 pub UNINIT_ASSUMED_INIT,
1599 "`MaybeUninit::uninit().assume_init()`"
1602 declare_clippy_lint! {
1603 /// ### What it does
1604 /// Checks for `.checked_add/sub(x).unwrap_or(MAX/MIN)`.
1606 /// ### Why is this bad?
1607 /// These can be written simply with `saturating_add/sub` methods.
1611 /// # let y: u32 = 0;
1612 /// # let x: u32 = 100;
1613 /// let add = x.checked_add(y).unwrap_or(u32::MAX);
1614 /// let sub = x.checked_sub(y).unwrap_or(u32::MIN);
1617 /// can be written using dedicated methods for saturating addition/subtraction as:
1620 /// # let y: u32 = 0;
1621 /// # let x: u32 = 100;
1622 /// let add = x.saturating_add(y);
1623 /// let sub = x.saturating_sub(y);
1625 #[clippy::version = "1.39.0"]
1626 pub MANUAL_SATURATING_ARITHMETIC,
1628 "`.checked_add/sub(x).unwrap_or(MAX/MIN)`"
1631 declare_clippy_lint! {
1632 /// ### What it does
1633 /// Checks for `offset(_)`, `wrapping_`{`add`, `sub`}, etc. on raw pointers to
1634 /// zero-sized types
1636 /// ### Why is this bad?
1637 /// This is a no-op, and likely unintended
1641 /// unsafe { (&() as *const ()).offset(1) };
1643 #[clippy::version = "1.41.0"]
1646 "Check for offset calculations on raw pointers to zero-sized types"
1649 declare_clippy_lint! {
1650 /// ### What it does
1651 /// Checks for `FileType::is_file()`.
1653 /// ### Why is this bad?
1654 /// When people testing a file type with `FileType::is_file`
1655 /// they are testing whether a path is something they can get bytes from. But
1656 /// `is_file` doesn't cover special file types in unix-like systems, and doesn't cover
1657 /// symlink in windows. Using `!FileType::is_dir()` is a better way to that intention.
1662 /// let metadata = std::fs::metadata("foo.txt")?;
1663 /// let filetype = metadata.file_type();
1665 /// if filetype.is_file() {
1668 /// # Ok::<_, std::io::Error>(())
1672 /// should be written as:
1676 /// let metadata = std::fs::metadata("foo.txt")?;
1677 /// let filetype = metadata.file_type();
1679 /// if !filetype.is_dir() {
1682 /// # Ok::<_, std::io::Error>(())
1685 #[clippy::version = "1.42.0"]
1686 pub FILETYPE_IS_FILE,
1688 "`FileType::is_file` is not recommended to test for readable file type"
1691 declare_clippy_lint! {
1692 /// ### What it does
1693 /// Checks for usage of `_.as_ref().map(Deref::deref)` or it's aliases (such as String::as_str).
1695 /// ### Why is this bad?
1696 /// Readability, this can be written more concisely as
1701 /// # let opt = Some("".to_string());
1702 /// opt.as_ref().map(String::as_str)
1705 /// Can be written as
1707 /// # let opt = Some("".to_string());
1711 #[clippy::version = "1.42.0"]
1712 pub OPTION_AS_REF_DEREF,
1714 "using `as_ref().map(Deref::deref)`, which is more succinctly expressed as `as_deref()`"
1717 declare_clippy_lint! {
1718 /// ### What it does
1719 /// Checks for usage of `iter().next()` on a Slice or an Array
1721 /// ### Why is this bad?
1722 /// These can be shortened into `.get()`
1726 /// # let a = [1, 2, 3];
1727 /// # let b = vec![1, 2, 3];
1728 /// a[2..].iter().next();
1729 /// b.iter().next();
1731 /// should be written as:
1733 /// # let a = [1, 2, 3];
1734 /// # let b = vec![1, 2, 3];
1738 #[clippy::version = "1.46.0"]
1739 pub ITER_NEXT_SLICE,
1741 "using `.iter().next()` on a sliced array, which can be shortened to just `.get()`"
1744 declare_clippy_lint! {
1745 /// ### What it does
1746 /// Warns when using `push_str`/`insert_str` with a single-character string literal
1747 /// where `push`/`insert` with a `char` would work fine.
1749 /// ### Why is this bad?
1750 /// It's less clear that we are pushing a single character.
1754 /// # let mut string = String::new();
1755 /// string.insert_str(0, "R");
1756 /// string.push_str("R");
1761 /// # let mut string = String::new();
1762 /// string.insert(0, 'R');
1763 /// string.push('R');
1765 #[clippy::version = "1.49.0"]
1766 pub SINGLE_CHAR_ADD_STR,
1768 "`push_str()` or `insert_str()` used with a single-character string literal as parameter"
1771 declare_clippy_lint! {
1772 /// ### What it does
1773 /// As the counterpart to `or_fun_call`, this lint looks for unnecessary
1774 /// lazily evaluated closures on `Option` and `Result`.
1776 /// This lint suggests changing the following functions, when eager evaluation results in
1778 /// - `unwrap_or_else` to `unwrap_or`
1779 /// - `and_then` to `and`
1780 /// - `or_else` to `or`
1781 /// - `get_or_insert_with` to `get_or_insert`
1782 /// - `ok_or_else` to `ok_or`
1784 /// ### Why is this bad?
1785 /// Using eager evaluation is shorter and simpler in some cases.
1787 /// ### Known problems
1788 /// It is possible, but not recommended for `Deref` and `Index` to have
1789 /// side effects. Eagerly evaluating them can change the semantics of the program.
1793 /// // example code where clippy issues a warning
1794 /// let opt: Option<u32> = None;
1796 /// opt.unwrap_or_else(|| 42);
1800 /// let opt: Option<u32> = None;
1802 /// opt.unwrap_or(42);
1804 #[clippy::version = "1.48.0"]
1805 pub UNNECESSARY_LAZY_EVALUATIONS,
1807 "using unnecessary lazy evaluation, which can be replaced with simpler eager evaluation"
1810 declare_clippy_lint! {
1811 /// ### What it does
1812 /// Checks for usage of `_.map(_).collect::<Result<(), _>()`.
1814 /// ### Why is this bad?
1815 /// Using `try_for_each` instead is more readable and idiomatic.
1819 /// (0..3).map(|t| Err(t)).collect::<Result<(), _>>();
1823 /// (0..3).try_for_each(|t| Err(t));
1825 #[clippy::version = "1.49.0"]
1826 pub MAP_COLLECT_RESULT_UNIT,
1828 "using `.map(_).collect::<Result<(),_>()`, which can be replaced with `try_for_each`"
1831 declare_clippy_lint! {
1832 /// ### What it does
1833 /// Checks for `from_iter()` function calls on types that implement the `FromIterator`
1836 /// ### Why is this bad?
1837 /// It is recommended style to use collect. See
1838 /// [FromIterator documentation](https://doc.rust-lang.org/std/iter/trait.FromIterator.html)
1842 /// let five_fives = std::iter::repeat(5).take(5);
1844 /// let v = Vec::from_iter(five_fives);
1846 /// assert_eq!(v, vec![5, 5, 5, 5, 5]);
1850 /// let five_fives = std::iter::repeat(5).take(5);
1852 /// let v: Vec<i32> = five_fives.collect();
1854 /// assert_eq!(v, vec![5, 5, 5, 5, 5]);
1856 #[clippy::version = "1.49.0"]
1857 pub FROM_ITER_INSTEAD_OF_COLLECT,
1859 "use `.collect()` instead of `::from_iter()`"
1862 declare_clippy_lint! {
1863 /// ### What it does
1864 /// Checks for usage of `inspect().for_each()`.
1866 /// ### Why is this bad?
1867 /// It is the same as performing the computation
1868 /// inside `inspect` at the beginning of the closure in `for_each`.
1872 /// [1,2,3,4,5].iter()
1873 /// .inspect(|&x| println!("inspect the number: {}", x))
1874 /// .for_each(|&x| {
1875 /// assert!(x >= 0);
1878 /// Can be written as
1880 /// [1,2,3,4,5].iter()
1881 /// .for_each(|&x| {
1882 /// println!("inspect the number: {}", x);
1883 /// assert!(x >= 0);
1886 #[clippy::version = "1.51.0"]
1887 pub INSPECT_FOR_EACH,
1889 "using `.inspect().for_each()`, which can be replaced with `.for_each()`"
1892 declare_clippy_lint! {
1893 /// ### What it does
1894 /// Checks for usage of `filter_map(|x| x)`.
1896 /// ### Why is this bad?
1897 /// Readability, this can be written more concisely by using `flatten`.
1901 /// # let iter = vec![Some(1)].into_iter();
1902 /// iter.filter_map(|x| x);
1906 /// # let iter = vec![Some(1)].into_iter();
1909 #[clippy::version = "1.52.0"]
1910 pub FILTER_MAP_IDENTITY,
1912 "call to `filter_map` where `flatten` is sufficient"
1915 declare_clippy_lint! {
1916 /// ### What it does
1917 /// Checks for instances of `map(f)` where `f` is the identity function.
1919 /// ### Why is this bad?
1920 /// It can be written more concisely without the call to `map`.
1924 /// let x = [1, 2, 3];
1925 /// let y: Vec<_> = x.iter().map(|x| x).map(|x| 2*x).collect();
1929 /// let x = [1, 2, 3];
1930 /// let y: Vec<_> = x.iter().map(|x| 2*x).collect();
1932 #[clippy::version = "1.47.0"]
1935 "using iterator.map(|x| x)"
1938 declare_clippy_lint! {
1939 /// ### What it does
1940 /// Checks for the use of `.bytes().nth()`.
1942 /// ### Why is this bad?
1943 /// `.as_bytes().get()` is more efficient and more
1948 /// # #[allow(unused)]
1949 /// "Hello".bytes().nth(3);
1954 /// # #[allow(unused)]
1955 /// "Hello".as_bytes().get(3);
1957 #[clippy::version = "1.52.0"]
1960 "replace `.bytes().nth()` with `.as_bytes().get()`"
1963 declare_clippy_lint! {
1964 /// ### What it does
1965 /// Checks for the usage of `_.to_owned()`, `vec.to_vec()`, or similar when calling `_.clone()` would be clearer.
1967 /// ### Why is this bad?
1968 /// These methods do the same thing as `_.clone()` but may be confusing as
1969 /// to why we are calling `to_vec` on something that is already a `Vec` or calling `to_owned` on something that is already owned.
1973 /// let a = vec![1, 2, 3];
1974 /// let b = a.to_vec();
1975 /// let c = a.to_owned();
1979 /// let a = vec![1, 2, 3];
1980 /// let b = a.clone();
1981 /// let c = a.clone();
1983 #[clippy::version = "1.52.0"]
1986 "implicitly cloning a value by invoking a function on its dereferenced type"
1989 declare_clippy_lint! {
1990 /// ### What it does
1991 /// Checks for the use of `.iter().count()`.
1993 /// ### Why is this bad?
1994 /// `.len()` is more efficient and more
1999 /// # #![allow(unused)]
2000 /// let some_vec = vec![0, 1, 2, 3];
2002 /// some_vec.iter().count();
2003 /// &some_vec[..].iter().count();
2008 /// let some_vec = vec![0, 1, 2, 3];
2011 /// &some_vec[..].len();
2013 #[clippy::version = "1.52.0"]
2016 "replace `.iter().count()` with `.len()`"
2019 declare_clippy_lint! {
2020 /// ### What it does
2021 /// Checks for calls to [`splitn`]
2022 /// (https://doc.rust-lang.org/std/primitive.str.html#method.splitn) and
2023 /// related functions with either zero or one splits.
2025 /// ### Why is this bad?
2026 /// These calls don't actually split the value and are
2027 /// likely to be intended as a different number.
2032 /// for x in s.splitn(1, ":") {
2040 /// for x in s.splitn(2, ":") {
2044 #[clippy::version = "1.54.0"]
2045 pub SUSPICIOUS_SPLITN,
2047 "checks for `.splitn(0, ..)` and `.splitn(1, ..)`"
2050 declare_clippy_lint! {
2051 /// ### What it does
2052 /// Checks for manual implementations of `str::repeat`
2054 /// ### Why is this bad?
2055 /// These are both harder to read, as well as less performant.
2059 /// let x: String = std::iter::repeat('x').take(10).collect();
2064 /// let x: String = "x".repeat(10);
2066 #[clippy::version = "1.54.0"]
2067 pub MANUAL_STR_REPEAT,
2069 "manual implementation of `str::repeat`"
2072 declare_clippy_lint! {
2073 /// ### What it does
2074 /// Checks for usages of `str::splitn(2, _)`
2076 /// ### Why is this bad?
2077 /// `split_once` is both clearer in intent and slightly more efficient.
2081 /// let s = "key=value=add";
2082 /// let (key, value) = s.splitn(2, '=').next_tuple()?;
2083 /// let value = s.splitn(2, '=').nth(1)?;
2085 /// let mut parts = s.splitn(2, '=');
2086 /// let key = parts.next()?;
2087 /// let value = parts.next()?;
2092 /// let s = "key=value=add";
2093 /// let (key, value) = s.split_once('=')?;
2094 /// let value = s.split_once('=')?.1;
2096 /// let (key, value) = s.split_once('=')?;
2100 /// The multiple statement variant currently only detects `iter.next()?`/`iter.next().unwrap()`
2101 /// in two separate `let` statements that immediately follow the `splitn()`
2102 #[clippy::version = "1.57.0"]
2103 pub MANUAL_SPLIT_ONCE,
2105 "replace `.splitn(2, pat)` with `.split_once(pat)`"
2108 declare_clippy_lint! {
2109 /// ### What it does
2110 /// Checks for usages of `str::splitn` (or `str::rsplitn`) where using `str::split` would be the same.
2111 /// ### Why is this bad?
2112 /// The function `split` is simpler and there is no performance difference in these cases, considering
2113 /// that both functions return a lazy iterator.
2116 /// let str = "key=value=add";
2117 /// let _ = str.splitn(3, '=').next().unwrap();
2122 /// let str = "key=value=add";
2123 /// let _ = str.split('=').next().unwrap();
2125 #[clippy::version = "1.59.0"]
2126 pub NEEDLESS_SPLITN,
2128 "usages of `str::splitn` that can be replaced with `str::split`"
2131 declare_clippy_lint! {
2132 /// ### What it does
2133 /// Checks for unnecessary calls to [`ToOwned::to_owned`](https://doc.rust-lang.org/std/borrow/trait.ToOwned.html#tymethod.to_owned)
2134 /// and other `to_owned`-like functions.
2136 /// ### Why is this bad?
2137 /// The unnecessary calls result in useless allocations.
2139 /// ### Known problems
2140 /// `unnecessary_to_owned` can falsely trigger if `IntoIterator::into_iter` is applied to an
2141 /// owned copy of a resource and the resource is later used mutably. See
2142 /// [#8148](https://github.com/rust-lang/rust-clippy/issues/8148).
2146 /// let path = std::path::Path::new("x");
2147 /// foo(&path.to_string_lossy().to_string());
2148 /// fn foo(s: &str) {}
2152 /// let path = std::path::Path::new("x");
2153 /// foo(&path.to_string_lossy());
2154 /// fn foo(s: &str) {}
2156 #[clippy::version = "1.59.0"]
2157 pub UNNECESSARY_TO_OWNED,
2159 "unnecessary calls to `to_owned`-like functions"
2162 declare_clippy_lint! {
2163 /// ### What it does
2164 /// Checks for use of `.collect::<Vec<String>>().join("")` on iterators.
2166 /// ### Why is this bad?
2167 /// `.collect::<String>()` is more concise and might be more performant
2171 /// let vector = vec!["hello", "world"];
2172 /// let output = vector.iter().map(|item| item.to_uppercase()).collect::<Vec<String>>().join("");
2173 /// println!("{}", output);
2175 /// The correct use would be:
2177 /// let vector = vec!["hello", "world"];
2178 /// let output = vector.iter().map(|item| item.to_uppercase()).collect::<String>();
2179 /// println!("{}", output);
2181 /// ### Known problems
2182 /// While `.collect::<String>()` is sometimes more performant, there are cases where
2183 /// using `.collect::<String>()` over `.collect::<Vec<String>>().join("")`
2184 /// will prevent loop unrolling and will result in a negative performance impact.
2186 /// Additionally, differences have been observed between aarch64 and x86_64 assembly output,
2187 /// with aarch64 tending to producing faster assembly in more cases when using `.collect::<String>()`
2188 #[clippy::version = "1.61.0"]
2189 pub UNNECESSARY_JOIN,
2191 "using `.collect::<Vec<String>>().join(\"\")` on an iterator"
2194 declare_clippy_lint! {
2195 /// ### What it does
2196 /// Checks for no-op uses of `Option::{as_deref, as_deref_mut}`,
2197 /// for example, `Option<&T>::as_deref()` returns the same type.
2199 /// ### Why is this bad?
2200 /// Redundant code and improving readability.
2204 /// let a = Some(&1);
2205 /// let b = a.as_deref(); // goes from Option<&i32> to Option<&i32>
2210 /// let a = Some(&1);
2213 #[clippy::version = "1.57.0"]
2214 pub NEEDLESS_OPTION_AS_DEREF,
2216 "no-op use of `deref` or `deref_mut` method to `Option`."
2219 declare_clippy_lint! {
2220 /// ### What it does
2221 /// Finds usages of [`char::is_digit`](https://doc.rust-lang.org/stable/std/primitive.char.html#method.is_digit) that
2222 /// can be replaced with [`is_ascii_digit`](https://doc.rust-lang.org/stable/std/primitive.char.html#method.is_ascii_digit) or
2223 /// [`is_ascii_hexdigit`](https://doc.rust-lang.org/stable/std/primitive.char.html#method.is_ascii_hexdigit).
2225 /// ### Why is this bad?
2226 /// `is_digit(..)` is slower and requires specifying the radix.
2230 /// let c: char = '6';
2236 /// let c: char = '6';
2237 /// c.is_ascii_digit();
2238 /// c.is_ascii_hexdigit();
2240 #[clippy::version = "1.62.0"]
2241 pub IS_DIGIT_ASCII_RADIX,
2243 "use of `char::is_digit(..)` with literal radix of 10 or 16"
2246 declare_clippy_lint! {
2247 /// ### What it does
2248 /// Checks for calling `take` function after `as_ref`.
2250 /// ### Why is this bad?
2251 /// Redundant code. `take` writes `None` to its argument.
2252 /// In this case the modification is useless as it's a temporary that cannot be read from afterwards.
2256 /// let x = Some(3);
2257 /// x.as_ref().take();
2261 /// let x = Some(3);
2264 #[clippy::version = "1.62.0"]
2265 pub NEEDLESS_OPTION_TAKE,
2267 "using `.as_ref().take()` on a temporary value"
2270 declare_clippy_lint! {
2271 /// ### What it does
2272 /// Checks for `replace` statements which have no effect.
2274 /// ### Why is this bad?
2275 /// It's either a mistake or confusing.
2279 /// "1234".replace("12", "12");
2280 /// "1234".replacen("12", "12", 1);
2282 #[clippy::version = "1.63.0"]
2283 pub NO_EFFECT_REPLACE,
2285 "replace with no effect"
2288 declare_clippy_lint! {
2289 /// ### What it does
2290 /// Checks for usages of `.then_some(..).unwrap_or(..)`
2292 /// ### Why is this bad?
2293 /// This can be written more clearly with `if .. else ..`
2296 /// This lint currently only looks for usages of
2297 /// `.then_some(..).unwrap_or(..)`, but will be expanded
2298 /// to account for similar patterns.
2303 /// x.then_some("a").unwrap_or("b");
2308 /// if x { "a" } else { "b" };
2310 #[clippy::version = "1.64.0"]
2311 pub OBFUSCATED_IF_ELSE,
2313 "use of `.then_some(..).unwrap_or(..)` can be written \
2314 more clearly with `if .. else ..`"
2317 declare_clippy_lint! {
2318 /// ### What it does
2320 /// Checks for calls to `iter`, `iter_mut` or `into_iter` on collections containing a single item
2322 /// ### Why is this bad?
2324 /// It is simpler to use the once function from the standard library:
2329 /// let a = [123].iter();
2330 /// let b = Some(123).into_iter();
2335 /// let a = iter::once(&123);
2336 /// let b = iter::once(123);
2339 /// ### Known problems
2341 /// The type of the resulting iterator might become incompatible with its usage
2342 #[clippy::version = "1.64.0"]
2343 pub ITER_ON_SINGLE_ITEMS,
2345 "Iterator for array of length 1"
2348 declare_clippy_lint! {
2349 /// ### What it does
2351 /// Checks for calls to `iter`, `iter_mut` or `into_iter` on empty collections
2353 /// ### Why is this bad?
2355 /// It is simpler to use the empty function from the standard library:
2360 /// use std::{slice, option};
2361 /// let a: slice::Iter<i32> = [].iter();
2362 /// let f: option::IntoIter<i32> = None.into_iter();
2367 /// let a: iter::Empty<i32> = iter::empty();
2368 /// let b: iter::Empty<i32> = iter::empty();
2371 /// ### Known problems
2373 /// The type of the resulting iterator might become incompatible with its usage
2374 #[clippy::version = "1.64.0"]
2375 pub ITER_ON_EMPTY_COLLECTIONS,
2377 "Iterator for empty array"
2380 declare_clippy_lint! {
2381 /// ### What it does
2382 /// Checks for naive byte counts
2384 /// ### Why is this bad?
2385 /// The [`bytecount`](https://crates.io/crates/bytecount)
2386 /// crate has methods to count your bytes faster, especially for large slices.
2388 /// ### Known problems
2389 /// If you have predominantly small slices, the
2390 /// `bytecount::count(..)` method may actually be slower. However, if you can
2391 /// ensure that less than 2³²-1 matches arise, the `naive_count_32(..)` can be
2392 /// faster in those cases.
2396 /// # let vec = vec![1_u8];
2397 /// let count = vec.iter().filter(|x| **x == 0u8).count();
2402 /// # let vec = vec![1_u8];
2403 /// let count = bytecount::count(&vec, 0u8);
2405 #[clippy::version = "pre 1.29.0"]
2406 pub NAIVE_BYTECOUNT,
2408 "use of naive `<slice>.filter(|&x| x == y).count()` to count byte values"
2411 declare_clippy_lint! {
2412 /// ### What it does
2413 /// It checks for `str::bytes().count()` and suggests replacing it with
2416 /// ### Why is this bad?
2417 /// `str::bytes().count()` is longer and may not be as performant as using
2422 /// "hello".bytes().count();
2423 /// String::from("hello").bytes().count();
2428 /// String::from("hello").len();
2430 #[clippy::version = "1.62.0"]
2431 pub BYTES_COUNT_TO_LEN,
2433 "Using `bytes().count()` when `len()` performs the same functionality"
2436 declare_clippy_lint! {
2437 /// ### What it does
2438 /// Checks for calls to `ends_with` with possible file extensions
2439 /// and suggests to use a case-insensitive approach instead.
2441 /// ### Why is this bad?
2442 /// `ends_with` is case-sensitive and may not detect files with a valid extension.
2446 /// fn is_rust_file(filename: &str) -> bool {
2447 /// filename.ends_with(".rs")
2452 /// fn is_rust_file(filename: &str) -> bool {
2453 /// let filename = std::path::Path::new(filename);
2454 /// filename.extension()
2455 /// .map_or(false, |ext| ext.eq_ignore_ascii_case("rs"))
2458 #[clippy::version = "1.51.0"]
2459 pub CASE_SENSITIVE_FILE_EXTENSION_COMPARISONS,
2461 "Checks for calls to ends_with with case-sensitive file extensions"
2464 declare_clippy_lint! {
2465 /// ### What it does
2466 /// Checks for using `x.get(0)` instead of
2469 /// ### Why is this bad?
2470 /// Using `x.first()` is easier to read and has the same
2475 /// let x = vec![2, 3, 5];
2476 /// let first_element = x.get(0);
2481 /// let x = vec![2, 3, 5];
2482 /// let first_element = x.first();
2484 #[clippy::version = "1.63.0"]
2487 "Using `x.get(0)` when `x.first()` is simpler"
2490 declare_clippy_lint! {
2491 /// ### What it does
2493 /// Finds patterns that reimplement `Option::ok_or`.
2495 /// ### Why is this bad?
2497 /// Concise code helps focusing on behavior instead of boilerplate.
2501 /// let foo: Option<i32> = None;
2502 /// foo.map_or(Err("error"), |v| Ok(v));
2507 /// let foo: Option<i32> = None;
2508 /// foo.ok_or("error");
2510 #[clippy::version = "1.49.0"]
2513 "finds patterns that can be encoded more concisely with `Option::ok_or`"
2516 declare_clippy_lint! {
2517 /// ### What it does
2518 /// Checks for usage of `map(|x| x.clone())` or
2519 /// dereferencing closures for `Copy` types, on `Iterator` or `Option`,
2520 /// and suggests `cloned()` or `copied()` instead
2522 /// ### Why is this bad?
2523 /// Readability, this can be written more concisely
2527 /// let x = vec![42, 43];
2528 /// let y = x.iter();
2529 /// let z = y.map(|i| *i);
2532 /// The correct use would be:
2535 /// let x = vec![42, 43];
2536 /// let y = x.iter();
2537 /// let z = y.cloned();
2539 #[clippy::version = "pre 1.29.0"]
2542 "using `iterator.map(|x| x.clone())`, or dereferencing closures for `Copy` types"
2545 declare_clippy_lint! {
2546 /// ### What it does
2547 /// Checks for instances of `map_err(|_| Some::Enum)`
2549 /// ### Why is this bad?
2550 /// This `map_err` throws away the original error rather than allowing the enum to contain and report the cause of the error
2557 /// #[derive(Debug)]
2563 /// impl fmt::Display for Error {
2564 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2566 /// Error::Indivisible => write!(f, "could not divide input by three"),
2567 /// Error::Remainder(remainder) => write!(
2569 /// "input is not divisible by three, remainder = {}",
2576 /// impl std::error::Error for Error {}
2578 /// fn divisible_by_3(input: &str) -> Result<(), Error> {
2581 /// .map_err(|_| Error::Indivisible)
2583 /// .and_then(|remainder| {
2584 /// if remainder == 0 {
2587 /// Err(Error::Remainder(remainder as u8))
2595 /// use std::{fmt, num::ParseIntError};
2597 /// #[derive(Debug)]
2599 /// Indivisible(ParseIntError),
2603 /// impl fmt::Display for Error {
2604 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2606 /// Error::Indivisible(_) => write!(f, "could not divide input by three"),
2607 /// Error::Remainder(remainder) => write!(
2609 /// "input is not divisible by three, remainder = {}",
2616 /// impl std::error::Error for Error {
2617 /// fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
2619 /// Error::Indivisible(source) => Some(source),
2625 /// fn divisible_by_3(input: &str) -> Result<(), Error> {
2628 /// .map_err(Error::Indivisible)
2630 /// .and_then(|remainder| {
2631 /// if remainder == 0 {
2634 /// Err(Error::Remainder(remainder as u8))
2639 #[clippy::version = "1.48.0"]
2642 "`map_err` should not ignore the original error"
2645 pub struct Methods {
2646 avoid_breaking_exported_api: bool,
2647 msrv: Option<RustcVersion>,
2648 allow_expect_in_tests: bool,
2649 allow_unwrap_in_tests: bool,
2655 avoid_breaking_exported_api: bool,
2656 msrv: Option<RustcVersion>,
2657 allow_expect_in_tests: bool,
2658 allow_unwrap_in_tests: bool,
2661 avoid_breaking_exported_api,
2663 allow_expect_in_tests,
2664 allow_unwrap_in_tests,
2669 impl_lint_pass!(Methods => [
2672 SHOULD_IMPLEMENT_TRAIT,
2673 WRONG_SELF_CONVENTION,
2675 UNWRAP_OR_ELSE_DEFAULT,
2677 RESULT_MAP_OR_INTO_OPTION,
2679 BIND_INSTEAD_OF_MAP,
2688 ITER_OVEREAGER_CLONED,
2689 CLONED_INSTEAD_OF_COPIED,
2691 INEFFICIENT_TO_STRING,
2693 SINGLE_CHAR_PATTERN,
2694 SINGLE_CHAR_ADD_STR,
2698 FILTER_MAP_IDENTITY,
2706 ITERATOR_STEP_BY_ZERO,
2715 STRING_EXTEND_CHARS,
2716 ITER_CLONED_COLLECT,
2720 UNNECESSARY_FILTER_MAP,
2721 UNNECESSARY_FIND_MAP,
2724 UNINIT_ASSUMED_INIT,
2725 MANUAL_SATURATING_ARITHMETIC,
2728 OPTION_AS_REF_DEREF,
2729 UNNECESSARY_LAZY_EVALUATIONS,
2730 MAP_COLLECT_RESULT_UNIT,
2731 FROM_ITER_INSTEAD_OF_COLLECT,
2739 UNNECESSARY_TO_OWNED,
2742 NEEDLESS_OPTION_AS_DEREF,
2743 IS_DIGIT_ASCII_RADIX,
2744 NEEDLESS_OPTION_TAKE,
2747 ITER_ON_SINGLE_ITEMS,
2748 ITER_ON_EMPTY_COLLECTIONS,
2751 CASE_SENSITIVE_FILE_EXTENSION_COMPARISONS,
2758 /// Extracts a method call name, args, and `Span` of the method name.
2759 fn method_call<'tcx>(recv: &'tcx hir::Expr<'tcx>) -> Option<(&'tcx str, &'tcx [hir::Expr<'tcx>], Span)> {
2760 if let ExprKind::MethodCall(path, args, _) = recv.kind {
2761 if !args.iter().any(|e| e.span.from_expansion()) {
2762 let name = path.ident.name.as_str();
2763 return Some((name, args, path.ident.span));
2769 impl<'tcx> LateLintPass<'tcx> for Methods {
2770 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) {
2771 if expr.span.from_expansion() {
2775 self.check_methods(cx, expr);
2778 hir::ExprKind::Call(func, args) => {
2779 from_iter_instead_of_collect::check(cx, expr, args, func);
2781 hir::ExprKind::MethodCall(method_call, args, _) => {
2782 let method_span = method_call.ident.span;
2783 or_fun_call::check(cx, expr, method_span, method_call.ident.as_str(), args);
2784 expect_fun_call::check(cx, expr, method_span, method_call.ident.as_str(), args);
2785 clone_on_copy::check(cx, expr, method_call.ident.name, args);
2786 clone_on_ref_ptr::check(cx, expr, method_call.ident.name, args);
2787 inefficient_to_string::check(cx, expr, method_call.ident.name, args);
2788 single_char_add_str::check(cx, expr, args);
2789 into_iter_on_ref::check(cx, expr, method_span, method_call.ident.name, args);
2790 single_char_pattern::check(cx, expr, method_call.ident.name, args);
2791 unnecessary_to_owned::check(cx, expr, method_call.ident.name, args, self.msrv);
2793 hir::ExprKind::Binary(op, lhs, rhs) if op.node == hir::BinOpKind::Eq || op.node == hir::BinOpKind::Ne => {
2794 let mut info = BinaryExprInfo {
2798 eq: op.node == hir::BinOpKind::Eq,
2800 lint_binary_expr_with_method_call(cx, &mut info);
2806 #[allow(clippy::too_many_lines)]
2807 fn check_impl_item(&mut self, cx: &LateContext<'tcx>, impl_item: &'tcx hir::ImplItem<'_>) {
2808 if in_external_macro(cx.sess(), impl_item.span) {
2811 let name = impl_item.ident.name.as_str();
2812 let parent = cx.tcx.hir().get_parent_item(impl_item.hir_id());
2813 let item = cx.tcx.hir().expect_item(parent);
2814 let self_ty = cx.tcx.type_of(item.def_id);
2816 let implements_trait = matches!(item.kind, hir::ItemKind::Impl(hir::Impl { of_trait: Some(_), .. }));
2818 if let hir::ImplItemKind::Fn(ref sig, id) = impl_item.kind;
2819 if let Some(first_arg) = iter_input_pats(sig.decl, cx.tcx.hir().body(id)).next();
2821 let method_sig = cx.tcx.fn_sig(impl_item.def_id);
2822 let method_sig = cx.tcx.erase_late_bound_regions(method_sig);
2824 let first_arg_ty = method_sig.inputs().iter().next();
2826 // check conventions w.r.t. conversion method names and predicates
2827 if let Some(first_arg_ty) = first_arg_ty;
2830 // if this impl block implements a trait, lint in trait definition instead
2831 if !implements_trait && cx.access_levels.is_exported(impl_item.def_id) {
2832 // check missing trait implementations
2833 for method_config in &TRAIT_METHODS {
2834 if name == method_config.method_name &&
2835 sig.decl.inputs.len() == method_config.param_count &&
2836 method_config.output_type.matches(&sig.decl.output) &&
2837 method_config.self_kind.matches(cx, self_ty, *first_arg_ty) &&
2838 fn_header_equals(method_config.fn_header, sig.header) &&
2839 method_config.lifetime_param_cond(impl_item)
2843 SHOULD_IMPLEMENT_TRAIT,
2846 "method `{}` can be confused for the standard trait method `{}::{}`",
2847 method_config.method_name,
2848 method_config.trait_name,
2849 method_config.method_name
2853 "consider implementing the trait `{}` or choosing a less ambiguous method name",
2854 method_config.trait_name
2861 if sig.decl.implicit_self.has_implicit_self()
2862 && !(self.avoid_breaking_exported_api
2863 && cx.access_levels.is_exported(impl_item.def_id))
2865 wrong_self_convention::check(
2878 // if this impl block implements a trait, lint in trait definition instead
2879 if implements_trait {
2883 if let hir::ImplItemKind::Fn(_, _) = impl_item.kind {
2884 let ret_ty = return_ty(cx, impl_item.hir_id());
2886 // walk the return type and check for Self (this does not check associated types)
2887 if let Some(self_adt) = self_ty.ty_adt_def() {
2888 if contains_adt_constructor(ret_ty, self_adt) {
2891 } else if contains_ty(ret_ty, self_ty) {
2895 // if return type is impl trait, check the associated types
2896 if let ty::Opaque(def_id, _) = *ret_ty.kind() {
2897 // one of the associated types must be Self
2898 for &(predicate, _span) in cx.tcx.explicit_item_bounds(def_id) {
2899 if let ty::PredicateKind::Projection(projection_predicate) = predicate.kind().skip_binder() {
2900 let assoc_ty = match projection_predicate.term {
2901 ty::Term::Ty(ty) => ty,
2902 ty::Term::Const(_c) => continue,
2904 // walk the associated type and check for Self
2905 if let Some(self_adt) = self_ty.ty_adt_def() {
2906 if contains_adt_constructor(assoc_ty, self_adt) {
2909 } else if contains_ty(assoc_ty, self_ty) {
2916 if name == "new" && ret_ty != self_ty {
2921 "methods called `new` usually return `Self`",
2927 fn check_trait_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx TraitItem<'_>) {
2928 if in_external_macro(cx.tcx.sess, item.span) {
2933 if let TraitItemKind::Fn(ref sig, _) = item.kind;
2934 if sig.decl.implicit_self.has_implicit_self();
2935 if let Some(first_arg_ty) = sig.decl.inputs.iter().next();
2938 let first_arg_span = first_arg_ty.span;
2939 let first_arg_ty = hir_ty_to_ty(cx.tcx, first_arg_ty);
2940 let self_ty = TraitRef::identity(cx.tcx, item.def_id.to_def_id()).self_ty().skip_binder();
2941 wrong_self_convention::check(
2943 item.ident.name.as_str(),
2954 if item.ident.name == sym::new;
2955 if let TraitItemKind::Fn(_, _) = item.kind;
2956 let ret_ty = return_ty(cx, item.hir_id());
2957 let self_ty = TraitRef::identity(cx.tcx, item.def_id.to_def_id()).self_ty().skip_binder();
2958 if !contains_ty(ret_ty, self_ty);
2965 "methods called `new` usually return `Self`",
2971 extract_msrv_attr!(LateContext);
2975 #[allow(clippy::too_many_lines)]
2976 fn check_methods<'tcx>(&self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
2977 if let Some((name, [recv, args @ ..], span)) = method_call(expr) {
2978 match (name, args) {
2979 ("add" | "offset" | "sub" | "wrapping_offset" | "wrapping_add" | "wrapping_sub", [_arg]) => {
2980 zst_offset::check(cx, expr, recv);
2982 ("and_then", [arg]) => {
2983 let biom_option_linted = bind_instead_of_map::OptionAndThenSome::check(cx, expr, recv, arg);
2984 let biom_result_linted = bind_instead_of_map::ResultAndThenOk::check(cx, expr, recv, arg);
2985 if !biom_option_linted && !biom_result_linted {
2986 unnecessary_lazy_eval::check(cx, expr, recv, arg, "and");
2989 ("as_deref" | "as_deref_mut", []) => {
2990 needless_option_as_deref::check(cx, expr, recv, name);
2992 ("as_mut", []) => useless_asref::check(cx, expr, "as_mut", recv),
2993 ("as_ref", []) => useless_asref::check(cx, expr, "as_ref", recv),
2994 ("assume_init", []) => uninit_assumed_init::check(cx, expr, recv),
2995 ("cloned", []) => cloned_instead_of_copied::check(cx, expr, recv, span, self.msrv),
2996 ("collect", []) => match method_call(recv) {
2997 Some((name @ ("cloned" | "copied"), [recv2], _)) => {
2998 iter_cloned_collect::check(cx, name, expr, recv2);
3000 Some(("map", [m_recv, m_arg], _)) => {
3001 map_collect_result_unit::check(cx, expr, m_recv, m_arg, recv);
3003 Some(("take", [take_self_arg, take_arg], _)) => {
3004 if meets_msrv(self.msrv, msrvs::STR_REPEAT) {
3005 manual_str_repeat::check(cx, expr, recv, take_self_arg, take_arg);
3010 ("count", []) if is_trait_method(cx, expr, sym::Iterator) => match method_call(recv) {
3011 Some(("cloned", [recv2], _)) => iter_overeager_cloned::check(cx, expr, recv, recv2, true, false),
3012 Some((name2 @ ("into_iter" | "iter" | "iter_mut"), [recv2], _)) => {
3013 iter_count::check(cx, expr, recv2, name2);
3015 Some(("map", [_, arg], _)) => suspicious_map::check(cx, expr, recv, arg),
3016 Some(("filter", [recv2, arg], _)) => bytecount::check(cx, expr, recv2, arg),
3017 Some(("bytes", [recv2], _)) => bytes_count_to_len::check(cx, expr, recv, recv2),
3020 ("drain", [arg]) => {
3021 iter_with_drain::check(cx, expr, recv, span, arg);
3023 ("ends_with", [arg]) => {
3024 if let ExprKind::MethodCall(_, _, span) = expr.kind {
3025 case_sensitive_file_extension_comparisons::check(cx, expr, span, recv, arg);
3028 ("expect", [_]) => match method_call(recv) {
3029 Some(("ok", [recv], _)) => ok_expect::check(cx, expr, recv),
3030 Some(("err", [recv], err_span)) => err_expect::check(cx, expr, recv, self.msrv, span, err_span),
3031 _ => expect_used::check(cx, expr, recv, false, self.allow_expect_in_tests),
3033 ("expect_err", [_]) => expect_used::check(cx, expr, recv, true, self.allow_expect_in_tests),
3034 ("extend", [arg]) => {
3035 string_extend_chars::check(cx, expr, recv, arg);
3036 extend_with_drain::check(cx, expr, recv, arg);
3038 ("filter_map", [arg]) => {
3039 unnecessary_filter_map::check(cx, expr, arg, name);
3040 filter_map_identity::check(cx, expr, arg, span);
3042 ("find_map", [arg]) => {
3043 unnecessary_filter_map::check(cx, expr, arg, name);
3045 ("flat_map", [arg]) => {
3046 flat_map_identity::check(cx, expr, arg, span);
3047 flat_map_option::check(cx, expr, arg, span);
3049 ("flatten", []) => match method_call(recv) {
3050 Some(("map", [recv, map_arg], map_span)) => map_flatten::check(cx, expr, recv, map_arg, map_span),
3051 Some(("cloned", [recv2], _)) => iter_overeager_cloned::check(cx, expr, recv, recv2, false, true),
3054 ("fold", [init, acc]) => unnecessary_fold::check(cx, expr, init, acc, span),
3055 ("for_each", [_]) => {
3056 if let Some(("inspect", [_, _], span2)) = method_call(recv) {
3057 inspect_for_each::check(cx, expr, span2);
3061 get_first::check(cx, expr, recv, arg);
3062 get_last_with_len::check(cx, expr, recv, arg);
3064 ("get_or_insert_with", [arg]) => unnecessary_lazy_eval::check(cx, expr, recv, arg, "get_or_insert"),
3065 ("is_file", []) => filetype_is_file::check(cx, expr, recv),
3066 ("is_digit", [radix]) => is_digit_ascii_radix::check(cx, expr, recv, radix, self.msrv),
3067 ("is_none", []) => check_is_some_is_none(cx, expr, recv, false),
3068 ("is_some", []) => check_is_some_is_none(cx, expr, recv, true),
3069 ("iter" | "iter_mut" | "into_iter", []) => {
3070 iter_on_single_or_empty_collections::check(cx, expr, name, recv);
3072 ("join", [join_arg]) => {
3073 if let Some(("collect", _, span)) = method_call(recv) {
3074 unnecessary_join::check(cx, expr, recv, join_arg, span);
3077 ("last", []) | ("skip", [_]) => {
3078 if let Some((name2, [recv2, args2 @ ..], _span2)) = method_call(recv) {
3079 if let ("cloned", []) = (name2, args2) {
3080 iter_overeager_cloned::check(cx, expr, recv, recv2, false, false);
3084 (name @ ("map" | "map_err"), [m_arg]) => {
3086 map_clone::check(cx, expr, recv, m_arg, self.msrv);
3088 map_err_ignore::check(cx, expr, m_arg);
3090 if let Some((name, [recv2, args @ ..], span2)) = method_call(recv) {
3091 match (name, args) {
3092 ("as_mut", []) => option_as_ref_deref::check(cx, expr, recv2, m_arg, true, self.msrv),
3093 ("as_ref", []) => option_as_ref_deref::check(cx, expr, recv2, m_arg, false, self.msrv),
3094 ("filter", [f_arg]) => {
3095 filter_map::check(cx, expr, recv2, f_arg, span2, recv, m_arg, span, false);
3097 ("find", [f_arg]) => {
3098 filter_map::check(cx, expr, recv2, f_arg, span2, recv, m_arg, span, true);
3103 map_identity::check(cx, expr, recv, m_arg, name, span);
3105 ("map_or", [def, map]) => {
3106 option_map_or_none::check(cx, expr, recv, def, map);
3107 manual_ok_or::check(cx, expr, recv, def, map);
3110 if let Some((name2, [recv2, args2 @ ..], _)) = method_call(recv) {
3111 match (name2, args2) {
3112 ("cloned", []) => iter_overeager_cloned::check(cx, expr, recv, recv2, false, false),
3113 ("filter", [arg]) => filter_next::check(cx, expr, recv2, arg),
3114 ("filter_map", [arg]) => filter_map_next::check(cx, expr, recv2, arg, self.msrv),
3115 ("iter", []) => iter_next_slice::check(cx, expr, recv2),
3116 ("skip", [arg]) => iter_skip_next::check(cx, expr, recv2, arg),
3117 ("skip_while", [_]) => skip_while_next::check(cx, expr),
3122 ("nth", [n_arg]) => match method_call(recv) {
3123 Some(("bytes", [recv2], _)) => bytes_nth::check(cx, expr, recv2, n_arg),
3124 Some(("cloned", [recv2], _)) => iter_overeager_cloned::check(cx, expr, recv, recv2, false, false),
3125 Some(("iter", [recv2], _)) => iter_nth::check(cx, expr, recv2, recv, n_arg, false),
3126 Some(("iter_mut", [recv2], _)) => iter_nth::check(cx, expr, recv2, recv, n_arg, true),
3127 _ => iter_nth_zero::check(cx, expr, recv, n_arg),
3129 ("ok_or_else", [arg]) => unnecessary_lazy_eval::check(cx, expr, recv, arg, "ok_or"),
3130 ("or_else", [arg]) => {
3131 if !bind_instead_of_map::ResultOrElseErrInfo::check(cx, expr, recv, arg) {
3132 unnecessary_lazy_eval::check(cx, expr, recv, arg, "or");
3135 ("splitn" | "rsplitn", [count_arg, pat_arg]) => {
3136 if let Some((Constant::Int(count), _)) = constant(cx, cx.typeck_results(), count_arg) {
3137 suspicious_splitn::check(cx, name, expr, recv, count);
3138 str_splitn::check(cx, name, expr, recv, pat_arg, count, self.msrv);
3141 ("splitn_mut" | "rsplitn_mut", [count_arg, _]) => {
3142 if let Some((Constant::Int(count), _)) = constant(cx, cx.typeck_results(), count_arg) {
3143 suspicious_splitn::check(cx, name, expr, recv, count);
3146 ("step_by", [arg]) => iterator_step_by_zero::check(cx, expr, arg),
3147 ("take", [_arg]) => {
3148 if let Some((name2, [recv2, args2 @ ..], _span2)) = method_call(recv) {
3149 if let ("cloned", []) = (name2, args2) {
3150 iter_overeager_cloned::check(cx, expr, recv, recv2, false, false);
3154 ("take", []) => needless_option_take::check(cx, expr, recv),
3155 ("then", [arg]) => {
3156 if !meets_msrv(self.msrv, msrvs::BOOL_THEN_SOME) {
3159 unnecessary_lazy_eval::check(cx, expr, recv, arg, "then_some");
3161 ("to_os_string" | "to_owned" | "to_path_buf" | "to_vec", []) => {
3162 implicit_clone::check(cx, name, expr, recv);
3165 match method_call(recv) {
3166 Some(("get", [recv, get_arg], _)) => {
3167 get_unwrap::check(cx, expr, recv, get_arg, false);
3169 Some(("get_mut", [recv, get_arg], _)) => {
3170 get_unwrap::check(cx, expr, recv, get_arg, true);
3172 Some(("or", [recv, or_arg], or_span)) => {
3173 or_then_unwrap::check(cx, expr, recv, or_arg, or_span);
3177 unwrap_used::check(cx, expr, recv, false, self.allow_unwrap_in_tests);
3179 ("unwrap_err", []) => unwrap_used::check(cx, expr, recv, true, self.allow_unwrap_in_tests),
3180 ("unwrap_or", [u_arg]) => match method_call(recv) {
3181 Some((arith @ ("checked_add" | "checked_sub" | "checked_mul"), [lhs, rhs], _)) => {
3182 manual_saturating_arithmetic::check(cx, expr, lhs, rhs, u_arg, &arith["checked_".len()..]);
3184 Some(("map", [m_recv, m_arg], span)) => {
3185 option_map_unwrap_or::check(cx, expr, m_recv, m_arg, recv, u_arg, span);
3187 Some(("then_some", [t_recv, t_arg], _)) => {
3188 obfuscated_if_else::check(cx, expr, t_recv, t_arg, u_arg);
3192 ("unwrap_or_else", [u_arg]) => match method_call(recv) {
3193 Some(("map", [recv, map_arg], _))
3194 if map_unwrap_or::check(cx, expr, recv, map_arg, u_arg, self.msrv) => {},
3196 unwrap_or_else_default::check(cx, expr, recv, u_arg);
3197 unnecessary_lazy_eval::check(cx, expr, recv, u_arg, "unwrap_or");
3200 ("replace" | "replacen", [arg1, arg2] | [arg1, arg2, _]) => {
3201 no_effect_replace::check(cx, expr, arg1, arg2);
3209 fn check_is_some_is_none(cx: &LateContext<'_>, expr: &Expr<'_>, recv: &Expr<'_>, is_some: bool) {
3210 if let Some((name @ ("find" | "position" | "rposition"), [f_recv, arg], span)) = method_call(recv) {
3211 search_is_some::check(cx, expr, name, is_some, f_recv, arg, recv, span);
3215 /// Used for `lint_binary_expr_with_method_call`.
3216 #[derive(Copy, Clone)]
3217 struct BinaryExprInfo<'a> {
3218 expr: &'a hir::Expr<'a>,
3219 chain: &'a hir::Expr<'a>,
3220 other: &'a hir::Expr<'a>,
3224 /// Checks for the `CHARS_NEXT_CMP` and `CHARS_LAST_CMP` lints.
3225 fn lint_binary_expr_with_method_call(cx: &LateContext<'_>, info: &mut BinaryExprInfo<'_>) {
3226 macro_rules! lint_with_both_lhs_and_rhs {
3227 ($func:expr, $cx:expr, $info:ident) => {
3228 if !$func($cx, $info) {
3229 ::std::mem::swap(&mut $info.chain, &mut $info.other);
3230 if $func($cx, $info) {
3237 lint_with_both_lhs_and_rhs!(chars_next_cmp::check, cx, info);
3238 lint_with_both_lhs_and_rhs!(chars_last_cmp::check, cx, info);
3239 lint_with_both_lhs_and_rhs!(chars_next_cmp_with_unwrap::check, cx, info);
3240 lint_with_both_lhs_and_rhs!(chars_last_cmp_with_unwrap::check, cx, info);
3243 const FN_HEADER: hir::FnHeader = hir::FnHeader {
3244 unsafety: hir::Unsafety::Normal,
3245 constness: hir::Constness::NotConst,
3246 asyncness: hir::IsAsync::NotAsync,
3247 abi: rustc_target::spec::abi::Abi::Rust,
3250 struct ShouldImplTraitCase {
3251 trait_name: &'static str,
3252 method_name: &'static str,
3254 fn_header: hir::FnHeader,
3255 // implicit self kind expected (none, self, &self, ...)
3256 self_kind: SelfKind,
3257 // checks against the output type
3258 output_type: OutType,
3259 // certain methods with explicit lifetimes can't implement the equivalent trait method
3260 lint_explicit_lifetime: bool,
3262 impl ShouldImplTraitCase {
3264 trait_name: &'static str,
3265 method_name: &'static str,
3267 fn_header: hir::FnHeader,
3268 self_kind: SelfKind,
3269 output_type: OutType,
3270 lint_explicit_lifetime: bool,
3271 ) -> ShouldImplTraitCase {
3272 ShouldImplTraitCase {
3279 lint_explicit_lifetime,
3283 fn lifetime_param_cond(&self, impl_item: &hir::ImplItem<'_>) -> bool {
3284 self.lint_explicit_lifetime
3285 || !impl_item.generics.params.iter().any(|p| {
3288 hir::GenericParamKind::Lifetime {
3289 kind: hir::LifetimeParamKind::Explicit
3297 const TRAIT_METHODS: [ShouldImplTraitCase; 30] = [
3298 ShouldImplTraitCase::new("std::ops::Add", "add", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3299 ShouldImplTraitCase::new("std::convert::AsMut", "as_mut", 1, FN_HEADER, SelfKind::RefMut, OutType::Ref, true),
3300 ShouldImplTraitCase::new("std::convert::AsRef", "as_ref", 1, FN_HEADER, SelfKind::Ref, OutType::Ref, true),
3301 ShouldImplTraitCase::new("std::ops::BitAnd", "bitand", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3302 ShouldImplTraitCase::new("std::ops::BitOr", "bitor", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3303 ShouldImplTraitCase::new("std::ops::BitXor", "bitxor", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3304 ShouldImplTraitCase::new("std::borrow::Borrow", "borrow", 1, FN_HEADER, SelfKind::Ref, OutType::Ref, true),
3305 ShouldImplTraitCase::new("std::borrow::BorrowMut", "borrow_mut", 1, FN_HEADER, SelfKind::RefMut, OutType::Ref, true),
3306 ShouldImplTraitCase::new("std::clone::Clone", "clone", 1, FN_HEADER, SelfKind::Ref, OutType::Any, true),
3307 ShouldImplTraitCase::new("std::cmp::Ord", "cmp", 2, FN_HEADER, SelfKind::Ref, OutType::Any, true),
3308 // FIXME: default doesn't work
3309 ShouldImplTraitCase::new("std::default::Default", "default", 0, FN_HEADER, SelfKind::No, OutType::Any, true),
3310 ShouldImplTraitCase::new("std::ops::Deref", "deref", 1, FN_HEADER, SelfKind::Ref, OutType::Ref, true),
3311 ShouldImplTraitCase::new("std::ops::DerefMut", "deref_mut", 1, FN_HEADER, SelfKind::RefMut, OutType::Ref, true),
3312 ShouldImplTraitCase::new("std::ops::Div", "div", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3313 ShouldImplTraitCase::new("std::ops::Drop", "drop", 1, FN_HEADER, SelfKind::RefMut, OutType::Unit, true),
3314 ShouldImplTraitCase::new("std::cmp::PartialEq", "eq", 2, FN_HEADER, SelfKind::Ref, OutType::Bool, true),
3315 ShouldImplTraitCase::new("std::iter::FromIterator", "from_iter", 1, FN_HEADER, SelfKind::No, OutType::Any, true),
3316 ShouldImplTraitCase::new("std::str::FromStr", "from_str", 1, FN_HEADER, SelfKind::No, OutType::Any, true),
3317 ShouldImplTraitCase::new("std::hash::Hash", "hash", 2, FN_HEADER, SelfKind::Ref, OutType::Unit, true),
3318 ShouldImplTraitCase::new("std::ops::Index", "index", 2, FN_HEADER, SelfKind::Ref, OutType::Ref, true),
3319 ShouldImplTraitCase::new("std::ops::IndexMut", "index_mut", 2, FN_HEADER, SelfKind::RefMut, OutType::Ref, true),
3320 ShouldImplTraitCase::new("std::iter::IntoIterator", "into_iter", 1, FN_HEADER, SelfKind::Value, OutType::Any, true),
3321 ShouldImplTraitCase::new("std::ops::Mul", "mul", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3322 ShouldImplTraitCase::new("std::ops::Neg", "neg", 1, FN_HEADER, SelfKind::Value, OutType::Any, true),
3323 ShouldImplTraitCase::new("std::iter::Iterator", "next", 1, FN_HEADER, SelfKind::RefMut, OutType::Any, false),
3324 ShouldImplTraitCase::new("std::ops::Not", "not", 1, FN_HEADER, SelfKind::Value, OutType::Any, true),
3325 ShouldImplTraitCase::new("std::ops::Rem", "rem", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3326 ShouldImplTraitCase::new("std::ops::Shl", "shl", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3327 ShouldImplTraitCase::new("std::ops::Shr", "shr", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3328 ShouldImplTraitCase::new("std::ops::Sub", "sub", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3331 #[derive(Clone, Copy, PartialEq, Eq, Debug)]
3340 fn matches<'a>(self, cx: &LateContext<'a>, parent_ty: Ty<'a>, ty: Ty<'a>) -> bool {
3341 fn matches_value<'a>(cx: &LateContext<'a>, parent_ty: Ty<'a>, ty: Ty<'a>) -> bool {
3342 if ty == parent_ty {
3344 } else if ty.is_box() {
3345 ty.boxed_ty() == parent_ty
3346 } else if is_type_diagnostic_item(cx, ty, sym::Rc) || is_type_diagnostic_item(cx, ty, sym::Arc) {
3347 if let ty::Adt(_, substs) = ty.kind() {
3348 substs.types().next().map_or(false, |t| t == parent_ty)
3357 fn matches_ref<'a>(cx: &LateContext<'a>, mutability: hir::Mutability, parent_ty: Ty<'a>, ty: Ty<'a>) -> bool {
3358 if let ty::Ref(_, t, m) = *ty.kind() {
3359 return m == mutability && t == parent_ty;
3362 let trait_path = match mutability {
3363 hir::Mutability::Not => &paths::ASREF_TRAIT,
3364 hir::Mutability::Mut => &paths::ASMUT_TRAIT,
3367 let trait_def_id = match get_trait_def_id(cx, trait_path) {
3369 None => return false,
3371 implements_trait(cx, ty, trait_def_id, &[parent_ty.into()])
3374 fn matches_none<'a>(cx: &LateContext<'a>, parent_ty: Ty<'a>, ty: Ty<'a>) -> bool {
3375 !matches_value(cx, parent_ty, ty)
3376 && !matches_ref(cx, hir::Mutability::Not, parent_ty, ty)
3377 && !matches_ref(cx, hir::Mutability::Mut, parent_ty, ty)
3381 Self::Value => matches_value(cx, parent_ty, ty),
3382 Self::Ref => matches_ref(cx, hir::Mutability::Not, parent_ty, ty) || ty == parent_ty && is_copy(cx, ty),
3383 Self::RefMut => matches_ref(cx, hir::Mutability::Mut, parent_ty, ty),
3384 Self::No => matches_none(cx, parent_ty, ty),
3389 fn description(self) -> &'static str {
3391 Self::Value => "`self` by value",
3392 Self::Ref => "`self` by reference",
3393 Self::RefMut => "`self` by mutable reference",
3394 Self::No => "no `self`",
3399 #[derive(Clone, Copy)]
3408 fn matches(self, ty: &hir::FnRetTy<'_>) -> bool {
3409 let is_unit = |ty: &hir::Ty<'_>| matches!(ty.kind, hir::TyKind::Tup(&[]));
3411 (Self::Unit, &hir::FnRetTy::DefaultReturn(_)) => true,
3412 (Self::Unit, &hir::FnRetTy::Return(ty)) if is_unit(ty) => true,
3413 (Self::Bool, &hir::FnRetTy::Return(ty)) if is_bool(ty) => true,
3414 (Self::Any, &hir::FnRetTy::Return(ty)) if !is_unit(ty) => true,
3415 (Self::Ref, &hir::FnRetTy::Return(ty)) => matches!(ty.kind, hir::TyKind::Rptr(_, _)),
3421 fn is_bool(ty: &hir::Ty<'_>) -> bool {
3422 if let hir::TyKind::Path(QPath::Resolved(_, path)) = ty.kind {
3423 matches!(path.res, Res::PrimTy(PrimTy::Bool))
3429 fn fn_header_equals(expected: hir::FnHeader, actual: hir::FnHeader) -> bool {
3430 expected.constness == actual.constness
3431 && expected.unsafety == actual.unsafety
3432 && expected.asyncness == actual.asyncness