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;
53 mod needless_option_as_deref;
54 mod needless_option_take;
55 mod no_effect_replace;
56 mod obfuscated_if_else;
58 mod option_as_ref_deref;
59 mod option_map_or_none;
60 mod option_map_unwrap_or;
64 mod single_char_add_str;
65 mod single_char_insert_string;
66 mod single_char_pattern;
67 mod single_char_push_string;
70 mod string_extend_chars;
72 mod suspicious_splitn;
73 mod uninit_assumed_init;
74 mod unnecessary_filter_map;
76 mod unnecessary_iter_cloned;
78 mod unnecessary_lazy_eval;
79 mod unnecessary_to_owned;
80 mod unwrap_or_else_default;
84 mod wrong_self_convention;
87 use bind_instead_of_map::BindInsteadOfMap;
88 use clippy_utils::consts::{constant, Constant};
89 use clippy_utils::diagnostics::{span_lint, span_lint_and_help};
90 use clippy_utils::ty::{contains_adt_constructor, contains_ty, implements_trait, is_copy, is_type_diagnostic_item};
92 contains_return, get_trait_def_id, is_trait_method, iter_input_pats, meets_msrv, msrvs, paths, return_ty,
94 use if_chain::if_chain;
96 use rustc_hir::def::Res;
97 use rustc_hir::{Expr, ExprKind, PrimTy, QPath, TraitItem, TraitItemKind};
98 use rustc_lint::{LateContext, LateLintPass, LintContext};
99 use rustc_middle::lint::in_external_macro;
100 use rustc_middle::ty::{self, TraitRef, Ty};
101 use rustc_semver::RustcVersion;
102 use rustc_session::{declare_tool_lint, impl_lint_pass};
103 use rustc_span::{sym, Span};
104 use rustc_typeck::hir_ty_to_ty;
106 declare_clippy_lint! {
108 /// Checks for usages of `cloned()` on an `Iterator` or `Option` where
109 /// `copied()` could be used instead.
111 /// ### Why is this bad?
112 /// `copied()` is better because it guarantees that the type being cloned
113 /// implements `Copy`.
117 /// [1, 2, 3].iter().cloned();
121 /// [1, 2, 3].iter().copied();
123 #[clippy::version = "1.53.0"]
124 pub CLONED_INSTEAD_OF_COPIED,
126 "used `cloned` where `copied` could be used instead"
129 declare_clippy_lint! {
131 /// Checks for usage of `_.cloned().<func>()` where call to `.cloned()` can be postponed.
133 /// ### Why is this bad?
134 /// It's often inefficient to clone all elements of an iterator, when eventually, only some
135 /// of them will be consumed.
137 /// ### Known Problems
138 /// This `lint` removes the side of effect of cloning items in the iterator.
139 /// A code that relies on that side-effect could fail.
143 /// # let vec = vec!["string".to_string()];
144 /// vec.iter().cloned().take(10);
145 /// vec.iter().cloned().last();
150 /// # let vec = vec!["string".to_string()];
151 /// vec.iter().take(10).cloned();
152 /// vec.iter().last().cloned();
154 #[clippy::version = "1.60.0"]
155 pub ITER_OVEREAGER_CLONED,
157 "using `cloned()` early with `Iterator::iter()` can lead to some performance inefficiencies"
160 declare_clippy_lint! {
162 /// Checks for usages of `Iterator::flat_map()` where `filter_map()` could be
165 /// ### Why is this bad?
166 /// When applicable, `filter_map()` is more clear since it shows that
167 /// `Option` is used to produce 0 or 1 items.
171 /// let nums: Vec<i32> = ["1", "2", "whee!"].iter().flat_map(|x| x.parse().ok()).collect();
175 /// let nums: Vec<i32> = ["1", "2", "whee!"].iter().filter_map(|x| x.parse().ok()).collect();
177 #[clippy::version = "1.53.0"]
180 "used `flat_map` where `filter_map` could be used instead"
183 declare_clippy_lint! {
185 /// Checks for `.unwrap()` or `.unwrap_err()` calls on `Result`s and `.unwrap()` call on `Option`s.
187 /// ### Why is this bad?
188 /// It is better to handle the `None` or `Err` case,
189 /// or at least call `.expect(_)` with a more helpful message. Still, for a lot of
190 /// quick-and-dirty code, `unwrap` is a good choice, which is why this lint is
191 /// `Allow` by default.
193 /// `result.unwrap()` will let the thread panic on `Err` values.
194 /// Normally, you want to implement more sophisticated error handling,
195 /// and propagate errors upwards with `?` operator.
197 /// Even if you want to panic on errors, not all `Error`s implement good
198 /// messages on display. Therefore, it may be beneficial to look at the places
199 /// where they may get displayed. Activate this lint to do just that.
203 /// # let option = Some(1);
204 /// # let result: Result<usize, ()> = Ok(1);
211 /// # let option = Some(1);
212 /// # let result: Result<usize, ()> = Ok(1);
213 /// option.expect("more helpful message");
214 /// result.expect("more helpful message");
217 /// If [expect_used](#expect_used) is enabled, instead:
219 /// # let option = Some(1);
220 /// # let result: Result<usize, ()> = Ok(1);
227 #[clippy::version = "1.45.0"]
230 "using `.unwrap()` on `Result` or `Option`, which should at least get a better message using `expect()`"
233 declare_clippy_lint! {
235 /// Checks for `.expect()` or `.expect_err()` calls on `Result`s and `.expect()` call on `Option`s.
237 /// ### Why is this bad?
238 /// Usually it is better to handle the `None` or `Err` case.
239 /// Still, for a lot of quick-and-dirty code, `expect` is a good choice, which is why
240 /// this lint is `Allow` by default.
242 /// `result.expect()` will let the thread panic on `Err`
243 /// values. Normally, you want to implement more sophisticated error handling,
244 /// and propagate errors upwards with `?` operator.
248 /// # let option = Some(1);
249 /// # let result: Result<usize, ()> = Ok(1);
250 /// option.expect("one");
251 /// result.expect("one");
256 /// # let option = Some(1);
257 /// # let result: Result<usize, ()> = Ok(1);
264 #[clippy::version = "1.45.0"]
267 "using `.expect()` on `Result` or `Option`, which might be better handled"
270 declare_clippy_lint! {
272 /// Checks for methods that should live in a trait
273 /// implementation of a `std` trait (see [llogiq's blog
274 /// post](http://llogiq.github.io/2015/07/30/traits.html) for further
275 /// information) instead of an inherent implementation.
277 /// ### Why is this bad?
278 /// Implementing the traits improve ergonomics for users of
279 /// the code, often with very little cost. Also people seeing a `mul(...)`
281 /// may expect `*` to work equally, so you should have good reason to disappoint
288 /// fn add(&self, other: &X) -> X {
294 #[clippy::version = "pre 1.29.0"]
295 pub SHOULD_IMPLEMENT_TRAIT,
297 "defining a method that should be implementing a std trait"
300 declare_clippy_lint! {
302 /// Checks for methods with certain name prefixes and which
303 /// doesn't match how self is taken. The actual rules are:
305 /// |Prefix |Postfix |`self` taken | `self` type |
306 /// |-------|------------|-------------------------------|--------------|
307 /// |`as_` | none |`&self` or `&mut self` | any |
308 /// |`from_`| none | none | any |
309 /// |`into_`| none |`self` | any |
310 /// |`is_` | none |`&mut self` or `&self` or none | any |
311 /// |`to_` | `_mut` |`&mut self` | any |
312 /// |`to_` | not `_mut` |`self` | `Copy` |
313 /// |`to_` | not `_mut` |`&self` | not `Copy` |
315 /// Note: Clippy doesn't trigger methods with `to_` prefix in:
316 /// - Traits definition.
317 /// Clippy can not tell if a type that implements a trait is `Copy` or not.
318 /// - Traits implementation, when `&self` is taken.
319 /// The method signature is controlled by the trait and often `&self` is required for all types that implement the trait
320 /// (see e.g. the `std::string::ToString` trait).
322 /// Clippy allows `Pin<&Self>` and `Pin<&mut Self>` if `&self` and `&mut self` is required.
324 /// Please find more info here:
325 /// https://rust-lang.github.io/api-guidelines/naming.html#ad-hoc-conversions-follow-as_-to_-into_-conventions-c-conv
327 /// ### Why is this bad?
328 /// Consistency breeds readability. If you follow the
329 /// conventions, your users won't be surprised that they, e.g., need to supply a
330 /// mutable reference to a `as_..` function.
336 /// fn as_str(self) -> &'static str {
342 #[clippy::version = "pre 1.29.0"]
343 pub WRONG_SELF_CONVENTION,
345 "defining a method named with an established prefix (like \"into_\") that takes `self` with the wrong convention"
348 declare_clippy_lint! {
350 /// Checks for usage of `ok().expect(..)`.
352 /// ### Why is this bad?
353 /// Because you usually call `expect()` on the `Result`
354 /// directly to get a better error message.
356 /// ### Known problems
357 /// The error type needs to implement `Debug`
361 /// # let x = Ok::<_, ()>(());
362 /// x.ok().expect("why did I do this again?");
367 /// # let x = Ok::<_, ()>(());
368 /// x.expect("why did I do this again?");
370 #[clippy::version = "pre 1.29.0"]
373 "using `ok().expect()`, which gives worse error messages than calling `expect` directly on the Result"
376 declare_clippy_lint! {
378 /// Checks for `.err().expect()` calls on the `Result` type.
380 /// ### Why is this bad?
381 /// `.expect_err()` can be called directly to avoid the extra type conversion from `err()`.
385 /// let x: Result<u32, &str> = Ok(10);
386 /// x.err().expect("Testing err().expect()");
390 /// let x: Result<u32, &str> = Ok(10);
391 /// x.expect_err("Testing expect_err");
393 #[clippy::version = "1.62.0"]
396 r#"using `.err().expect("")` when `.expect_err("")` can be used"#
399 declare_clippy_lint! {
401 /// Checks for usages of `_.unwrap_or_else(Default::default)` on `Option` and
404 /// ### Why is this bad?
405 /// Readability, these can be written as `_.unwrap_or_default`, which is
406 /// simpler and more concise.
410 /// # let x = Some(1);
411 /// x.unwrap_or_else(Default::default);
412 /// x.unwrap_or_else(u32::default);
417 /// # let x = Some(1);
418 /// x.unwrap_or_default();
420 #[clippy::version = "1.56.0"]
421 pub UNWRAP_OR_ELSE_DEFAULT,
423 "using `.unwrap_or_else(Default::default)`, which is more succinctly expressed as `.unwrap_or_default()`"
426 declare_clippy_lint! {
428 /// Checks for usage of `option.map(_).unwrap_or(_)` or `option.map(_).unwrap_or_else(_)` or
429 /// `result.map(_).unwrap_or_else(_)`.
431 /// ### Why is this bad?
432 /// Readability, these can be written more concisely (resp.) as
433 /// `option.map_or(_, _)`, `option.map_or_else(_, _)` and `result.map_or_else(_, _)`.
435 /// ### Known problems
436 /// The order of the arguments is not in execution order
440 /// # let option = Some(1);
441 /// # let result: Result<usize, ()> = Ok(1);
442 /// # fn some_function(foo: ()) -> usize { 1 }
443 /// option.map(|a| a + 1).unwrap_or(0);
444 /// result.map(|a| a + 1).unwrap_or_else(some_function);
449 /// # let option = Some(1);
450 /// # let result: Result<usize, ()> = Ok(1);
451 /// # fn some_function(foo: ()) -> usize { 1 }
452 /// option.map_or(0, |a| a + 1);
453 /// result.map_or_else(some_function, |a| a + 1);
455 #[clippy::version = "1.45.0"]
458 "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)`"
461 declare_clippy_lint! {
463 /// Checks for usage of `_.map_or(None, _)`.
465 /// ### Why is this bad?
466 /// Readability, this can be written more concisely as
469 /// ### Known problems
470 /// The order of the arguments is not in execution order.
474 /// # let opt = Some(1);
475 /// opt.map_or(None, |a| Some(a + 1));
480 /// # let opt = Some(1);
481 /// opt.and_then(|a| Some(a + 1));
483 #[clippy::version = "pre 1.29.0"]
484 pub OPTION_MAP_OR_NONE,
486 "using `Option.map_or(None, f)`, which is more succinctly expressed as `and_then(f)`"
489 declare_clippy_lint! {
491 /// Checks for usage of `_.map_or(None, Some)`.
493 /// ### Why is this bad?
494 /// Readability, this can be written more concisely as
499 /// # let r: Result<u32, &str> = Ok(1);
500 /// assert_eq!(Some(1), r.map_or(None, Some));
505 /// # let r: Result<u32, &str> = Ok(1);
506 /// assert_eq!(Some(1), r.ok());
508 #[clippy::version = "1.44.0"]
509 pub RESULT_MAP_OR_INTO_OPTION,
511 "using `Result.map_or(None, Some)`, which is more succinctly expressed as `ok()`"
514 declare_clippy_lint! {
516 /// Checks for usage of `_.and_then(|x| Some(y))`, `_.and_then(|x| Ok(y))` or
517 /// `_.or_else(|x| Err(y))`.
519 /// ### Why is this bad?
520 /// Readability, this can be written more concisely as
521 /// `_.map(|x| y)` or `_.map_err(|x| y)`.
525 /// # fn opt() -> Option<&'static str> { Some("42") }
526 /// # fn res() -> Result<&'static str, &'static str> { Ok("42") }
527 /// let _ = opt().and_then(|s| Some(s.len()));
528 /// let _ = res().and_then(|s| if s.len() == 42 { Ok(10) } else { Ok(20) });
529 /// let _ = res().or_else(|s| if s.len() == 42 { Err(10) } else { Err(20) });
532 /// The correct use would be:
535 /// # fn opt() -> Option<&'static str> { Some("42") }
536 /// # fn res() -> Result<&'static str, &'static str> { Ok("42") }
537 /// let _ = opt().map(|s| s.len());
538 /// let _ = res().map(|s| if s.len() == 42 { 10 } else { 20 });
539 /// let _ = res().map_err(|s| if s.len() == 42 { 10 } else { 20 });
541 #[clippy::version = "1.45.0"]
542 pub BIND_INSTEAD_OF_MAP,
544 "using `Option.and_then(|x| Some(y))`, which is more succinctly expressed as `map(|x| y)`"
547 declare_clippy_lint! {
549 /// Checks for usage of `_.filter(_).next()`.
551 /// ### Why is this bad?
552 /// Readability, this can be written more concisely as
557 /// # let vec = vec![1];
558 /// vec.iter().filter(|x| **x == 0).next();
563 /// # let vec = vec![1];
564 /// vec.iter().find(|x| **x == 0);
566 #[clippy::version = "pre 1.29.0"]
569 "using `filter(p).next()`, which is more succinctly expressed as `.find(p)`"
572 declare_clippy_lint! {
574 /// Checks for usage of `_.skip_while(condition).next()`.
576 /// ### Why is this bad?
577 /// Readability, this can be written more concisely as
578 /// `_.find(!condition)`.
582 /// # let vec = vec![1];
583 /// vec.iter().skip_while(|x| **x == 0).next();
588 /// # let vec = vec![1];
589 /// vec.iter().find(|x| **x != 0);
591 #[clippy::version = "1.42.0"]
594 "using `skip_while(p).next()`, which is more succinctly expressed as `.find(!p)`"
597 declare_clippy_lint! {
599 /// Checks for usage of `_.map(_).flatten(_)` on `Iterator` and `Option`
601 /// ### Why is this bad?
602 /// Readability, this can be written more concisely as
603 /// `_.flat_map(_)` for `Iterator` or `_.and_then(_)` for `Option`
607 /// let vec = vec![vec![1]];
608 /// let opt = Some(5);
610 /// vec.iter().map(|x| x.iter()).flatten();
611 /// opt.map(|x| Some(x * 2)).flatten();
616 /// # let vec = vec![vec![1]];
617 /// # let opt = Some(5);
618 /// vec.iter().flat_map(|x| x.iter());
619 /// opt.and_then(|x| Some(x * 2));
621 #[clippy::version = "1.31.0"]
624 "using combinations of `flatten` and `map` which can usually be written as a single method call"
627 declare_clippy_lint! {
629 /// Checks for usage of `_.filter(_).map(_)` that can be written more simply
630 /// as `filter_map(_)`.
632 /// ### Why is this bad?
633 /// Redundant code in the `filter` and `map` operations is poor style and
638 /// # #![allow(unused)]
640 /// .filter(|n| n.checked_add(1).is_some())
641 /// .map(|n| n.checked_add(1).unwrap());
646 /// # #[allow(unused)]
647 /// (0_i32..10).filter_map(|n| n.checked_add(1));
649 #[clippy::version = "1.51.0"]
650 pub MANUAL_FILTER_MAP,
652 "using `_.filter(_).map(_)` in a way that can be written more simply as `filter_map(_)`"
655 declare_clippy_lint! {
657 /// Checks for usage of `_.find(_).map(_)` that can be written more simply
658 /// as `find_map(_)`.
660 /// ### Why is this bad?
661 /// Redundant code in the `find` and `map` operations is poor style and
667 /// .find(|n| n.checked_add(1).is_some())
668 /// .map(|n| n.checked_add(1).unwrap());
673 /// (0_i32..10).find_map(|n| n.checked_add(1));
675 #[clippy::version = "1.51.0"]
678 "using `_.find(_).map(_)` in a way that can be written more simply as `find_map(_)`"
681 declare_clippy_lint! {
683 /// Checks for usage of `_.filter_map(_).next()`.
685 /// ### Why is this bad?
686 /// Readability, this can be written more concisely as
691 /// (0..3).filter_map(|x| if x == 2 { Some(x) } else { None }).next();
693 /// Can be written as
696 /// (0..3).find_map(|x| if x == 2 { Some(x) } else { None });
698 #[clippy::version = "1.36.0"]
701 "using combination of `filter_map` and `next` which can usually be written as a single method call"
704 declare_clippy_lint! {
706 /// Checks for usage of `flat_map(|x| x)`.
708 /// ### Why is this bad?
709 /// Readability, this can be written more concisely by using `flatten`.
713 /// # let iter = vec![vec![0]].into_iter();
714 /// iter.flat_map(|x| x);
716 /// Can be written as
718 /// # let iter = vec![vec![0]].into_iter();
721 #[clippy::version = "1.39.0"]
722 pub FLAT_MAP_IDENTITY,
724 "call to `flat_map` where `flatten` is sufficient"
727 declare_clippy_lint! {
729 /// Checks for an iterator or string search (such as `find()`,
730 /// `position()`, or `rposition()`) followed by a call to `is_some()` or `is_none()`.
732 /// ### Why is this bad?
733 /// Readability, this can be written more concisely as:
734 /// * `_.any(_)`, or `_.contains(_)` for `is_some()`,
735 /// * `!_.any(_)`, or `!_.contains(_)` for `is_none()`.
739 /// # #![allow(unused)]
740 /// let vec = vec![1];
741 /// vec.iter().find(|x| **x == 0).is_some();
743 /// "hello world".find("world").is_none();
748 /// let vec = vec![1];
749 /// vec.iter().any(|x| *x == 0);
751 /// # #[allow(unused)]
752 /// !"hello world".contains("world");
754 #[clippy::version = "pre 1.29.0"]
757 "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()`)"
760 declare_clippy_lint! {
762 /// Checks for usage of `.chars().next()` on a `str` to check
763 /// if it starts with a given char.
765 /// ### Why is this bad?
766 /// Readability, this can be written more concisely as
767 /// `_.starts_with(_)`.
771 /// let name = "foo";
772 /// if name.chars().next() == Some('_') {};
777 /// let name = "foo";
778 /// if name.starts_with('_') {};
780 #[clippy::version = "pre 1.29.0"]
783 "using `.chars().next()` to check if a string starts with a char"
786 declare_clippy_lint! {
788 /// Checks for calls to `.or(foo(..))`, `.unwrap_or(foo(..))`,
789 /// etc., and suggests to use `or_else`, `unwrap_or_else`, etc., or
790 /// `unwrap_or_default` instead.
792 /// ### Why is this bad?
793 /// The function will always be called and potentially
794 /// allocate an object acting as the default.
796 /// ### Known problems
797 /// If the function has side-effects, not calling it will
798 /// change the semantic of the program, but you shouldn't rely on that anyway.
802 /// # let foo = Some(String::new());
803 /// foo.unwrap_or(String::new());
808 /// # let foo = Some(String::new());
809 /// foo.unwrap_or_else(String::new);
813 /// # let foo = Some(String::new());
814 /// foo.unwrap_or_default();
816 #[clippy::version = "pre 1.29.0"]
819 "using any `*or` method with a function call, which suggests `*or_else`"
822 declare_clippy_lint! {
824 /// Checks for `.or(…).unwrap()` calls to Options and Results.
826 /// ### Why is this bad?
827 /// You should use `.unwrap_or(…)` instead for clarity.
831 /// # let fallback = "fallback";
833 /// # type Error = &'static str;
834 /// # let result: Result<&str, Error> = Err("error");
835 /// let value = result.or::<Error>(Ok(fallback)).unwrap();
838 /// # let option: Option<&str> = None;
839 /// let value = option.or(Some(fallback)).unwrap();
843 /// # let fallback = "fallback";
845 /// # let result: Result<&str, &str> = Err("error");
846 /// let value = result.unwrap_or(fallback);
849 /// # let option: Option<&str> = None;
850 /// let value = option.unwrap_or(fallback);
852 #[clippy::version = "1.61.0"]
855 "checks for `.or(…).unwrap()` calls to Options and Results."
858 declare_clippy_lint! {
860 /// Checks for calls to `.expect(&format!(...))`, `.expect(foo(..))`,
861 /// etc., and suggests to use `unwrap_or_else` instead
863 /// ### Why is this bad?
864 /// The function will always be called.
866 /// ### Known problems
867 /// If the function has side-effects, not calling it will
868 /// change the semantics of the program, but you shouldn't rely on that anyway.
872 /// # let foo = Some(String::new());
873 /// # let err_code = "418";
874 /// # let err_msg = "I'm a teapot";
875 /// foo.expect(&format!("Err {}: {}", err_code, err_msg));
879 /// # let foo = Some(String::new());
880 /// foo.expect(format!("Err {}: {}", err_code, err_msg).as_str());
885 /// # let foo = Some(String::new());
886 /// # let err_code = "418";
887 /// # let err_msg = "I'm a teapot";
888 /// foo.unwrap_or_else(|| panic!("Err {}: {}", err_code, err_msg));
890 #[clippy::version = "pre 1.29.0"]
893 "using any `expect` method with a function call"
896 declare_clippy_lint! {
898 /// Checks for usage of `.clone()` on a `Copy` type.
900 /// ### Why is this bad?
901 /// The only reason `Copy` types implement `Clone` is for
902 /// generics, not for using the `clone` method on a concrete type.
908 #[clippy::version = "pre 1.29.0"]
911 "using `clone` on a `Copy` type"
914 declare_clippy_lint! {
916 /// Checks for usage of `.clone()` on a ref-counted pointer,
917 /// (`Rc`, `Arc`, `rc::Weak`, or `sync::Weak`), and suggests calling Clone via unified
918 /// function syntax instead (e.g., `Rc::clone(foo)`).
920 /// ### Why is this bad?
921 /// Calling '.clone()' on an Rc, Arc, or Weak
922 /// can obscure the fact that only the pointer is being cloned, not the underlying
927 /// # use std::rc::Rc;
928 /// let x = Rc::new(1);
935 /// # use std::rc::Rc;
936 /// # let x = Rc::new(1);
939 #[clippy::version = "pre 1.29.0"]
940 pub CLONE_ON_REF_PTR,
942 "using 'clone' on a ref-counted pointer"
945 declare_clippy_lint! {
947 /// Checks for usage of `.clone()` on an `&&T`.
949 /// ### Why is this bad?
950 /// Cloning an `&&T` copies the inner `&T`, instead of
951 /// cloning the underlying `T`.
958 /// let z = y.clone();
959 /// println!("{:p} {:p}", *y, z); // prints out the same pointer
962 #[clippy::version = "pre 1.29.0"]
963 pub CLONE_DOUBLE_REF,
965 "using `clone` on `&&T`"
968 declare_clippy_lint! {
970 /// Checks for usage of `.to_string()` on an `&&T` where
971 /// `T` implements `ToString` directly (like `&&str` or `&&String`).
973 /// ### Why is this bad?
974 /// This bypasses the specialized implementation of
975 /// `ToString` and instead goes through the more expensive string formatting
980 /// // Generic implementation for `T: Display` is used (slow)
981 /// ["foo", "bar"].iter().map(|s| s.to_string());
983 /// // OK, the specialized impl is used
984 /// ["foo", "bar"].iter().map(|&s| s.to_string());
986 #[clippy::version = "1.40.0"]
987 pub INEFFICIENT_TO_STRING,
989 "using `to_string` on `&&T` where `T: ToString`"
992 declare_clippy_lint! {
994 /// Checks for `new` not returning a type that contains `Self`.
996 /// ### Why is this bad?
997 /// As a convention, `new` methods are used to make a new
998 /// instance of a type.
1001 /// In an impl block:
1004 /// # struct NotAFoo;
1006 /// fn new() -> NotAFoo {
1014 /// struct Bar(Foo);
1016 /// // Bad. The type name must contain `Self`
1017 /// fn new() -> Bar {
1025 /// # struct FooError;
1027 /// // Good. Return type contains `Self`
1028 /// fn new() -> Result<Foo, FooError> {
1034 /// Or in a trait definition:
1036 /// pub trait Trait {
1037 /// // Bad. The type name must contain `Self`
1043 /// pub trait Trait {
1044 /// // Good. Return type contains `Self`
1045 /// fn new() -> Self;
1048 #[clippy::version = "pre 1.29.0"]
1049 pub NEW_RET_NO_SELF,
1051 "not returning type containing `Self` in a `new` method"
1054 declare_clippy_lint! {
1055 /// ### What it does
1056 /// Checks for string methods that receive a single-character
1057 /// `str` as an argument, e.g., `_.split("x")`.
1059 /// ### Why is this bad?
1060 /// Performing these methods using a `char` is faster than
1063 /// ### Known problems
1064 /// Does not catch multi-byte unicode characters.
1075 #[clippy::version = "pre 1.29.0"]
1076 pub SINGLE_CHAR_PATTERN,
1078 "using a single-character str where a char could be used, e.g., `_.split(\"x\")`"
1081 declare_clippy_lint! {
1082 /// ### What it does
1083 /// Checks for calling `.step_by(0)` on iterators which panics.
1085 /// ### Why is this bad?
1086 /// This very much looks like an oversight. Use `panic!()` instead if you
1087 /// actually intend to panic.
1090 /// ```rust,should_panic
1091 /// for x in (0..100).step_by(0) {
1095 #[clippy::version = "pre 1.29.0"]
1096 pub ITERATOR_STEP_BY_ZERO,
1098 "using `Iterator::step_by(0)`, which will panic at runtime"
1101 declare_clippy_lint! {
1102 /// ### What it does
1103 /// Checks for indirect collection of populated `Option`
1105 /// ### Why is this bad?
1106 /// `Option` is like a collection of 0-1 things, so `flatten`
1107 /// automatically does this without suspicious-looking `unwrap` calls.
1111 /// let _ = std::iter::empty::<Option<i32>>().filter(Option::is_some).map(Option::unwrap);
1115 /// let _ = std::iter::empty::<Option<i32>>().flatten();
1117 #[clippy::version = "1.53.0"]
1118 pub OPTION_FILTER_MAP,
1120 "filtering `Option` for `Some` then force-unwrapping, which can be one type-safe operation"
1123 declare_clippy_lint! {
1124 /// ### What it does
1125 /// Checks for the use of `iter.nth(0)`.
1127 /// ### Why is this bad?
1128 /// `iter.next()` is equivalent to
1129 /// `iter.nth(0)`, as they both consume the next element,
1130 /// but is more readable.
1134 /// # use std::collections::HashSet;
1135 /// # let mut s = HashSet::new();
1137 /// let x = s.iter().nth(0);
1142 /// # use std::collections::HashSet;
1143 /// # let mut s = HashSet::new();
1145 /// let x = s.iter().next();
1147 #[clippy::version = "1.42.0"]
1150 "replace `iter.nth(0)` with `iter.next()`"
1153 declare_clippy_lint! {
1154 /// ### What it does
1155 /// Checks for use of `.iter().nth()` (and the related
1156 /// `.iter_mut().nth()`) on standard library types with *O*(1) element access.
1158 /// ### Why is this bad?
1159 /// `.get()` and `.get_mut()` are more efficient and more
1164 /// let some_vec = vec![0, 1, 2, 3];
1165 /// let bad_vec = some_vec.iter().nth(3);
1166 /// let bad_slice = &some_vec[..].iter().nth(3);
1168 /// The correct use would be:
1170 /// let some_vec = vec![0, 1, 2, 3];
1171 /// let bad_vec = some_vec.get(3);
1172 /// let bad_slice = &some_vec[..].get(3);
1174 #[clippy::version = "pre 1.29.0"]
1177 "using `.iter().nth()` on a standard library type with O(1) element access"
1180 declare_clippy_lint! {
1181 /// ### What it does
1182 /// Checks for use of `.skip(x).next()` on iterators.
1184 /// ### Why is this bad?
1185 /// `.nth(x)` is cleaner
1189 /// let some_vec = vec![0, 1, 2, 3];
1190 /// let bad_vec = some_vec.iter().skip(3).next();
1191 /// let bad_slice = &some_vec[..].iter().skip(3).next();
1193 /// The correct use would be:
1195 /// let some_vec = vec![0, 1, 2, 3];
1196 /// let bad_vec = some_vec.iter().nth(3);
1197 /// let bad_slice = &some_vec[..].iter().nth(3);
1199 #[clippy::version = "pre 1.29.0"]
1202 "using `.skip(x).next()` on an iterator"
1205 declare_clippy_lint! {
1206 /// ### What it does
1207 /// Checks for use of `.drain(..)` on `Vec` and `VecDeque` for iteration.
1209 /// ### Why is this bad?
1210 /// `.into_iter()` is simpler with better performance.
1214 /// # use std::collections::HashSet;
1215 /// let mut foo = vec![0, 1, 2, 3];
1216 /// let bar: HashSet<usize> = foo.drain(..).collect();
1220 /// # use std::collections::HashSet;
1221 /// let foo = vec![0, 1, 2, 3];
1222 /// let bar: HashSet<usize> = foo.into_iter().collect();
1224 #[clippy::version = "1.61.0"]
1225 pub ITER_WITH_DRAIN,
1227 "replace `.drain(..)` with `.into_iter()`"
1230 declare_clippy_lint! {
1231 /// ### What it does
1232 /// Checks for using `x.get(x.len() - 1)` instead of
1235 /// ### Why is this bad?
1236 /// Using `x.last()` is easier to read and has the same
1239 /// Note that using `x[x.len() - 1]` is semantically different from
1240 /// `x.last()`. Indexing into the array will panic on out-of-bounds
1241 /// accesses, while `x.get()` and `x.last()` will return `None`.
1243 /// There is another lint (get_unwrap) that covers the case of using
1244 /// `x.get(index).unwrap()` instead of `x[index]`.
1248 /// let x = vec![2, 3, 5];
1249 /// let last_element = x.get(x.len() - 1);
1254 /// let x = vec![2, 3, 5];
1255 /// let last_element = x.last();
1257 #[clippy::version = "1.37.0"]
1258 pub GET_LAST_WITH_LEN,
1260 "Using `x.get(x.len() - 1)` when `x.last()` is correct and simpler"
1263 declare_clippy_lint! {
1264 /// ### What it does
1265 /// Checks for use of `.get().unwrap()` (or
1266 /// `.get_mut().unwrap`) on a standard library type which implements `Index`
1268 /// ### Why is this bad?
1269 /// Using the Index trait (`[]`) is more clear and more
1272 /// ### Known problems
1273 /// Not a replacement for error handling: Using either
1274 /// `.unwrap()` or the Index trait (`[]`) carries the risk of causing a `panic`
1275 /// if the value being accessed is `None`. If the use of `.get().unwrap()` is a
1276 /// temporary placeholder for dealing with the `Option` type, then this does
1277 /// not mitigate the need for error handling. If there is a chance that `.get()`
1278 /// will be `None` in your program, then it is advisable that the `None` case
1279 /// is handled in a future refactor instead of using `.unwrap()` or the Index
1284 /// let mut some_vec = vec![0, 1, 2, 3];
1285 /// let last = some_vec.get(3).unwrap();
1286 /// *some_vec.get_mut(0).unwrap() = 1;
1288 /// The correct use would be:
1290 /// let mut some_vec = vec![0, 1, 2, 3];
1291 /// let last = some_vec[3];
1292 /// some_vec[0] = 1;
1294 #[clippy::version = "pre 1.29.0"]
1297 "using `.get().unwrap()` or `.get_mut().unwrap()` when using `[]` would work instead"
1300 declare_clippy_lint! {
1301 /// ### What it does
1302 /// Checks for occurrences where one vector gets extended instead of append
1304 /// ### Why is this bad?
1305 /// Using `append` instead of `extend` is more concise and faster
1309 /// let mut a = vec![1, 2, 3];
1310 /// let mut b = vec![4, 5, 6];
1312 /// a.extend(b.drain(..));
1317 /// let mut a = vec![1, 2, 3];
1318 /// let mut b = vec![4, 5, 6];
1320 /// a.append(&mut b);
1322 #[clippy::version = "1.55.0"]
1323 pub EXTEND_WITH_DRAIN,
1325 "using vec.append(&mut vec) to move the full range of a vector to another"
1328 declare_clippy_lint! {
1329 /// ### What it does
1330 /// Checks for the use of `.extend(s.chars())` where s is a
1331 /// `&str` or `String`.
1333 /// ### Why is this bad?
1334 /// `.push_str(s)` is clearer
1338 /// let abc = "abc";
1339 /// let def = String::from("def");
1340 /// let mut s = String::new();
1341 /// s.extend(abc.chars());
1342 /// s.extend(def.chars());
1344 /// The correct use would be:
1346 /// let abc = "abc";
1347 /// let def = String::from("def");
1348 /// let mut s = String::new();
1349 /// s.push_str(abc);
1350 /// s.push_str(&def);
1352 #[clippy::version = "pre 1.29.0"]
1353 pub STRING_EXTEND_CHARS,
1355 "using `x.extend(s.chars())` where s is a `&str` or `String`"
1358 declare_clippy_lint! {
1359 /// ### What it does
1360 /// Checks for the use of `.cloned().collect()` on slice to
1363 /// ### Why is this bad?
1364 /// `.to_vec()` is clearer
1368 /// let s = [1, 2, 3, 4, 5];
1369 /// let s2: Vec<isize> = s[..].iter().cloned().collect();
1371 /// The better use would be:
1373 /// let s = [1, 2, 3, 4, 5];
1374 /// let s2: Vec<isize> = s.to_vec();
1376 #[clippy::version = "pre 1.29.0"]
1377 pub ITER_CLONED_COLLECT,
1379 "using `.cloned().collect()` on slice to create a `Vec`"
1382 declare_clippy_lint! {
1383 /// ### What it does
1384 /// Checks for usage of `_.chars().last()` or
1385 /// `_.chars().next_back()` on a `str` to check if it ends with a given char.
1387 /// ### Why is this bad?
1388 /// Readability, this can be written more concisely as
1389 /// `_.ends_with(_)`.
1393 /// # let name = "_";
1394 /// name.chars().last() == Some('_') || name.chars().next_back() == Some('-');
1399 /// # let name = "_";
1400 /// name.ends_with('_') || name.ends_with('-');
1402 #[clippy::version = "pre 1.29.0"]
1405 "using `.chars().last()` or `.chars().next_back()` to check if a string ends with a char"
1408 declare_clippy_lint! {
1409 /// ### What it does
1410 /// Checks for usage of `.as_ref()` or `.as_mut()` where the
1411 /// types before and after the call are the same.
1413 /// ### Why is this bad?
1414 /// The call is unnecessary.
1418 /// # fn do_stuff(x: &[i32]) {}
1419 /// let x: &[i32] = &[1, 2, 3, 4, 5];
1420 /// do_stuff(x.as_ref());
1422 /// The correct use would be:
1424 /// # fn do_stuff(x: &[i32]) {}
1425 /// let x: &[i32] = &[1, 2, 3, 4, 5];
1428 #[clippy::version = "pre 1.29.0"]
1431 "using `as_ref` where the types before and after the call are the same"
1434 declare_clippy_lint! {
1435 /// ### What it does
1436 /// Checks for using `fold` when a more succinct alternative exists.
1437 /// Specifically, this checks for `fold`s which could be replaced by `any`, `all`,
1438 /// `sum` or `product`.
1440 /// ### Why is this bad?
1445 /// # #[allow(unused)]
1446 /// (0..3).fold(false, |acc, x| acc || x > 2);
1451 /// (0..3).any(|x| x > 2);
1453 #[clippy::version = "pre 1.29.0"]
1454 pub UNNECESSARY_FOLD,
1456 "using `fold` when a more succinct alternative exists"
1459 declare_clippy_lint! {
1460 /// ### What it does
1461 /// Checks for `filter_map` calls that could be replaced by `filter` or `map`.
1462 /// More specifically it checks if the closure provided is only performing one of the
1463 /// filter or map operations and suggests the appropriate option.
1465 /// ### Why is this bad?
1466 /// Complexity. The intent is also clearer if only a single
1467 /// operation is being performed.
1471 /// let _ = (0..3).filter_map(|x| if x > 2 { Some(x) } else { None });
1473 /// // As there is no transformation of the argument this could be written as:
1474 /// let _ = (0..3).filter(|&x| x > 2);
1478 /// let _ = (0..4).filter_map(|x| Some(x + 1));
1480 /// // As there is no conditional check on the argument this could be written as:
1481 /// let _ = (0..4).map(|x| x + 1);
1483 #[clippy::version = "1.31.0"]
1484 pub UNNECESSARY_FILTER_MAP,
1486 "using `filter_map` when a more succinct alternative exists"
1489 declare_clippy_lint! {
1490 /// ### What it does
1491 /// Checks for `find_map` calls that could be replaced by `find` or `map`. More
1492 /// specifically it checks if the closure provided is only performing one of the
1493 /// find or map operations and suggests the appropriate option.
1495 /// ### Why is this bad?
1496 /// Complexity. The intent is also clearer if only a single
1497 /// operation is being performed.
1501 /// let _ = (0..3).find_map(|x| if x > 2 { Some(x) } else { None });
1503 /// // As there is no transformation of the argument this could be written as:
1504 /// let _ = (0..3).find(|&x| x > 2);
1508 /// let _ = (0..4).find_map(|x| Some(x + 1));
1510 /// // As there is no conditional check on the argument this could be written as:
1511 /// let _ = (0..4).map(|x| x + 1).next();
1513 #[clippy::version = "1.61.0"]
1514 pub UNNECESSARY_FIND_MAP,
1516 "using `find_map` when a more succinct alternative exists"
1519 declare_clippy_lint! {
1520 /// ### What it does
1521 /// Checks for `into_iter` calls on references which should be replaced by `iter`
1524 /// ### Why is this bad?
1525 /// Readability. Calling `into_iter` on a reference will not move out its
1526 /// content into the resulting iterator, which is confusing. It is better just call `iter` or
1527 /// `iter_mut` directly.
1531 /// # let vec = vec![3, 4, 5];
1532 /// (&vec).into_iter();
1537 /// # let vec = vec![3, 4, 5];
1540 #[clippy::version = "1.32.0"]
1541 pub INTO_ITER_ON_REF,
1543 "using `.into_iter()` on a reference"
1546 declare_clippy_lint! {
1547 /// ### What it does
1548 /// Checks for calls to `map` followed by a `count`.
1550 /// ### Why is this bad?
1551 /// It looks suspicious. Maybe `map` was confused with `filter`.
1552 /// If the `map` call is intentional, this should be rewritten
1553 /// using `inspect`. Or, if you intend to drive the iterator to
1554 /// completion, you can just use `for_each` instead.
1558 /// let _ = (0..3).map(|x| x + 2).count();
1560 #[clippy::version = "1.39.0"]
1563 "suspicious usage of map"
1566 declare_clippy_lint! {
1567 /// ### What it does
1568 /// Checks for `MaybeUninit::uninit().assume_init()`.
1570 /// ### Why is this bad?
1571 /// For most types, this is undefined behavior.
1573 /// ### Known problems
1574 /// For now, we accept empty tuples and tuples / arrays
1575 /// of `MaybeUninit`. There may be other types that allow uninitialized
1576 /// data, but those are not yet rigorously defined.
1580 /// // Beware the UB
1581 /// use std::mem::MaybeUninit;
1583 /// let _: usize = unsafe { MaybeUninit::uninit().assume_init() };
1586 /// Note that the following is OK:
1589 /// use std::mem::MaybeUninit;
1591 /// let _: [MaybeUninit<bool>; 5] = unsafe {
1592 /// MaybeUninit::uninit().assume_init()
1595 #[clippy::version = "1.39.0"]
1596 pub UNINIT_ASSUMED_INIT,
1598 "`MaybeUninit::uninit().assume_init()`"
1601 declare_clippy_lint! {
1602 /// ### What it does
1603 /// Checks for `.checked_add/sub(x).unwrap_or(MAX/MIN)`.
1605 /// ### Why is this bad?
1606 /// These can be written simply with `saturating_add/sub` methods.
1610 /// # let y: u32 = 0;
1611 /// # let x: u32 = 100;
1612 /// let add = x.checked_add(y).unwrap_or(u32::MAX);
1613 /// let sub = x.checked_sub(y).unwrap_or(u32::MIN);
1616 /// can be written using dedicated methods for saturating addition/subtraction as:
1619 /// # let y: u32 = 0;
1620 /// # let x: u32 = 100;
1621 /// let add = x.saturating_add(y);
1622 /// let sub = x.saturating_sub(y);
1624 #[clippy::version = "1.39.0"]
1625 pub MANUAL_SATURATING_ARITHMETIC,
1627 "`.checked_add/sub(x).unwrap_or(MAX/MIN)`"
1630 declare_clippy_lint! {
1631 /// ### What it does
1632 /// Checks for `offset(_)`, `wrapping_`{`add`, `sub`}, etc. on raw pointers to
1633 /// zero-sized types
1635 /// ### Why is this bad?
1636 /// This is a no-op, and likely unintended
1640 /// unsafe { (&() as *const ()).offset(1) };
1642 #[clippy::version = "1.41.0"]
1645 "Check for offset calculations on raw pointers to zero-sized types"
1648 declare_clippy_lint! {
1649 /// ### What it does
1650 /// Checks for `FileType::is_file()`.
1652 /// ### Why is this bad?
1653 /// When people testing a file type with `FileType::is_file`
1654 /// they are testing whether a path is something they can get bytes from. But
1655 /// `is_file` doesn't cover special file types in unix-like systems, and doesn't cover
1656 /// symlink in windows. Using `!FileType::is_dir()` is a better way to that intention.
1661 /// let metadata = std::fs::metadata("foo.txt")?;
1662 /// let filetype = metadata.file_type();
1664 /// if filetype.is_file() {
1667 /// # Ok::<_, std::io::Error>(())
1671 /// should be written as:
1675 /// let metadata = std::fs::metadata("foo.txt")?;
1676 /// let filetype = metadata.file_type();
1678 /// if !filetype.is_dir() {
1681 /// # Ok::<_, std::io::Error>(())
1684 #[clippy::version = "1.42.0"]
1685 pub FILETYPE_IS_FILE,
1687 "`FileType::is_file` is not recommended to test for readable file type"
1690 declare_clippy_lint! {
1691 /// ### What it does
1692 /// Checks for usage of `_.as_ref().map(Deref::deref)` or it's aliases (such as String::as_str).
1694 /// ### Why is this bad?
1695 /// Readability, this can be written more concisely as
1700 /// # let opt = Some("".to_string());
1701 /// opt.as_ref().map(String::as_str)
1704 /// Can be written as
1706 /// # let opt = Some("".to_string());
1710 #[clippy::version = "1.42.0"]
1711 pub OPTION_AS_REF_DEREF,
1713 "using `as_ref().map(Deref::deref)`, which is more succinctly expressed as `as_deref()`"
1716 declare_clippy_lint! {
1717 /// ### What it does
1718 /// Checks for usage of `iter().next()` on a Slice or an Array
1720 /// ### Why is this bad?
1721 /// These can be shortened into `.get()`
1725 /// # let a = [1, 2, 3];
1726 /// # let b = vec![1, 2, 3];
1727 /// a[2..].iter().next();
1728 /// b.iter().next();
1730 /// should be written as:
1732 /// # let a = [1, 2, 3];
1733 /// # let b = vec![1, 2, 3];
1737 #[clippy::version = "1.46.0"]
1738 pub ITER_NEXT_SLICE,
1740 "using `.iter().next()` on a sliced array, which can be shortened to just `.get()`"
1743 declare_clippy_lint! {
1744 /// ### What it does
1745 /// Warns when using `push_str`/`insert_str` with a single-character string literal
1746 /// where `push`/`insert` with a `char` would work fine.
1748 /// ### Why is this bad?
1749 /// It's less clear that we are pushing a single character.
1753 /// # let mut string = String::new();
1754 /// string.insert_str(0, "R");
1755 /// string.push_str("R");
1760 /// # let mut string = String::new();
1761 /// string.insert(0, 'R');
1762 /// string.push('R');
1764 #[clippy::version = "1.49.0"]
1765 pub SINGLE_CHAR_ADD_STR,
1767 "`push_str()` or `insert_str()` used with a single-character string literal as parameter"
1770 declare_clippy_lint! {
1771 /// ### What it does
1772 /// As the counterpart to `or_fun_call`, this lint looks for unnecessary
1773 /// lazily evaluated closures on `Option` and `Result`.
1775 /// This lint suggests changing the following functions, when eager evaluation results in
1777 /// - `unwrap_or_else` to `unwrap_or`
1778 /// - `and_then` to `and`
1779 /// - `or_else` to `or`
1780 /// - `get_or_insert_with` to `get_or_insert`
1781 /// - `ok_or_else` to `ok_or`
1783 /// ### Why is this bad?
1784 /// Using eager evaluation is shorter and simpler in some cases.
1786 /// ### Known problems
1787 /// It is possible, but not recommended for `Deref` and `Index` to have
1788 /// side effects. Eagerly evaluating them can change the semantics of the program.
1792 /// // example code where clippy issues a warning
1793 /// let opt: Option<u32> = None;
1795 /// opt.unwrap_or_else(|| 42);
1799 /// let opt: Option<u32> = None;
1801 /// opt.unwrap_or(42);
1803 #[clippy::version = "1.48.0"]
1804 pub UNNECESSARY_LAZY_EVALUATIONS,
1806 "using unnecessary lazy evaluation, which can be replaced with simpler eager evaluation"
1809 declare_clippy_lint! {
1810 /// ### What it does
1811 /// Checks for usage of `_.map(_).collect::<Result<(), _>()`.
1813 /// ### Why is this bad?
1814 /// Using `try_for_each` instead is more readable and idiomatic.
1818 /// (0..3).map(|t| Err(t)).collect::<Result<(), _>>();
1822 /// (0..3).try_for_each(|t| Err(t));
1824 #[clippy::version = "1.49.0"]
1825 pub MAP_COLLECT_RESULT_UNIT,
1827 "using `.map(_).collect::<Result<(),_>()`, which can be replaced with `try_for_each`"
1830 declare_clippy_lint! {
1831 /// ### What it does
1832 /// Checks for `from_iter()` function calls on types that implement the `FromIterator`
1835 /// ### Why is this bad?
1836 /// It is recommended style to use collect. See
1837 /// [FromIterator documentation](https://doc.rust-lang.org/std/iter/trait.FromIterator.html)
1841 /// let five_fives = std::iter::repeat(5).take(5);
1843 /// let v = Vec::from_iter(five_fives);
1845 /// assert_eq!(v, vec![5, 5, 5, 5, 5]);
1849 /// let five_fives = std::iter::repeat(5).take(5);
1851 /// let v: Vec<i32> = five_fives.collect();
1853 /// assert_eq!(v, vec![5, 5, 5, 5, 5]);
1855 #[clippy::version = "1.49.0"]
1856 pub FROM_ITER_INSTEAD_OF_COLLECT,
1858 "use `.collect()` instead of `::from_iter()`"
1861 declare_clippy_lint! {
1862 /// ### What it does
1863 /// Checks for usage of `inspect().for_each()`.
1865 /// ### Why is this bad?
1866 /// It is the same as performing the computation
1867 /// inside `inspect` at the beginning of the closure in `for_each`.
1871 /// [1,2,3,4,5].iter()
1872 /// .inspect(|&x| println!("inspect the number: {}", x))
1873 /// .for_each(|&x| {
1874 /// assert!(x >= 0);
1877 /// Can be written as
1879 /// [1,2,3,4,5].iter()
1880 /// .for_each(|&x| {
1881 /// println!("inspect the number: {}", x);
1882 /// assert!(x >= 0);
1885 #[clippy::version = "1.51.0"]
1886 pub INSPECT_FOR_EACH,
1888 "using `.inspect().for_each()`, which can be replaced with `.for_each()`"
1891 declare_clippy_lint! {
1892 /// ### What it does
1893 /// Checks for usage of `filter_map(|x| x)`.
1895 /// ### Why is this bad?
1896 /// Readability, this can be written more concisely by using `flatten`.
1900 /// # let iter = vec![Some(1)].into_iter();
1901 /// iter.filter_map(|x| x);
1905 /// # let iter = vec![Some(1)].into_iter();
1908 #[clippy::version = "1.52.0"]
1909 pub FILTER_MAP_IDENTITY,
1911 "call to `filter_map` where `flatten` is sufficient"
1914 declare_clippy_lint! {
1915 /// ### What it does
1916 /// Checks for instances of `map(f)` where `f` is the identity function.
1918 /// ### Why is this bad?
1919 /// It can be written more concisely without the call to `map`.
1923 /// let x = [1, 2, 3];
1924 /// let y: Vec<_> = x.iter().map(|x| x).map(|x| 2*x).collect();
1928 /// let x = [1, 2, 3];
1929 /// let y: Vec<_> = x.iter().map(|x| 2*x).collect();
1931 #[clippy::version = "1.47.0"]
1934 "using iterator.map(|x| x)"
1937 declare_clippy_lint! {
1938 /// ### What it does
1939 /// Checks for the use of `.bytes().nth()`.
1941 /// ### Why is this bad?
1942 /// `.as_bytes().get()` is more efficient and more
1947 /// # #[allow(unused)]
1948 /// "Hello".bytes().nth(3);
1953 /// # #[allow(unused)]
1954 /// "Hello".as_bytes().get(3);
1956 #[clippy::version = "1.52.0"]
1959 "replace `.bytes().nth()` with `.as_bytes().get()`"
1962 declare_clippy_lint! {
1963 /// ### What it does
1964 /// Checks for the usage of `_.to_owned()`, `vec.to_vec()`, or similar when calling `_.clone()` would be clearer.
1966 /// ### Why is this bad?
1967 /// These methods do the same thing as `_.clone()` but may be confusing as
1968 /// to why we are calling `to_vec` on something that is already a `Vec` or calling `to_owned` on something that is already owned.
1972 /// let a = vec![1, 2, 3];
1973 /// let b = a.to_vec();
1974 /// let c = a.to_owned();
1978 /// let a = vec![1, 2, 3];
1979 /// let b = a.clone();
1980 /// let c = a.clone();
1982 #[clippy::version = "1.52.0"]
1985 "implicitly cloning a value by invoking a function on its dereferenced type"
1988 declare_clippy_lint! {
1989 /// ### What it does
1990 /// Checks for the use of `.iter().count()`.
1992 /// ### Why is this bad?
1993 /// `.len()` is more efficient and more
1998 /// # #![allow(unused)]
1999 /// let some_vec = vec![0, 1, 2, 3];
2001 /// some_vec.iter().count();
2002 /// &some_vec[..].iter().count();
2007 /// let some_vec = vec![0, 1, 2, 3];
2010 /// &some_vec[..].len();
2012 #[clippy::version = "1.52.0"]
2015 "replace `.iter().count()` with `.len()`"
2018 declare_clippy_lint! {
2019 /// ### What it does
2020 /// Checks for calls to [`splitn`]
2021 /// (https://doc.rust-lang.org/std/primitive.str.html#method.splitn) and
2022 /// related functions with either zero or one splits.
2024 /// ### Why is this bad?
2025 /// These calls don't actually split the value and are
2026 /// likely to be intended as a different number.
2031 /// for x in s.splitn(1, ":") {
2039 /// for x in s.splitn(2, ":") {
2043 #[clippy::version = "1.54.0"]
2044 pub SUSPICIOUS_SPLITN,
2046 "checks for `.splitn(0, ..)` and `.splitn(1, ..)`"
2049 declare_clippy_lint! {
2050 /// ### What it does
2051 /// Checks for manual implementations of `str::repeat`
2053 /// ### Why is this bad?
2054 /// These are both harder to read, as well as less performant.
2058 /// let x: String = std::iter::repeat('x').take(10).collect();
2063 /// let x: String = "x".repeat(10);
2065 #[clippy::version = "1.54.0"]
2066 pub MANUAL_STR_REPEAT,
2068 "manual implementation of `str::repeat`"
2071 declare_clippy_lint! {
2072 /// ### What it does
2073 /// Checks for usages of `str::splitn(2, _)`
2075 /// ### Why is this bad?
2076 /// `split_once` is both clearer in intent and slightly more efficient.
2080 /// let s = "key=value=add";
2081 /// let (key, value) = s.splitn(2, '=').next_tuple()?;
2082 /// let value = s.splitn(2, '=').nth(1)?;
2084 /// let mut parts = s.splitn(2, '=');
2085 /// let key = parts.next()?;
2086 /// let value = parts.next()?;
2091 /// let s = "key=value=add";
2092 /// let (key, value) = s.split_once('=')?;
2093 /// let value = s.split_once('=')?.1;
2095 /// let (key, value) = s.split_once('=')?;
2099 /// The multiple statement variant currently only detects `iter.next()?`/`iter.next().unwrap()`
2100 /// in two separate `let` statements that immediately follow the `splitn()`
2101 #[clippy::version = "1.57.0"]
2102 pub MANUAL_SPLIT_ONCE,
2104 "replace `.splitn(2, pat)` with `.split_once(pat)`"
2107 declare_clippy_lint! {
2108 /// ### What it does
2109 /// Checks for usages of `str::splitn` (or `str::rsplitn`) where using `str::split` would be the same.
2110 /// ### Why is this bad?
2111 /// The function `split` is simpler and there is no performance difference in these cases, considering
2112 /// that both functions return a lazy iterator.
2115 /// let str = "key=value=add";
2116 /// let _ = str.splitn(3, '=').next().unwrap();
2121 /// let str = "key=value=add";
2122 /// let _ = str.split('=').next().unwrap();
2124 #[clippy::version = "1.59.0"]
2125 pub NEEDLESS_SPLITN,
2127 "usages of `str::splitn` that can be replaced with `str::split`"
2130 declare_clippy_lint! {
2131 /// ### What it does
2132 /// Checks for unnecessary calls to [`ToOwned::to_owned`](https://doc.rust-lang.org/std/borrow/trait.ToOwned.html#tymethod.to_owned)
2133 /// and other `to_owned`-like functions.
2135 /// ### Why is this bad?
2136 /// The unnecessary calls result in useless allocations.
2138 /// ### Known problems
2139 /// `unnecessary_to_owned` can falsely trigger if `IntoIterator::into_iter` is applied to an
2140 /// owned copy of a resource and the resource is later used mutably. See
2141 /// [#8148](https://github.com/rust-lang/rust-clippy/issues/8148).
2145 /// let path = std::path::Path::new("x");
2146 /// foo(&path.to_string_lossy().to_string());
2147 /// fn foo(s: &str) {}
2151 /// let path = std::path::Path::new("x");
2152 /// foo(&path.to_string_lossy());
2153 /// fn foo(s: &str) {}
2155 #[clippy::version = "1.59.0"]
2156 pub UNNECESSARY_TO_OWNED,
2158 "unnecessary calls to `to_owned`-like functions"
2161 declare_clippy_lint! {
2162 /// ### What it does
2163 /// Checks for use of `.collect::<Vec<String>>().join("")` on iterators.
2165 /// ### Why is this bad?
2166 /// `.collect::<String>()` is more concise and might be more performant
2170 /// let vector = vec!["hello", "world"];
2171 /// let output = vector.iter().map(|item| item.to_uppercase()).collect::<Vec<String>>().join("");
2172 /// println!("{}", output);
2174 /// The correct use would be:
2176 /// let vector = vec!["hello", "world"];
2177 /// let output = vector.iter().map(|item| item.to_uppercase()).collect::<String>();
2178 /// println!("{}", output);
2180 /// ### Known problems
2181 /// While `.collect::<String>()` is sometimes more performant, there are cases where
2182 /// using `.collect::<String>()` over `.collect::<Vec<String>>().join("")`
2183 /// will prevent loop unrolling and will result in a negative performance impact.
2185 /// Additionally, differences have been observed between aarch64 and x86_64 assembly output,
2186 /// with aarch64 tending to producing faster assembly in more cases when using `.collect::<String>()`
2187 #[clippy::version = "1.61.0"]
2188 pub UNNECESSARY_JOIN,
2190 "using `.collect::<Vec<String>>().join(\"\")` on an iterator"
2193 declare_clippy_lint! {
2194 /// ### What it does
2195 /// Checks for no-op uses of `Option::{as_deref, as_deref_mut}`,
2196 /// for example, `Option<&T>::as_deref()` returns the same type.
2198 /// ### Why is this bad?
2199 /// Redundant code and improving readability.
2203 /// let a = Some(&1);
2204 /// let b = a.as_deref(); // goes from Option<&i32> to Option<&i32>
2209 /// let a = Some(&1);
2212 #[clippy::version = "1.57.0"]
2213 pub NEEDLESS_OPTION_AS_DEREF,
2215 "no-op use of `deref` or `deref_mut` method to `Option`."
2218 declare_clippy_lint! {
2219 /// ### What it does
2220 /// Finds usages of [`char::is_digit`](https://doc.rust-lang.org/stable/std/primitive.char.html#method.is_digit) that
2221 /// can be replaced with [`is_ascii_digit`](https://doc.rust-lang.org/stable/std/primitive.char.html#method.is_ascii_digit) or
2222 /// [`is_ascii_hexdigit`](https://doc.rust-lang.org/stable/std/primitive.char.html#method.is_ascii_hexdigit).
2224 /// ### Why is this bad?
2225 /// `is_digit(..)` is slower and requires specifying the radix.
2229 /// let c: char = '6';
2235 /// let c: char = '6';
2236 /// c.is_ascii_digit();
2237 /// c.is_ascii_hexdigit();
2239 #[clippy::version = "1.62.0"]
2240 pub IS_DIGIT_ASCII_RADIX,
2242 "use of `char::is_digit(..)` with literal radix of 10 or 16"
2245 declare_clippy_lint! {
2246 /// ### What it does
2247 /// Checks for calling `take` function after `as_ref`.
2249 /// ### Why is this bad?
2250 /// Redundant code. `take` writes `None` to its argument.
2251 /// In this case the modification is useless as it's a temporary that cannot be read from afterwards.
2255 /// let x = Some(3);
2256 /// x.as_ref().take();
2260 /// let x = Some(3);
2263 #[clippy::version = "1.62.0"]
2264 pub NEEDLESS_OPTION_TAKE,
2266 "using `.as_ref().take()` on a temporary value"
2269 declare_clippy_lint! {
2270 /// ### What it does
2271 /// Checks for `replace` statements which have no effect.
2273 /// ### Why is this bad?
2274 /// It's either a mistake or confusing.
2278 /// "1234".replace("12", "12");
2279 /// "1234".replacen("12", "12", 1);
2281 #[clippy::version = "1.63.0"]
2282 pub NO_EFFECT_REPLACE,
2284 "replace with no effect"
2287 declare_clippy_lint! {
2288 /// ### What it does
2289 /// Checks for usages of `.then_some(..).unwrap_or(..)`
2291 /// ### Why is this bad?
2292 /// This can be written more clearly with `if .. else ..`
2295 /// This lint currently only looks for usages of
2296 /// `.then_some(..).unwrap_or(..)`, but will be expanded
2297 /// to account for similar patterns.
2302 /// x.then_some("a").unwrap_or("b");
2307 /// if x { "a" } else { "b" };
2309 #[clippy::version = "1.64.0"]
2310 pub OBFUSCATED_IF_ELSE,
2312 "use of `.then_some(..).unwrap_or(..)` can be written \
2313 more clearly with `if .. else ..`"
2316 declare_clippy_lint! {
2317 /// ### What it does
2319 /// Checks for calls to `iter`, `iter_mut` or `into_iter` on collections containing a single item
2321 /// ### Why is this bad?
2323 /// It is simpler to use the once function from the standard library:
2328 /// let a = [123].iter();
2329 /// let b = Some(123).into_iter();
2334 /// let a = iter::once(&123);
2335 /// let b = iter::once(123);
2338 /// ### Known problems
2340 /// The type of the resulting iterator might become incompatible with its usage
2341 #[clippy::version = "1.64.0"]
2342 pub ITER_ON_SINGLE_ITEMS,
2344 "Iterator for array of length 1"
2347 declare_clippy_lint! {
2348 /// ### What it does
2350 /// Checks for calls to `iter`, `iter_mut` or `into_iter` on empty collections
2352 /// ### Why is this bad?
2354 /// It is simpler to use the empty function from the standard library:
2359 /// use std::{slice, option};
2360 /// let a: slice::Iter<i32> = [].iter();
2361 /// let f: option::IntoIter<i32> = None.into_iter();
2366 /// let a: iter::Empty<i32> = iter::empty();
2367 /// let b: iter::Empty<i32> = iter::empty();
2370 /// ### Known problems
2372 /// The type of the resulting iterator might become incompatible with its usage
2373 #[clippy::version = "1.64.0"]
2374 pub ITER_ON_EMPTY_COLLECTIONS,
2376 "Iterator for empty array"
2379 declare_clippy_lint! {
2380 /// ### What it does
2381 /// Checks for naive byte counts
2383 /// ### Why is this bad?
2384 /// The [`bytecount`](https://crates.io/crates/bytecount)
2385 /// crate has methods to count your bytes faster, especially for large slices.
2387 /// ### Known problems
2388 /// If you have predominantly small slices, the
2389 /// `bytecount::count(..)` method may actually be slower. However, if you can
2390 /// ensure that less than 2³²-1 matches arise, the `naive_count_32(..)` can be
2391 /// faster in those cases.
2395 /// # let vec = vec![1_u8];
2396 /// let count = vec.iter().filter(|x| **x == 0u8).count();
2401 /// # let vec = vec![1_u8];
2402 /// let count = bytecount::count(&vec, 0u8);
2404 #[clippy::version = "pre 1.29.0"]
2405 pub NAIVE_BYTECOUNT,
2407 "use of naive `<slice>.filter(|&x| x == y).count()` to count byte values"
2410 declare_clippy_lint! {
2411 /// ### What it does
2412 /// It checks for `str::bytes().count()` and suggests replacing it with
2415 /// ### Why is this bad?
2416 /// `str::bytes().count()` is longer and may not be as performant as using
2421 /// "hello".bytes().count();
2422 /// String::from("hello").bytes().count();
2427 /// String::from("hello").len();
2429 #[clippy::version = "1.62.0"]
2430 pub BYTES_COUNT_TO_LEN,
2432 "Using `bytes().count()` when `len()` performs the same functionality"
2435 declare_clippy_lint! {
2436 /// ### What it does
2437 /// Checks for calls to `ends_with` with possible file extensions
2438 /// and suggests to use a case-insensitive approach instead.
2440 /// ### Why is this bad?
2441 /// `ends_with` is case-sensitive and may not detect files with a valid extension.
2445 /// fn is_rust_file(filename: &str) -> bool {
2446 /// filename.ends_with(".rs")
2451 /// fn is_rust_file(filename: &str) -> bool {
2452 /// let filename = std::path::Path::new(filename);
2453 /// filename.extension()
2454 /// .map_or(false, |ext| ext.eq_ignore_ascii_case("rs"))
2457 #[clippy::version = "1.51.0"]
2458 pub CASE_SENSITIVE_FILE_EXTENSION_COMPARISONS,
2460 "Checks for calls to ends_with with case-sensitive file extensions"
2463 declare_clippy_lint! {
2464 /// ### What it does
2465 /// Checks for using `x.get(0)` instead of
2468 /// ### Why is this bad?
2469 /// Using `x.first()` is easier to read and has the same
2474 /// let x = vec![2, 3, 5];
2475 /// let first_element = x.get(0);
2480 /// let x = vec![2, 3, 5];
2481 /// let first_element = x.first();
2483 #[clippy::version = "1.63.0"]
2486 "Using `x.get(0)` when `x.first()` is simpler"
2489 declare_clippy_lint! {
2490 /// ### What it does
2492 /// Finds patterns that reimplement `Option::ok_or`.
2494 /// ### Why is this bad?
2496 /// Concise code helps focusing on behavior instead of boilerplate.
2500 /// let foo: Option<i32> = None;
2501 /// foo.map_or(Err("error"), |v| Ok(v));
2506 /// let foo: Option<i32> = None;
2507 /// foo.ok_or("error");
2509 #[clippy::version = "1.49.0"]
2512 "finds patterns that can be encoded more concisely with `Option::ok_or`"
2515 declare_clippy_lint! {
2516 /// ### What it does
2517 /// Checks for usage of `map(|x| x.clone())` or
2518 /// dereferencing closures for `Copy` types, on `Iterator` or `Option`,
2519 /// and suggests `cloned()` or `copied()` instead
2521 /// ### Why is this bad?
2522 /// Readability, this can be written more concisely
2526 /// let x = vec![42, 43];
2527 /// let y = x.iter();
2528 /// let z = y.map(|i| *i);
2531 /// The correct use would be:
2534 /// let x = vec![42, 43];
2535 /// let y = x.iter();
2536 /// let z = y.cloned();
2538 #[clippy::version = "pre 1.29.0"]
2541 "using `iterator.map(|x| x.clone())`, or dereferencing closures for `Copy` types"
2544 pub struct Methods {
2545 avoid_breaking_exported_api: bool,
2546 msrv: Option<RustcVersion>,
2547 allow_expect_in_tests: bool,
2548 allow_unwrap_in_tests: bool,
2554 avoid_breaking_exported_api: bool,
2555 msrv: Option<RustcVersion>,
2556 allow_expect_in_tests: bool,
2557 allow_unwrap_in_tests: bool,
2560 avoid_breaking_exported_api,
2562 allow_expect_in_tests,
2563 allow_unwrap_in_tests,
2568 impl_lint_pass!(Methods => [
2571 SHOULD_IMPLEMENT_TRAIT,
2572 WRONG_SELF_CONVENTION,
2574 UNWRAP_OR_ELSE_DEFAULT,
2576 RESULT_MAP_OR_INTO_OPTION,
2578 BIND_INSTEAD_OF_MAP,
2587 ITER_OVEREAGER_CLONED,
2588 CLONED_INSTEAD_OF_COPIED,
2590 INEFFICIENT_TO_STRING,
2592 SINGLE_CHAR_PATTERN,
2593 SINGLE_CHAR_ADD_STR,
2597 FILTER_MAP_IDENTITY,
2605 ITERATOR_STEP_BY_ZERO,
2614 STRING_EXTEND_CHARS,
2615 ITER_CLONED_COLLECT,
2619 UNNECESSARY_FILTER_MAP,
2620 UNNECESSARY_FIND_MAP,
2623 UNINIT_ASSUMED_INIT,
2624 MANUAL_SATURATING_ARITHMETIC,
2627 OPTION_AS_REF_DEREF,
2628 UNNECESSARY_LAZY_EVALUATIONS,
2629 MAP_COLLECT_RESULT_UNIT,
2630 FROM_ITER_INSTEAD_OF_COLLECT,
2638 UNNECESSARY_TO_OWNED,
2641 NEEDLESS_OPTION_AS_DEREF,
2642 IS_DIGIT_ASCII_RADIX,
2643 NEEDLESS_OPTION_TAKE,
2646 ITER_ON_SINGLE_ITEMS,
2647 ITER_ON_EMPTY_COLLECTIONS,
2650 CASE_SENSITIVE_FILE_EXTENSION_COMPARISONS,
2656 /// Extracts a method call name, args, and `Span` of the method name.
2657 fn method_call<'tcx>(recv: &'tcx hir::Expr<'tcx>) -> Option<(&'tcx str, &'tcx [hir::Expr<'tcx>], Span)> {
2658 if let ExprKind::MethodCall(path, args, _) = recv.kind {
2659 if !args.iter().any(|e| e.span.from_expansion()) {
2660 let name = path.ident.name.as_str();
2661 return Some((name, args, path.ident.span));
2667 impl<'tcx> LateLintPass<'tcx> for Methods {
2668 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) {
2669 if expr.span.from_expansion() {
2673 self.check_methods(cx, expr);
2676 hir::ExprKind::Call(func, args) => {
2677 from_iter_instead_of_collect::check(cx, expr, args, func);
2679 hir::ExprKind::MethodCall(method_call, args, _) => {
2680 let method_span = method_call.ident.span;
2681 or_fun_call::check(cx, expr, method_span, method_call.ident.as_str(), args);
2682 expect_fun_call::check(cx, expr, method_span, method_call.ident.as_str(), args);
2683 clone_on_copy::check(cx, expr, method_call.ident.name, args);
2684 clone_on_ref_ptr::check(cx, expr, method_call.ident.name, args);
2685 inefficient_to_string::check(cx, expr, method_call.ident.name, args);
2686 single_char_add_str::check(cx, expr, args);
2687 into_iter_on_ref::check(cx, expr, method_span, method_call.ident.name, args);
2688 single_char_pattern::check(cx, expr, method_call.ident.name, args);
2689 unnecessary_to_owned::check(cx, expr, method_call.ident.name, args, self.msrv);
2691 hir::ExprKind::Binary(op, lhs, rhs) if op.node == hir::BinOpKind::Eq || op.node == hir::BinOpKind::Ne => {
2692 let mut info = BinaryExprInfo {
2696 eq: op.node == hir::BinOpKind::Eq,
2698 lint_binary_expr_with_method_call(cx, &mut info);
2704 #[allow(clippy::too_many_lines)]
2705 fn check_impl_item(&mut self, cx: &LateContext<'tcx>, impl_item: &'tcx hir::ImplItem<'_>) {
2706 if in_external_macro(cx.sess(), impl_item.span) {
2709 let name = impl_item.ident.name.as_str();
2710 let parent = cx.tcx.hir().get_parent_item(impl_item.hir_id());
2711 let item = cx.tcx.hir().expect_item(parent);
2712 let self_ty = cx.tcx.type_of(item.def_id);
2714 let implements_trait = matches!(item.kind, hir::ItemKind::Impl(hir::Impl { of_trait: Some(_), .. }));
2716 if let hir::ImplItemKind::Fn(ref sig, id) = impl_item.kind;
2717 if let Some(first_arg) = iter_input_pats(sig.decl, cx.tcx.hir().body(id)).next();
2719 let method_sig = cx.tcx.fn_sig(impl_item.def_id);
2720 let method_sig = cx.tcx.erase_late_bound_regions(method_sig);
2722 let first_arg_ty = method_sig.inputs().iter().next();
2724 // check conventions w.r.t. conversion method names and predicates
2725 if let Some(first_arg_ty) = first_arg_ty;
2728 // if this impl block implements a trait, lint in trait definition instead
2729 if !implements_trait && cx.access_levels.is_exported(impl_item.def_id) {
2730 // check missing trait implementations
2731 for method_config in &TRAIT_METHODS {
2732 if name == method_config.method_name &&
2733 sig.decl.inputs.len() == method_config.param_count &&
2734 method_config.output_type.matches(&sig.decl.output) &&
2735 method_config.self_kind.matches(cx, self_ty, *first_arg_ty) &&
2736 fn_header_equals(method_config.fn_header, sig.header) &&
2737 method_config.lifetime_param_cond(impl_item)
2741 SHOULD_IMPLEMENT_TRAIT,
2744 "method `{}` can be confused for the standard trait method `{}::{}`",
2745 method_config.method_name,
2746 method_config.trait_name,
2747 method_config.method_name
2751 "consider implementing the trait `{}` or choosing a less ambiguous method name",
2752 method_config.trait_name
2759 if sig.decl.implicit_self.has_implicit_self()
2760 && !(self.avoid_breaking_exported_api
2761 && cx.access_levels.is_exported(impl_item.def_id))
2763 wrong_self_convention::check(
2776 // if this impl block implements a trait, lint in trait definition instead
2777 if implements_trait {
2781 if let hir::ImplItemKind::Fn(_, _) = impl_item.kind {
2782 let ret_ty = return_ty(cx, impl_item.hir_id());
2784 // walk the return type and check for Self (this does not check associated types)
2785 if let Some(self_adt) = self_ty.ty_adt_def() {
2786 if contains_adt_constructor(ret_ty, self_adt) {
2789 } else if contains_ty(ret_ty, self_ty) {
2793 // if return type is impl trait, check the associated types
2794 if let ty::Opaque(def_id, _) = *ret_ty.kind() {
2795 // one of the associated types must be Self
2796 for &(predicate, _span) in cx.tcx.explicit_item_bounds(def_id) {
2797 if let ty::PredicateKind::Projection(projection_predicate) = predicate.kind().skip_binder() {
2798 let assoc_ty = match projection_predicate.term {
2799 ty::Term::Ty(ty) => ty,
2800 ty::Term::Const(_c) => continue,
2802 // walk the associated type and check for Self
2803 if let Some(self_adt) = self_ty.ty_adt_def() {
2804 if contains_adt_constructor(assoc_ty, self_adt) {
2807 } else if contains_ty(assoc_ty, self_ty) {
2814 if name == "new" && ret_ty != self_ty {
2819 "methods called `new` usually return `Self`",
2825 fn check_trait_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx TraitItem<'_>) {
2826 if in_external_macro(cx.tcx.sess, item.span) {
2831 if let TraitItemKind::Fn(ref sig, _) = item.kind;
2832 if sig.decl.implicit_self.has_implicit_self();
2833 if let Some(first_arg_ty) = sig.decl.inputs.iter().next();
2836 let first_arg_span = first_arg_ty.span;
2837 let first_arg_ty = hir_ty_to_ty(cx.tcx, first_arg_ty);
2838 let self_ty = TraitRef::identity(cx.tcx, item.def_id.to_def_id()).self_ty().skip_binder();
2839 wrong_self_convention::check(
2841 item.ident.name.as_str(),
2852 if item.ident.name == sym::new;
2853 if let TraitItemKind::Fn(_, _) = item.kind;
2854 let ret_ty = return_ty(cx, item.hir_id());
2855 let self_ty = TraitRef::identity(cx.tcx, item.def_id.to_def_id()).self_ty().skip_binder();
2856 if !contains_ty(ret_ty, self_ty);
2863 "methods called `new` usually return `Self`",
2869 extract_msrv_attr!(LateContext);
2873 #[allow(clippy::too_many_lines)]
2874 fn check_methods<'tcx>(&self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
2875 if let Some((name, [recv, args @ ..], span)) = method_call(expr) {
2876 match (name, args) {
2877 ("add" | "offset" | "sub" | "wrapping_offset" | "wrapping_add" | "wrapping_sub", [_arg]) => {
2878 zst_offset::check(cx, expr, recv);
2880 ("and_then", [arg]) => {
2881 let biom_option_linted = bind_instead_of_map::OptionAndThenSome::check(cx, expr, recv, arg);
2882 let biom_result_linted = bind_instead_of_map::ResultAndThenOk::check(cx, expr, recv, arg);
2883 if !biom_option_linted && !biom_result_linted {
2884 unnecessary_lazy_eval::check(cx, expr, recv, arg, "and");
2887 ("as_deref" | "as_deref_mut", []) => {
2888 needless_option_as_deref::check(cx, expr, recv, name);
2890 ("as_mut", []) => useless_asref::check(cx, expr, "as_mut", recv),
2891 ("as_ref", []) => useless_asref::check(cx, expr, "as_ref", recv),
2892 ("assume_init", []) => uninit_assumed_init::check(cx, expr, recv),
2893 ("cloned", []) => cloned_instead_of_copied::check(cx, expr, recv, span, self.msrv),
2894 ("collect", []) => match method_call(recv) {
2895 Some((name @ ("cloned" | "copied"), [recv2], _)) => {
2896 iter_cloned_collect::check(cx, name, expr, recv2);
2898 Some(("map", [m_recv, m_arg], _)) => {
2899 map_collect_result_unit::check(cx, expr, m_recv, m_arg, recv);
2901 Some(("take", [take_self_arg, take_arg], _)) => {
2902 if meets_msrv(self.msrv, msrvs::STR_REPEAT) {
2903 manual_str_repeat::check(cx, expr, recv, take_self_arg, take_arg);
2908 ("count", []) if is_trait_method(cx, expr, sym::Iterator) => match method_call(recv) {
2909 Some(("cloned", [recv2], _)) => iter_overeager_cloned::check(cx, expr, recv, recv2, true, false),
2910 Some((name2 @ ("into_iter" | "iter" | "iter_mut"), [recv2], _)) => {
2911 iter_count::check(cx, expr, recv2, name2);
2913 Some(("map", [_, arg], _)) => suspicious_map::check(cx, expr, recv, arg),
2914 Some(("filter", [recv2, arg], _)) => bytecount::check(cx, expr, recv2, arg),
2915 Some(("bytes", [recv2], _)) => bytes_count_to_len::check(cx, expr, recv, recv2),
2918 ("drain", [arg]) => {
2919 iter_with_drain::check(cx, expr, recv, span, arg);
2921 ("ends_with", [arg]) => {
2922 if let ExprKind::MethodCall(_, _, span) = expr.kind {
2923 case_sensitive_file_extension_comparisons::check(cx, expr, span, recv, arg);
2926 ("expect", [_]) => match method_call(recv) {
2927 Some(("ok", [recv], _)) => ok_expect::check(cx, expr, recv),
2928 Some(("err", [recv], err_span)) => err_expect::check(cx, expr, recv, self.msrv, span, err_span),
2929 _ => expect_used::check(cx, expr, recv, false, self.allow_expect_in_tests),
2931 ("expect_err", [_]) => expect_used::check(cx, expr, recv, true, self.allow_expect_in_tests),
2932 ("extend", [arg]) => {
2933 string_extend_chars::check(cx, expr, recv, arg);
2934 extend_with_drain::check(cx, expr, recv, arg);
2936 ("filter_map", [arg]) => {
2937 unnecessary_filter_map::check(cx, expr, arg, name);
2938 filter_map_identity::check(cx, expr, arg, span);
2940 ("find_map", [arg]) => {
2941 unnecessary_filter_map::check(cx, expr, arg, name);
2943 ("flat_map", [arg]) => {
2944 flat_map_identity::check(cx, expr, arg, span);
2945 flat_map_option::check(cx, expr, arg, span);
2947 ("flatten", []) => match method_call(recv) {
2948 Some(("map", [recv, map_arg], map_span)) => map_flatten::check(cx, expr, recv, map_arg, map_span),
2949 Some(("cloned", [recv2], _)) => iter_overeager_cloned::check(cx, expr, recv, recv2, false, true),
2952 ("fold", [init, acc]) => unnecessary_fold::check(cx, expr, init, acc, span),
2953 ("for_each", [_]) => {
2954 if let Some(("inspect", [_, _], span2)) = method_call(recv) {
2955 inspect_for_each::check(cx, expr, span2);
2959 get_first::check(cx, expr, recv, arg);
2960 get_last_with_len::check(cx, expr, recv, arg);
2962 ("get_or_insert_with", [arg]) => unnecessary_lazy_eval::check(cx, expr, recv, arg, "get_or_insert"),
2963 ("is_file", []) => filetype_is_file::check(cx, expr, recv),
2964 ("is_digit", [radix]) => is_digit_ascii_radix::check(cx, expr, recv, radix, self.msrv),
2965 ("is_none", []) => check_is_some_is_none(cx, expr, recv, false),
2966 ("is_some", []) => check_is_some_is_none(cx, expr, recv, true),
2967 ("iter" | "iter_mut" | "into_iter", []) => {
2968 iter_on_single_or_empty_collections::check(cx, expr, name, recv);
2970 ("join", [join_arg]) => {
2971 if let Some(("collect", _, span)) = method_call(recv) {
2972 unnecessary_join::check(cx, expr, recv, join_arg, span);
2975 ("last", []) | ("skip", [_]) => {
2976 if let Some((name2, [recv2, args2 @ ..], _span2)) = method_call(recv) {
2977 if let ("cloned", []) = (name2, args2) {
2978 iter_overeager_cloned::check(cx, expr, recv, recv2, false, false);
2982 (name @ ("map" | "map_err"), [m_arg]) => {
2984 map_clone::check(cx, expr, recv, m_arg, self.msrv);
2986 if let Some((name, [recv2, args @ ..], span2)) = method_call(recv) {
2987 match (name, args) {
2988 ("as_mut", []) => option_as_ref_deref::check(cx, expr, recv2, m_arg, true, self.msrv),
2989 ("as_ref", []) => option_as_ref_deref::check(cx, expr, recv2, m_arg, false, self.msrv),
2990 ("filter", [f_arg]) => {
2991 filter_map::check(cx, expr, recv2, f_arg, span2, recv, m_arg, span, false);
2993 ("find", [f_arg]) => {
2994 filter_map::check(cx, expr, recv2, f_arg, span2, recv, m_arg, span, true);
2999 map_identity::check(cx, expr, recv, m_arg, name, span);
3001 ("map_or", [def, map]) => {
3002 option_map_or_none::check(cx, expr, recv, def, map);
3003 manual_ok_or::check(cx, expr, recv, def, map);
3006 if let Some((name2, [recv2, args2 @ ..], _)) = method_call(recv) {
3007 match (name2, args2) {
3008 ("cloned", []) => iter_overeager_cloned::check(cx, expr, recv, recv2, false, false),
3009 ("filter", [arg]) => filter_next::check(cx, expr, recv2, arg),
3010 ("filter_map", [arg]) => filter_map_next::check(cx, expr, recv2, arg, self.msrv),
3011 ("iter", []) => iter_next_slice::check(cx, expr, recv2),
3012 ("skip", [arg]) => iter_skip_next::check(cx, expr, recv2, arg),
3013 ("skip_while", [_]) => skip_while_next::check(cx, expr),
3018 ("nth", [n_arg]) => match method_call(recv) {
3019 Some(("bytes", [recv2], _)) => bytes_nth::check(cx, expr, recv2, n_arg),
3020 Some(("cloned", [recv2], _)) => iter_overeager_cloned::check(cx, expr, recv, recv2, false, false),
3021 Some(("iter", [recv2], _)) => iter_nth::check(cx, expr, recv2, recv, n_arg, false),
3022 Some(("iter_mut", [recv2], _)) => iter_nth::check(cx, expr, recv2, recv, n_arg, true),
3023 _ => iter_nth_zero::check(cx, expr, recv, n_arg),
3025 ("ok_or_else", [arg]) => unnecessary_lazy_eval::check(cx, expr, recv, arg, "ok_or"),
3026 ("or_else", [arg]) => {
3027 if !bind_instead_of_map::ResultOrElseErrInfo::check(cx, expr, recv, arg) {
3028 unnecessary_lazy_eval::check(cx, expr, recv, arg, "or");
3031 ("splitn" | "rsplitn", [count_arg, pat_arg]) => {
3032 if let Some((Constant::Int(count), _)) = constant(cx, cx.typeck_results(), count_arg) {
3033 suspicious_splitn::check(cx, name, expr, recv, count);
3034 str_splitn::check(cx, name, expr, recv, pat_arg, count, self.msrv);
3037 ("splitn_mut" | "rsplitn_mut", [count_arg, _]) => {
3038 if let Some((Constant::Int(count), _)) = constant(cx, cx.typeck_results(), count_arg) {
3039 suspicious_splitn::check(cx, name, expr, recv, count);
3042 ("step_by", [arg]) => iterator_step_by_zero::check(cx, expr, arg),
3043 ("take", [_arg]) => {
3044 if let Some((name2, [recv2, args2 @ ..], _span2)) = method_call(recv) {
3045 if let ("cloned", []) = (name2, args2) {
3046 iter_overeager_cloned::check(cx, expr, recv, recv2, false, false);
3050 ("take", []) => needless_option_take::check(cx, expr, recv),
3051 ("then", [arg]) => {
3052 if !meets_msrv(self.msrv, msrvs::BOOL_THEN_SOME) {
3055 unnecessary_lazy_eval::check(cx, expr, recv, arg, "then_some");
3057 ("to_os_string" | "to_owned" | "to_path_buf" | "to_vec", []) => {
3058 implicit_clone::check(cx, name, expr, recv);
3061 match method_call(recv) {
3062 Some(("get", [recv, get_arg], _)) => {
3063 get_unwrap::check(cx, expr, recv, get_arg, false);
3065 Some(("get_mut", [recv, get_arg], _)) => {
3066 get_unwrap::check(cx, expr, recv, get_arg, true);
3068 Some(("or", [recv, or_arg], or_span)) => {
3069 or_then_unwrap::check(cx, expr, recv, or_arg, or_span);
3073 unwrap_used::check(cx, expr, recv, false, self.allow_unwrap_in_tests);
3075 ("unwrap_err", []) => unwrap_used::check(cx, expr, recv, true, self.allow_unwrap_in_tests),
3076 ("unwrap_or", [u_arg]) => match method_call(recv) {
3077 Some((arith @ ("checked_add" | "checked_sub" | "checked_mul"), [lhs, rhs], _)) => {
3078 manual_saturating_arithmetic::check(cx, expr, lhs, rhs, u_arg, &arith["checked_".len()..]);
3080 Some(("map", [m_recv, m_arg], span)) => {
3081 option_map_unwrap_or::check(cx, expr, m_recv, m_arg, recv, u_arg, span);
3083 Some(("then_some", [t_recv, t_arg], _)) => {
3084 obfuscated_if_else::check(cx, expr, t_recv, t_arg, u_arg);
3088 ("unwrap_or_else", [u_arg]) => match method_call(recv) {
3089 Some(("map", [recv, map_arg], _))
3090 if map_unwrap_or::check(cx, expr, recv, map_arg, u_arg, self.msrv) => {},
3092 unwrap_or_else_default::check(cx, expr, recv, u_arg);
3093 unnecessary_lazy_eval::check(cx, expr, recv, u_arg, "unwrap_or");
3096 ("replace" | "replacen", [arg1, arg2] | [arg1, arg2, _]) => {
3097 no_effect_replace::check(cx, expr, arg1, arg2);
3105 fn check_is_some_is_none(cx: &LateContext<'_>, expr: &Expr<'_>, recv: &Expr<'_>, is_some: bool) {
3106 if let Some((name @ ("find" | "position" | "rposition"), [f_recv, arg], span)) = method_call(recv) {
3107 search_is_some::check(cx, expr, name, is_some, f_recv, arg, recv, span);
3111 /// Used for `lint_binary_expr_with_method_call`.
3112 #[derive(Copy, Clone)]
3113 struct BinaryExprInfo<'a> {
3114 expr: &'a hir::Expr<'a>,
3115 chain: &'a hir::Expr<'a>,
3116 other: &'a hir::Expr<'a>,
3120 /// Checks for the `CHARS_NEXT_CMP` and `CHARS_LAST_CMP` lints.
3121 fn lint_binary_expr_with_method_call(cx: &LateContext<'_>, info: &mut BinaryExprInfo<'_>) {
3122 macro_rules! lint_with_both_lhs_and_rhs {
3123 ($func:expr, $cx:expr, $info:ident) => {
3124 if !$func($cx, $info) {
3125 ::std::mem::swap(&mut $info.chain, &mut $info.other);
3126 if $func($cx, $info) {
3133 lint_with_both_lhs_and_rhs!(chars_next_cmp::check, cx, info);
3134 lint_with_both_lhs_and_rhs!(chars_last_cmp::check, cx, info);
3135 lint_with_both_lhs_and_rhs!(chars_next_cmp_with_unwrap::check, cx, info);
3136 lint_with_both_lhs_and_rhs!(chars_last_cmp_with_unwrap::check, cx, info);
3139 const FN_HEADER: hir::FnHeader = hir::FnHeader {
3140 unsafety: hir::Unsafety::Normal,
3141 constness: hir::Constness::NotConst,
3142 asyncness: hir::IsAsync::NotAsync,
3143 abi: rustc_target::spec::abi::Abi::Rust,
3146 struct ShouldImplTraitCase {
3147 trait_name: &'static str,
3148 method_name: &'static str,
3150 fn_header: hir::FnHeader,
3151 // implicit self kind expected (none, self, &self, ...)
3152 self_kind: SelfKind,
3153 // checks against the output type
3154 output_type: OutType,
3155 // certain methods with explicit lifetimes can't implement the equivalent trait method
3156 lint_explicit_lifetime: bool,
3158 impl ShouldImplTraitCase {
3160 trait_name: &'static str,
3161 method_name: &'static str,
3163 fn_header: hir::FnHeader,
3164 self_kind: SelfKind,
3165 output_type: OutType,
3166 lint_explicit_lifetime: bool,
3167 ) -> ShouldImplTraitCase {
3168 ShouldImplTraitCase {
3175 lint_explicit_lifetime,
3179 fn lifetime_param_cond(&self, impl_item: &hir::ImplItem<'_>) -> bool {
3180 self.lint_explicit_lifetime
3181 || !impl_item.generics.params.iter().any(|p| {
3184 hir::GenericParamKind::Lifetime {
3185 kind: hir::LifetimeParamKind::Explicit
3193 const TRAIT_METHODS: [ShouldImplTraitCase; 30] = [
3194 ShouldImplTraitCase::new("std::ops::Add", "add", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3195 ShouldImplTraitCase::new("std::convert::AsMut", "as_mut", 1, FN_HEADER, SelfKind::RefMut, OutType::Ref, true),
3196 ShouldImplTraitCase::new("std::convert::AsRef", "as_ref", 1, FN_HEADER, SelfKind::Ref, OutType::Ref, true),
3197 ShouldImplTraitCase::new("std::ops::BitAnd", "bitand", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3198 ShouldImplTraitCase::new("std::ops::BitOr", "bitor", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3199 ShouldImplTraitCase::new("std::ops::BitXor", "bitxor", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3200 ShouldImplTraitCase::new("std::borrow::Borrow", "borrow", 1, FN_HEADER, SelfKind::Ref, OutType::Ref, true),
3201 ShouldImplTraitCase::new("std::borrow::BorrowMut", "borrow_mut", 1, FN_HEADER, SelfKind::RefMut, OutType::Ref, true),
3202 ShouldImplTraitCase::new("std::clone::Clone", "clone", 1, FN_HEADER, SelfKind::Ref, OutType::Any, true),
3203 ShouldImplTraitCase::new("std::cmp::Ord", "cmp", 2, FN_HEADER, SelfKind::Ref, OutType::Any, true),
3204 // FIXME: default doesn't work
3205 ShouldImplTraitCase::new("std::default::Default", "default", 0, FN_HEADER, SelfKind::No, OutType::Any, true),
3206 ShouldImplTraitCase::new("std::ops::Deref", "deref", 1, FN_HEADER, SelfKind::Ref, OutType::Ref, true),
3207 ShouldImplTraitCase::new("std::ops::DerefMut", "deref_mut", 1, FN_HEADER, SelfKind::RefMut, OutType::Ref, true),
3208 ShouldImplTraitCase::new("std::ops::Div", "div", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3209 ShouldImplTraitCase::new("std::ops::Drop", "drop", 1, FN_HEADER, SelfKind::RefMut, OutType::Unit, true),
3210 ShouldImplTraitCase::new("std::cmp::PartialEq", "eq", 2, FN_HEADER, SelfKind::Ref, OutType::Bool, true),
3211 ShouldImplTraitCase::new("std::iter::FromIterator", "from_iter", 1, FN_HEADER, SelfKind::No, OutType::Any, true),
3212 ShouldImplTraitCase::new("std::str::FromStr", "from_str", 1, FN_HEADER, SelfKind::No, OutType::Any, true),
3213 ShouldImplTraitCase::new("std::hash::Hash", "hash", 2, FN_HEADER, SelfKind::Ref, OutType::Unit, true),
3214 ShouldImplTraitCase::new("std::ops::Index", "index", 2, FN_HEADER, SelfKind::Ref, OutType::Ref, true),
3215 ShouldImplTraitCase::new("std::ops::IndexMut", "index_mut", 2, FN_HEADER, SelfKind::RefMut, OutType::Ref, true),
3216 ShouldImplTraitCase::new("std::iter::IntoIterator", "into_iter", 1, FN_HEADER, SelfKind::Value, OutType::Any, true),
3217 ShouldImplTraitCase::new("std::ops::Mul", "mul", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3218 ShouldImplTraitCase::new("std::ops::Neg", "neg", 1, FN_HEADER, SelfKind::Value, OutType::Any, true),
3219 ShouldImplTraitCase::new("std::iter::Iterator", "next", 1, FN_HEADER, SelfKind::RefMut, OutType::Any, false),
3220 ShouldImplTraitCase::new("std::ops::Not", "not", 1, FN_HEADER, SelfKind::Value, OutType::Any, true),
3221 ShouldImplTraitCase::new("std::ops::Rem", "rem", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3222 ShouldImplTraitCase::new("std::ops::Shl", "shl", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3223 ShouldImplTraitCase::new("std::ops::Shr", "shr", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3224 ShouldImplTraitCase::new("std::ops::Sub", "sub", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3227 #[derive(Clone, Copy, PartialEq, Eq, Debug)]
3236 fn matches<'a>(self, cx: &LateContext<'a>, parent_ty: Ty<'a>, ty: Ty<'a>) -> bool {
3237 fn matches_value<'a>(cx: &LateContext<'a>, parent_ty: Ty<'a>, ty: Ty<'a>) -> bool {
3238 if ty == parent_ty {
3240 } else if ty.is_box() {
3241 ty.boxed_ty() == parent_ty
3242 } else if is_type_diagnostic_item(cx, ty, sym::Rc) || is_type_diagnostic_item(cx, ty, sym::Arc) {
3243 if let ty::Adt(_, substs) = ty.kind() {
3244 substs.types().next().map_or(false, |t| t == parent_ty)
3253 fn matches_ref<'a>(cx: &LateContext<'a>, mutability: hir::Mutability, parent_ty: Ty<'a>, ty: Ty<'a>) -> bool {
3254 if let ty::Ref(_, t, m) = *ty.kind() {
3255 return m == mutability && t == parent_ty;
3258 let trait_path = match mutability {
3259 hir::Mutability::Not => &paths::ASREF_TRAIT,
3260 hir::Mutability::Mut => &paths::ASMUT_TRAIT,
3263 let trait_def_id = match get_trait_def_id(cx, trait_path) {
3265 None => return false,
3267 implements_trait(cx, ty, trait_def_id, &[parent_ty.into()])
3270 fn matches_none<'a>(cx: &LateContext<'a>, parent_ty: Ty<'a>, ty: Ty<'a>) -> bool {
3271 !matches_value(cx, parent_ty, ty)
3272 && !matches_ref(cx, hir::Mutability::Not, parent_ty, ty)
3273 && !matches_ref(cx, hir::Mutability::Mut, parent_ty, ty)
3277 Self::Value => matches_value(cx, parent_ty, ty),
3278 Self::Ref => matches_ref(cx, hir::Mutability::Not, parent_ty, ty) || ty == parent_ty && is_copy(cx, ty),
3279 Self::RefMut => matches_ref(cx, hir::Mutability::Mut, parent_ty, ty),
3280 Self::No => matches_none(cx, parent_ty, ty),
3285 fn description(self) -> &'static str {
3287 Self::Value => "`self` by value",
3288 Self::Ref => "`self` by reference",
3289 Self::RefMut => "`self` by mutable reference",
3290 Self::No => "no `self`",
3295 #[derive(Clone, Copy)]
3304 fn matches(self, ty: &hir::FnRetTy<'_>) -> bool {
3305 let is_unit = |ty: &hir::Ty<'_>| matches!(ty.kind, hir::TyKind::Tup(&[]));
3307 (Self::Unit, &hir::FnRetTy::DefaultReturn(_)) => true,
3308 (Self::Unit, &hir::FnRetTy::Return(ty)) if is_unit(ty) => true,
3309 (Self::Bool, &hir::FnRetTy::Return(ty)) if is_bool(ty) => true,
3310 (Self::Any, &hir::FnRetTy::Return(ty)) if !is_unit(ty) => true,
3311 (Self::Ref, &hir::FnRetTy::Return(ty)) => matches!(ty.kind, hir::TyKind::Rptr(_, _)),
3317 fn is_bool(ty: &hir::Ty<'_>) -> bool {
3318 if let hir::TyKind::Path(QPath::Resolved(_, path)) = ty.kind {
3319 matches!(path.res, Res::PrimTy(PrimTy::Bool))
3325 fn fn_header_equals(expected: hir::FnHeader, actual: hir::FnHeader) -> bool {
3326 expected.constness == actual.constness
3327 && expected.unsafety == actual.unsafety
3328 && expected.asyncness == actual.asyncness