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;
45 mod manual_saturating_arithmetic;
46 mod manual_str_repeat;
47 mod map_collect_result_unit;
51 mod needless_option_as_deref;
52 mod needless_option_take;
53 mod no_effect_replace;
54 mod obfuscated_if_else;
56 mod option_as_ref_deref;
57 mod option_map_or_none;
58 mod option_map_unwrap_or;
62 mod single_char_add_str;
63 mod single_char_insert_string;
64 mod single_char_pattern;
65 mod single_char_push_string;
68 mod string_extend_chars;
70 mod suspicious_splitn;
71 mod uninit_assumed_init;
72 mod unnecessary_filter_map;
74 mod unnecessary_iter_cloned;
76 mod unnecessary_lazy_eval;
77 mod unnecessary_to_owned;
78 mod unwrap_or_else_default;
82 mod wrong_self_convention;
85 use bind_instead_of_map::BindInsteadOfMap;
86 use clippy_utils::consts::{constant, Constant};
87 use clippy_utils::diagnostics::{span_lint, span_lint_and_help};
88 use clippy_utils::ty::{contains_adt_constructor, contains_ty, implements_trait, is_copy, is_type_diagnostic_item};
90 contains_return, get_trait_def_id, is_trait_method, iter_input_pats, meets_msrv, msrvs, paths, return_ty,
92 use if_chain::if_chain;
94 use rustc_hir::def::Res;
95 use rustc_hir::{Expr, ExprKind, PrimTy, QPath, TraitItem, TraitItemKind};
96 use rustc_lint::{LateContext, LateLintPass, LintContext};
97 use rustc_middle::lint::in_external_macro;
98 use rustc_middle::ty::{self, TraitRef, Ty};
99 use rustc_semver::RustcVersion;
100 use rustc_session::{declare_tool_lint, impl_lint_pass};
101 use rustc_span::{sym, Span};
102 use rustc_typeck::hir_ty_to_ty;
104 declare_clippy_lint! {
106 /// Checks for usages of `cloned()` on an `Iterator` or `Option` where
107 /// `copied()` could be used instead.
109 /// ### Why is this bad?
110 /// `copied()` is better because it guarantees that the type being cloned
111 /// implements `Copy`.
115 /// [1, 2, 3].iter().cloned();
119 /// [1, 2, 3].iter().copied();
121 #[clippy::version = "1.53.0"]
122 pub CLONED_INSTEAD_OF_COPIED,
124 "used `cloned` where `copied` could be used instead"
127 declare_clippy_lint! {
129 /// Checks for usage of `_.cloned().<func>()` where call to `.cloned()` can be postponed.
131 /// ### Why is this bad?
132 /// It's often inefficient to clone all elements of an iterator, when eventually, only some
133 /// of them will be consumed.
135 /// ### Known Problems
136 /// This `lint` removes the side of effect of cloning items in the iterator.
137 /// A code that relies on that side-effect could fail.
141 /// # let vec = vec!["string".to_string()];
142 /// vec.iter().cloned().take(10);
143 /// vec.iter().cloned().last();
148 /// # let vec = vec!["string".to_string()];
149 /// vec.iter().take(10).cloned();
150 /// vec.iter().last().cloned();
152 #[clippy::version = "1.60.0"]
153 pub ITER_OVEREAGER_CLONED,
155 "using `cloned()` early with `Iterator::iter()` can lead to some performance inefficiencies"
158 declare_clippy_lint! {
160 /// Checks for usages of `Iterator::flat_map()` where `filter_map()` could be
163 /// ### Why is this bad?
164 /// When applicable, `filter_map()` is more clear since it shows that
165 /// `Option` is used to produce 0 or 1 items.
169 /// let nums: Vec<i32> = ["1", "2", "whee!"].iter().flat_map(|x| x.parse().ok()).collect();
173 /// let nums: Vec<i32> = ["1", "2", "whee!"].iter().filter_map(|x| x.parse().ok()).collect();
175 #[clippy::version = "1.53.0"]
178 "used `flat_map` where `filter_map` could be used instead"
181 declare_clippy_lint! {
183 /// Checks for `.unwrap()` or `.unwrap_err()` calls on `Result`s and `.unwrap()` call on `Option`s.
185 /// ### Why is this bad?
186 /// It is better to handle the `None` or `Err` case,
187 /// or at least call `.expect(_)` with a more helpful message. Still, for a lot of
188 /// quick-and-dirty code, `unwrap` is a good choice, which is why this lint is
189 /// `Allow` by default.
191 /// `result.unwrap()` will let the thread panic on `Err` values.
192 /// Normally, you want to implement more sophisticated error handling,
193 /// and propagate errors upwards with `?` operator.
195 /// Even if you want to panic on errors, not all `Error`s implement good
196 /// messages on display. Therefore, it may be beneficial to look at the places
197 /// where they may get displayed. Activate this lint to do just that.
201 /// # let option = Some(1);
202 /// # let result: Result<usize, ()> = Ok(1);
209 /// # let option = Some(1);
210 /// # let result: Result<usize, ()> = Ok(1);
211 /// option.expect("more helpful message");
212 /// result.expect("more helpful message");
215 /// If [expect_used](#expect_used) is enabled, instead:
217 /// # let option = Some(1);
218 /// # let result: Result<usize, ()> = Ok(1);
225 #[clippy::version = "1.45.0"]
228 "using `.unwrap()` on `Result` or `Option`, which should at least get a better message using `expect()`"
231 declare_clippy_lint! {
233 /// Checks for `.expect()` or `.expect_err()` calls on `Result`s and `.expect()` call on `Option`s.
235 /// ### Why is this bad?
236 /// Usually it is better to handle the `None` or `Err` case.
237 /// Still, for a lot of quick-and-dirty code, `expect` is a good choice, which is why
238 /// this lint is `Allow` by default.
240 /// `result.expect()` will let the thread panic on `Err`
241 /// values. Normally, you want to implement more sophisticated error handling,
242 /// and propagate errors upwards with `?` operator.
246 /// # let option = Some(1);
247 /// # let result: Result<usize, ()> = Ok(1);
248 /// option.expect("one");
249 /// result.expect("one");
254 /// # let option = Some(1);
255 /// # let result: Result<usize, ()> = Ok(1);
262 #[clippy::version = "1.45.0"]
265 "using `.expect()` on `Result` or `Option`, which might be better handled"
268 declare_clippy_lint! {
270 /// Checks for methods that should live in a trait
271 /// implementation of a `std` trait (see [llogiq's blog
272 /// post](http://llogiq.github.io/2015/07/30/traits.html) for further
273 /// information) instead of an inherent implementation.
275 /// ### Why is this bad?
276 /// Implementing the traits improve ergonomics for users of
277 /// the code, often with very little cost. Also people seeing a `mul(...)`
279 /// may expect `*` to work equally, so you should have good reason to disappoint
286 /// fn add(&self, other: &X) -> X {
292 #[clippy::version = "pre 1.29.0"]
293 pub SHOULD_IMPLEMENT_TRAIT,
295 "defining a method that should be implementing a std trait"
298 declare_clippy_lint! {
300 /// Checks for methods with certain name prefixes and which
301 /// doesn't match how self is taken. The actual rules are:
303 /// |Prefix |Postfix |`self` taken | `self` type |
304 /// |-------|------------|-------------------------------|--------------|
305 /// |`as_` | none |`&self` or `&mut self` | any |
306 /// |`from_`| none | none | any |
307 /// |`into_`| none |`self` | any |
308 /// |`is_` | none |`&mut self` or `&self` or none | any |
309 /// |`to_` | `_mut` |`&mut self` | any |
310 /// |`to_` | not `_mut` |`self` | `Copy` |
311 /// |`to_` | not `_mut` |`&self` | not `Copy` |
313 /// Note: Clippy doesn't trigger methods with `to_` prefix in:
314 /// - Traits definition.
315 /// Clippy can not tell if a type that implements a trait is `Copy` or not.
316 /// - Traits implementation, when `&self` is taken.
317 /// The method signature is controlled by the trait and often `&self` is required for all types that implement the trait
318 /// (see e.g. the `std::string::ToString` trait).
320 /// Clippy allows `Pin<&Self>` and `Pin<&mut Self>` if `&self` and `&mut self` is required.
322 /// Please find more info here:
323 /// https://rust-lang.github.io/api-guidelines/naming.html#ad-hoc-conversions-follow-as_-to_-into_-conventions-c-conv
325 /// ### Why is this bad?
326 /// Consistency breeds readability. If you follow the
327 /// conventions, your users won't be surprised that they, e.g., need to supply a
328 /// mutable reference to a `as_..` function.
334 /// fn as_str(self) -> &'static str {
340 #[clippy::version = "pre 1.29.0"]
341 pub WRONG_SELF_CONVENTION,
343 "defining a method named with an established prefix (like \"into_\") that takes `self` with the wrong convention"
346 declare_clippy_lint! {
348 /// Checks for usage of `ok().expect(..)`.
350 /// ### Why is this bad?
351 /// Because you usually call `expect()` on the `Result`
352 /// directly to get a better error message.
354 /// ### Known problems
355 /// The error type needs to implement `Debug`
359 /// # let x = Ok::<_, ()>(());
360 /// x.ok().expect("why did I do this again?");
365 /// # let x = Ok::<_, ()>(());
366 /// x.expect("why did I do this again?");
368 #[clippy::version = "pre 1.29.0"]
371 "using `ok().expect()`, which gives worse error messages than calling `expect` directly on the Result"
374 declare_clippy_lint! {
376 /// Checks for `.err().expect()` calls on the `Result` type.
378 /// ### Why is this bad?
379 /// `.expect_err()` can be called directly to avoid the extra type conversion from `err()`.
383 /// let x: Result<u32, &str> = Ok(10);
384 /// x.err().expect("Testing err().expect()");
388 /// let x: Result<u32, &str> = Ok(10);
389 /// x.expect_err("Testing expect_err");
391 #[clippy::version = "1.62.0"]
394 r#"using `.err().expect("")` when `.expect_err("")` can be used"#
397 declare_clippy_lint! {
399 /// Checks for usages of `_.unwrap_or_else(Default::default)` on `Option` and
402 /// ### Why is this bad?
403 /// Readability, these can be written as `_.unwrap_or_default`, which is
404 /// simpler and more concise.
408 /// # let x = Some(1);
409 /// x.unwrap_or_else(Default::default);
410 /// x.unwrap_or_else(u32::default);
415 /// # let x = Some(1);
416 /// x.unwrap_or_default();
418 #[clippy::version = "1.56.0"]
419 pub UNWRAP_OR_ELSE_DEFAULT,
421 "using `.unwrap_or_else(Default::default)`, which is more succinctly expressed as `.unwrap_or_default()`"
424 declare_clippy_lint! {
426 /// Checks for usage of `option.map(_).unwrap_or(_)` or `option.map(_).unwrap_or_else(_)` or
427 /// `result.map(_).unwrap_or_else(_)`.
429 /// ### Why is this bad?
430 /// Readability, these can be written more concisely (resp.) as
431 /// `option.map_or(_, _)`, `option.map_or_else(_, _)` and `result.map_or_else(_, _)`.
433 /// ### Known problems
434 /// The order of the arguments is not in execution order
438 /// # let option = Some(1);
439 /// # let result: Result<usize, ()> = Ok(1);
440 /// # fn some_function(foo: ()) -> usize { 1 }
441 /// option.map(|a| a + 1).unwrap_or(0);
442 /// result.map(|a| a + 1).unwrap_or_else(some_function);
447 /// # let option = Some(1);
448 /// # let result: Result<usize, ()> = Ok(1);
449 /// # fn some_function(foo: ()) -> usize { 1 }
450 /// option.map_or(0, |a| a + 1);
451 /// result.map_or_else(some_function, |a| a + 1);
453 #[clippy::version = "1.45.0"]
456 "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)`"
459 declare_clippy_lint! {
461 /// Checks for usage of `_.map_or(None, _)`.
463 /// ### Why is this bad?
464 /// Readability, this can be written more concisely as
467 /// ### Known problems
468 /// The order of the arguments is not in execution order.
472 /// # let opt = Some(1);
473 /// opt.map_or(None, |a| Some(a + 1));
478 /// # let opt = Some(1);
479 /// opt.and_then(|a| Some(a + 1));
481 #[clippy::version = "pre 1.29.0"]
482 pub OPTION_MAP_OR_NONE,
484 "using `Option.map_or(None, f)`, which is more succinctly expressed as `and_then(f)`"
487 declare_clippy_lint! {
489 /// Checks for usage of `_.map_or(None, Some)`.
491 /// ### Why is this bad?
492 /// Readability, this can be written more concisely as
497 /// # let r: Result<u32, &str> = Ok(1);
498 /// assert_eq!(Some(1), r.map_or(None, Some));
503 /// # let r: Result<u32, &str> = Ok(1);
504 /// assert_eq!(Some(1), r.ok());
506 #[clippy::version = "1.44.0"]
507 pub RESULT_MAP_OR_INTO_OPTION,
509 "using `Result.map_or(None, Some)`, which is more succinctly expressed as `ok()`"
512 declare_clippy_lint! {
514 /// Checks for usage of `_.and_then(|x| Some(y))`, `_.and_then(|x| Ok(y))` or
515 /// `_.or_else(|x| Err(y))`.
517 /// ### Why is this bad?
518 /// Readability, this can be written more concisely as
519 /// `_.map(|x| y)` or `_.map_err(|x| y)`.
523 /// # fn opt() -> Option<&'static str> { Some("42") }
524 /// # fn res() -> Result<&'static str, &'static str> { Ok("42") }
525 /// let _ = opt().and_then(|s| Some(s.len()));
526 /// let _ = res().and_then(|s| if s.len() == 42 { Ok(10) } else { Ok(20) });
527 /// let _ = res().or_else(|s| if s.len() == 42 { Err(10) } else { Err(20) });
530 /// The correct use would be:
533 /// # fn opt() -> Option<&'static str> { Some("42") }
534 /// # fn res() -> Result<&'static str, &'static str> { Ok("42") }
535 /// let _ = opt().map(|s| s.len());
536 /// let _ = res().map(|s| if s.len() == 42 { 10 } else { 20 });
537 /// let _ = res().map_err(|s| if s.len() == 42 { 10 } else { 20 });
539 #[clippy::version = "1.45.0"]
540 pub BIND_INSTEAD_OF_MAP,
542 "using `Option.and_then(|x| Some(y))`, which is more succinctly expressed as `map(|x| y)`"
545 declare_clippy_lint! {
547 /// Checks for usage of `_.filter(_).next()`.
549 /// ### Why is this bad?
550 /// Readability, this can be written more concisely as
555 /// # let vec = vec![1];
556 /// vec.iter().filter(|x| **x == 0).next();
561 /// # let vec = vec![1];
562 /// vec.iter().find(|x| **x == 0);
564 #[clippy::version = "pre 1.29.0"]
567 "using `filter(p).next()`, which is more succinctly expressed as `.find(p)`"
570 declare_clippy_lint! {
572 /// Checks for usage of `_.skip_while(condition).next()`.
574 /// ### Why is this bad?
575 /// Readability, this can be written more concisely as
576 /// `_.find(!condition)`.
580 /// # let vec = vec![1];
581 /// vec.iter().skip_while(|x| **x == 0).next();
586 /// # let vec = vec![1];
587 /// vec.iter().find(|x| **x != 0);
589 #[clippy::version = "1.42.0"]
592 "using `skip_while(p).next()`, which is more succinctly expressed as `.find(!p)`"
595 declare_clippy_lint! {
597 /// Checks for usage of `_.map(_).flatten(_)` on `Iterator` and `Option`
599 /// ### Why is this bad?
600 /// Readability, this can be written more concisely as
601 /// `_.flat_map(_)` for `Iterator` or `_.and_then(_)` for `Option`
605 /// let vec = vec![vec![1]];
606 /// let opt = Some(5);
608 /// vec.iter().map(|x| x.iter()).flatten();
609 /// opt.map(|x| Some(x * 2)).flatten();
614 /// # let vec = vec![vec![1]];
615 /// # let opt = Some(5);
616 /// vec.iter().flat_map(|x| x.iter());
617 /// opt.and_then(|x| Some(x * 2));
619 #[clippy::version = "1.31.0"]
622 "using combinations of `flatten` and `map` which can usually be written as a single method call"
625 declare_clippy_lint! {
627 /// Checks for usage of `_.filter(_).map(_)` that can be written more simply
628 /// as `filter_map(_)`.
630 /// ### Why is this bad?
631 /// Redundant code in the `filter` and `map` operations is poor style and
636 /// # #![allow(unused)]
638 /// .filter(|n| n.checked_add(1).is_some())
639 /// .map(|n| n.checked_add(1).unwrap());
644 /// # #[allow(unused)]
645 /// (0_i32..10).filter_map(|n| n.checked_add(1));
647 #[clippy::version = "1.51.0"]
648 pub MANUAL_FILTER_MAP,
650 "using `_.filter(_).map(_)` in a way that can be written more simply as `filter_map(_)`"
653 declare_clippy_lint! {
655 /// Checks for usage of `_.find(_).map(_)` that can be written more simply
656 /// as `find_map(_)`.
658 /// ### Why is this bad?
659 /// Redundant code in the `find` and `map` operations is poor style and
665 /// .find(|n| n.checked_add(1).is_some())
666 /// .map(|n| n.checked_add(1).unwrap());
671 /// (0_i32..10).find_map(|n| n.checked_add(1));
673 #[clippy::version = "1.51.0"]
676 "using `_.find(_).map(_)` in a way that can be written more simply as `find_map(_)`"
679 declare_clippy_lint! {
681 /// Checks for usage of `_.filter_map(_).next()`.
683 /// ### Why is this bad?
684 /// Readability, this can be written more concisely as
689 /// (0..3).filter_map(|x| if x == 2 { Some(x) } else { None }).next();
691 /// Can be written as
694 /// (0..3).find_map(|x| if x == 2 { Some(x) } else { None });
696 #[clippy::version = "1.36.0"]
699 "using combination of `filter_map` and `next` which can usually be written as a single method call"
702 declare_clippy_lint! {
704 /// Checks for usage of `flat_map(|x| x)`.
706 /// ### Why is this bad?
707 /// Readability, this can be written more concisely by using `flatten`.
711 /// # let iter = vec![vec![0]].into_iter();
712 /// iter.flat_map(|x| x);
714 /// Can be written as
716 /// # let iter = vec![vec![0]].into_iter();
719 #[clippy::version = "1.39.0"]
720 pub FLAT_MAP_IDENTITY,
722 "call to `flat_map` where `flatten` is sufficient"
725 declare_clippy_lint! {
727 /// Checks for an iterator or string search (such as `find()`,
728 /// `position()`, or `rposition()`) followed by a call to `is_some()` or `is_none()`.
730 /// ### Why is this bad?
731 /// Readability, this can be written more concisely as:
732 /// * `_.any(_)`, or `_.contains(_)` for `is_some()`,
733 /// * `!_.any(_)`, or `!_.contains(_)` for `is_none()`.
737 /// # #![allow(unused)]
738 /// let vec = vec![1];
739 /// vec.iter().find(|x| **x == 0).is_some();
741 /// "hello world".find("world").is_none();
746 /// let vec = vec![1];
747 /// vec.iter().any(|x| *x == 0);
749 /// # #[allow(unused)]
750 /// !"hello world".contains("world");
752 #[clippy::version = "pre 1.29.0"]
755 "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()`)"
758 declare_clippy_lint! {
760 /// Checks for usage of `.chars().next()` on a `str` to check
761 /// if it starts with a given char.
763 /// ### Why is this bad?
764 /// Readability, this can be written more concisely as
765 /// `_.starts_with(_)`.
769 /// let name = "foo";
770 /// if name.chars().next() == Some('_') {};
775 /// let name = "foo";
776 /// if name.starts_with('_') {};
778 #[clippy::version = "pre 1.29.0"]
781 "using `.chars().next()` to check if a string starts with a char"
784 declare_clippy_lint! {
786 /// Checks for calls to `.or(foo(..))`, `.unwrap_or(foo(..))`,
787 /// etc., and suggests to use `or_else`, `unwrap_or_else`, etc., or
788 /// `unwrap_or_default` instead.
790 /// ### Why is this bad?
791 /// The function will always be called and potentially
792 /// allocate an object acting as the default.
794 /// ### Known problems
795 /// If the function has side-effects, not calling it will
796 /// change the semantic of the program, but you shouldn't rely on that anyway.
800 /// # let foo = Some(String::new());
801 /// foo.unwrap_or(String::new());
806 /// # let foo = Some(String::new());
807 /// foo.unwrap_or_else(String::new);
811 /// # let foo = Some(String::new());
812 /// foo.unwrap_or_default();
814 #[clippy::version = "pre 1.29.0"]
817 "using any `*or` method with a function call, which suggests `*or_else`"
820 declare_clippy_lint! {
822 /// Checks for `.or(…).unwrap()` calls to Options and Results.
824 /// ### Why is this bad?
825 /// You should use `.unwrap_or(…)` instead for clarity.
829 /// # let fallback = "fallback";
831 /// # type Error = &'static str;
832 /// # let result: Result<&str, Error> = Err("error");
833 /// let value = result.or::<Error>(Ok(fallback)).unwrap();
836 /// # let option: Option<&str> = None;
837 /// let value = option.or(Some(fallback)).unwrap();
841 /// # let fallback = "fallback";
843 /// # let result: Result<&str, &str> = Err("error");
844 /// let value = result.unwrap_or(fallback);
847 /// # let option: Option<&str> = None;
848 /// let value = option.unwrap_or(fallback);
850 #[clippy::version = "1.61.0"]
853 "checks for `.or(…).unwrap()` calls to Options and Results."
856 declare_clippy_lint! {
858 /// Checks for calls to `.expect(&format!(...))`, `.expect(foo(..))`,
859 /// etc., and suggests to use `unwrap_or_else` instead
861 /// ### Why is this bad?
862 /// The function will always be called.
864 /// ### Known problems
865 /// If the function has side-effects, not calling it will
866 /// change the semantics of the program, but you shouldn't rely on that anyway.
870 /// # let foo = Some(String::new());
871 /// # let err_code = "418";
872 /// # let err_msg = "I'm a teapot";
873 /// foo.expect(&format!("Err {}: {}", err_code, err_msg));
877 /// # let foo = Some(String::new());
878 /// foo.expect(format!("Err {}: {}", err_code, err_msg).as_str());
883 /// # let foo = Some(String::new());
884 /// # let err_code = "418";
885 /// # let err_msg = "I'm a teapot";
886 /// foo.unwrap_or_else(|| panic!("Err {}: {}", err_code, err_msg));
888 #[clippy::version = "pre 1.29.0"]
891 "using any `expect` method with a function call"
894 declare_clippy_lint! {
896 /// Checks for usage of `.clone()` on a `Copy` type.
898 /// ### Why is this bad?
899 /// The only reason `Copy` types implement `Clone` is for
900 /// generics, not for using the `clone` method on a concrete type.
906 #[clippy::version = "pre 1.29.0"]
909 "using `clone` on a `Copy` type"
912 declare_clippy_lint! {
914 /// Checks for usage of `.clone()` on a ref-counted pointer,
915 /// (`Rc`, `Arc`, `rc::Weak`, or `sync::Weak`), and suggests calling Clone via unified
916 /// function syntax instead (e.g., `Rc::clone(foo)`).
918 /// ### Why is this bad?
919 /// Calling '.clone()' on an Rc, Arc, or Weak
920 /// can obscure the fact that only the pointer is being cloned, not the underlying
925 /// # use std::rc::Rc;
926 /// let x = Rc::new(1);
933 /// # use std::rc::Rc;
934 /// # let x = Rc::new(1);
937 #[clippy::version = "pre 1.29.0"]
938 pub CLONE_ON_REF_PTR,
940 "using 'clone' on a ref-counted pointer"
943 declare_clippy_lint! {
945 /// Checks for usage of `.clone()` on an `&&T`.
947 /// ### Why is this bad?
948 /// Cloning an `&&T` copies the inner `&T`, instead of
949 /// cloning the underlying `T`.
956 /// let z = y.clone();
957 /// println!("{:p} {:p}", *y, z); // prints out the same pointer
960 #[clippy::version = "pre 1.29.0"]
961 pub CLONE_DOUBLE_REF,
963 "using `clone` on `&&T`"
966 declare_clippy_lint! {
968 /// Checks for usage of `.to_string()` on an `&&T` where
969 /// `T` implements `ToString` directly (like `&&str` or `&&String`).
971 /// ### Why is this bad?
972 /// This bypasses the specialized implementation of
973 /// `ToString` and instead goes through the more expensive string formatting
978 /// // Generic implementation for `T: Display` is used (slow)
979 /// ["foo", "bar"].iter().map(|s| s.to_string());
981 /// // OK, the specialized impl is used
982 /// ["foo", "bar"].iter().map(|&s| s.to_string());
984 #[clippy::version = "1.40.0"]
985 pub INEFFICIENT_TO_STRING,
987 "using `to_string` on `&&T` where `T: ToString`"
990 declare_clippy_lint! {
992 /// Checks for `new` not returning a type that contains `Self`.
994 /// ### Why is this bad?
995 /// As a convention, `new` methods are used to make a new
996 /// instance of a type.
999 /// In an impl block:
1002 /// # struct NotAFoo;
1004 /// fn new() -> NotAFoo {
1012 /// struct Bar(Foo);
1014 /// // Bad. The type name must contain `Self`
1015 /// fn new() -> Bar {
1023 /// # struct FooError;
1025 /// // Good. Return type contains `Self`
1026 /// fn new() -> Result<Foo, FooError> {
1032 /// Or in a trait definition:
1034 /// pub trait Trait {
1035 /// // Bad. The type name must contain `Self`
1041 /// pub trait Trait {
1042 /// // Good. Return type contains `Self`
1043 /// fn new() -> Self;
1046 #[clippy::version = "pre 1.29.0"]
1047 pub NEW_RET_NO_SELF,
1049 "not returning type containing `Self` in a `new` method"
1052 declare_clippy_lint! {
1053 /// ### What it does
1054 /// Checks for string methods that receive a single-character
1055 /// `str` as an argument, e.g., `_.split("x")`.
1057 /// ### Why is this bad?
1058 /// Performing these methods using a `char` is faster than
1061 /// ### Known problems
1062 /// Does not catch multi-byte unicode characters.
1073 #[clippy::version = "pre 1.29.0"]
1074 pub SINGLE_CHAR_PATTERN,
1076 "using a single-character str where a char could be used, e.g., `_.split(\"x\")`"
1079 declare_clippy_lint! {
1080 /// ### What it does
1081 /// Checks for calling `.step_by(0)` on iterators which panics.
1083 /// ### Why is this bad?
1084 /// This very much looks like an oversight. Use `panic!()` instead if you
1085 /// actually intend to panic.
1088 /// ```rust,should_panic
1089 /// for x in (0..100).step_by(0) {
1093 #[clippy::version = "pre 1.29.0"]
1094 pub ITERATOR_STEP_BY_ZERO,
1096 "using `Iterator::step_by(0)`, which will panic at runtime"
1099 declare_clippy_lint! {
1100 /// ### What it does
1101 /// Checks for indirect collection of populated `Option`
1103 /// ### Why is this bad?
1104 /// `Option` is like a collection of 0-1 things, so `flatten`
1105 /// automatically does this without suspicious-looking `unwrap` calls.
1109 /// let _ = std::iter::empty::<Option<i32>>().filter(Option::is_some).map(Option::unwrap);
1113 /// let _ = std::iter::empty::<Option<i32>>().flatten();
1115 #[clippy::version = "1.53.0"]
1116 pub OPTION_FILTER_MAP,
1118 "filtering `Option` for `Some` then force-unwrapping, which can be one type-safe operation"
1121 declare_clippy_lint! {
1122 /// ### What it does
1123 /// Checks for the use of `iter.nth(0)`.
1125 /// ### Why is this bad?
1126 /// `iter.next()` is equivalent to
1127 /// `iter.nth(0)`, as they both consume the next element,
1128 /// but is more readable.
1132 /// # use std::collections::HashSet;
1133 /// # let mut s = HashSet::new();
1135 /// let x = s.iter().nth(0);
1140 /// # use std::collections::HashSet;
1141 /// # let mut s = HashSet::new();
1143 /// let x = s.iter().next();
1145 #[clippy::version = "1.42.0"]
1148 "replace `iter.nth(0)` with `iter.next()`"
1151 declare_clippy_lint! {
1152 /// ### What it does
1153 /// Checks for use of `.iter().nth()` (and the related
1154 /// `.iter_mut().nth()`) on standard library types with *O*(1) element access.
1156 /// ### Why is this bad?
1157 /// `.get()` and `.get_mut()` are more efficient and more
1162 /// let some_vec = vec![0, 1, 2, 3];
1163 /// let bad_vec = some_vec.iter().nth(3);
1164 /// let bad_slice = &some_vec[..].iter().nth(3);
1166 /// The correct use would be:
1168 /// let some_vec = vec![0, 1, 2, 3];
1169 /// let bad_vec = some_vec.get(3);
1170 /// let bad_slice = &some_vec[..].get(3);
1172 #[clippy::version = "pre 1.29.0"]
1175 "using `.iter().nth()` on a standard library type with O(1) element access"
1178 declare_clippy_lint! {
1179 /// ### What it does
1180 /// Checks for use of `.skip(x).next()` on iterators.
1182 /// ### Why is this bad?
1183 /// `.nth(x)` is cleaner
1187 /// let some_vec = vec![0, 1, 2, 3];
1188 /// let bad_vec = some_vec.iter().skip(3).next();
1189 /// let bad_slice = &some_vec[..].iter().skip(3).next();
1191 /// The correct use would be:
1193 /// let some_vec = vec![0, 1, 2, 3];
1194 /// let bad_vec = some_vec.iter().nth(3);
1195 /// let bad_slice = &some_vec[..].iter().nth(3);
1197 #[clippy::version = "pre 1.29.0"]
1200 "using `.skip(x).next()` on an iterator"
1203 declare_clippy_lint! {
1204 /// ### What it does
1205 /// Checks for use of `.drain(..)` on `Vec` and `VecDeque` for iteration.
1207 /// ### Why is this bad?
1208 /// `.into_iter()` is simpler with better performance.
1212 /// # use std::collections::HashSet;
1213 /// let mut foo = vec![0, 1, 2, 3];
1214 /// let bar: HashSet<usize> = foo.drain(..).collect();
1218 /// # use std::collections::HashSet;
1219 /// let foo = vec![0, 1, 2, 3];
1220 /// let bar: HashSet<usize> = foo.into_iter().collect();
1222 #[clippy::version = "1.61.0"]
1223 pub ITER_WITH_DRAIN,
1225 "replace `.drain(..)` with `.into_iter()`"
1228 declare_clippy_lint! {
1229 /// ### What it does
1230 /// Checks for using `x.get(x.len() - 1)` instead of
1233 /// ### Why is this bad?
1234 /// Using `x.last()` is easier to read and has the same
1237 /// Note that using `x[x.len() - 1]` is semantically different from
1238 /// `x.last()`. Indexing into the array will panic on out-of-bounds
1239 /// accesses, while `x.get()` and `x.last()` will return `None`.
1241 /// There is another lint (get_unwrap) that covers the case of using
1242 /// `x.get(index).unwrap()` instead of `x[index]`.
1246 /// let x = vec![2, 3, 5];
1247 /// let last_element = x.get(x.len() - 1);
1252 /// let x = vec![2, 3, 5];
1253 /// let last_element = x.last();
1255 #[clippy::version = "1.37.0"]
1256 pub GET_LAST_WITH_LEN,
1258 "Using `x.get(x.len() - 1)` when `x.last()` is correct and simpler"
1261 declare_clippy_lint! {
1262 /// ### What it does
1263 /// Checks for use of `.get().unwrap()` (or
1264 /// `.get_mut().unwrap`) on a standard library type which implements `Index`
1266 /// ### Why is this bad?
1267 /// Using the Index trait (`[]`) is more clear and more
1270 /// ### Known problems
1271 /// Not a replacement for error handling: Using either
1272 /// `.unwrap()` or the Index trait (`[]`) carries the risk of causing a `panic`
1273 /// if the value being accessed is `None`. If the use of `.get().unwrap()` is a
1274 /// temporary placeholder for dealing with the `Option` type, then this does
1275 /// not mitigate the need for error handling. If there is a chance that `.get()`
1276 /// will be `None` in your program, then it is advisable that the `None` case
1277 /// is handled in a future refactor instead of using `.unwrap()` or the Index
1282 /// let mut some_vec = vec![0, 1, 2, 3];
1283 /// let last = some_vec.get(3).unwrap();
1284 /// *some_vec.get_mut(0).unwrap() = 1;
1286 /// The correct use would be:
1288 /// let mut some_vec = vec![0, 1, 2, 3];
1289 /// let last = some_vec[3];
1290 /// some_vec[0] = 1;
1292 #[clippy::version = "pre 1.29.0"]
1295 "using `.get().unwrap()` or `.get_mut().unwrap()` when using `[]` would work instead"
1298 declare_clippy_lint! {
1299 /// ### What it does
1300 /// Checks for occurrences where one vector gets extended instead of append
1302 /// ### Why is this bad?
1303 /// Using `append` instead of `extend` is more concise and faster
1307 /// let mut a = vec![1, 2, 3];
1308 /// let mut b = vec![4, 5, 6];
1310 /// a.extend(b.drain(..));
1315 /// let mut a = vec![1, 2, 3];
1316 /// let mut b = vec![4, 5, 6];
1318 /// a.append(&mut b);
1320 #[clippy::version = "1.55.0"]
1321 pub EXTEND_WITH_DRAIN,
1323 "using vec.append(&mut vec) to move the full range of a vector to another"
1326 declare_clippy_lint! {
1327 /// ### What it does
1328 /// Checks for the use of `.extend(s.chars())` where s is a
1329 /// `&str` or `String`.
1331 /// ### Why is this bad?
1332 /// `.push_str(s)` is clearer
1336 /// let abc = "abc";
1337 /// let def = String::from("def");
1338 /// let mut s = String::new();
1339 /// s.extend(abc.chars());
1340 /// s.extend(def.chars());
1342 /// The correct use would be:
1344 /// let abc = "abc";
1345 /// let def = String::from("def");
1346 /// let mut s = String::new();
1347 /// s.push_str(abc);
1348 /// s.push_str(&def);
1350 #[clippy::version = "pre 1.29.0"]
1351 pub STRING_EXTEND_CHARS,
1353 "using `x.extend(s.chars())` where s is a `&str` or `String`"
1356 declare_clippy_lint! {
1357 /// ### What it does
1358 /// Checks for the use of `.cloned().collect()` on slice to
1361 /// ### Why is this bad?
1362 /// `.to_vec()` is clearer
1366 /// let s = [1, 2, 3, 4, 5];
1367 /// let s2: Vec<isize> = s[..].iter().cloned().collect();
1369 /// The better use would be:
1371 /// let s = [1, 2, 3, 4, 5];
1372 /// let s2: Vec<isize> = s.to_vec();
1374 #[clippy::version = "pre 1.29.0"]
1375 pub ITER_CLONED_COLLECT,
1377 "using `.cloned().collect()` on slice to create a `Vec`"
1380 declare_clippy_lint! {
1381 /// ### What it does
1382 /// Checks for usage of `_.chars().last()` or
1383 /// `_.chars().next_back()` on a `str` to check if it ends with a given char.
1385 /// ### Why is this bad?
1386 /// Readability, this can be written more concisely as
1387 /// `_.ends_with(_)`.
1391 /// # let name = "_";
1392 /// name.chars().last() == Some('_') || name.chars().next_back() == Some('-');
1397 /// # let name = "_";
1398 /// name.ends_with('_') || name.ends_with('-');
1400 #[clippy::version = "pre 1.29.0"]
1403 "using `.chars().last()` or `.chars().next_back()` to check if a string ends with a char"
1406 declare_clippy_lint! {
1407 /// ### What it does
1408 /// Checks for usage of `.as_ref()` or `.as_mut()` where the
1409 /// types before and after the call are the same.
1411 /// ### Why is this bad?
1412 /// The call is unnecessary.
1416 /// # fn do_stuff(x: &[i32]) {}
1417 /// let x: &[i32] = &[1, 2, 3, 4, 5];
1418 /// do_stuff(x.as_ref());
1420 /// The correct use would be:
1422 /// # fn do_stuff(x: &[i32]) {}
1423 /// let x: &[i32] = &[1, 2, 3, 4, 5];
1426 #[clippy::version = "pre 1.29.0"]
1429 "using `as_ref` where the types before and after the call are the same"
1432 declare_clippy_lint! {
1433 /// ### What it does
1434 /// Checks for using `fold` when a more succinct alternative exists.
1435 /// Specifically, this checks for `fold`s which could be replaced by `any`, `all`,
1436 /// `sum` or `product`.
1438 /// ### Why is this bad?
1443 /// # #[allow(unused)]
1444 /// (0..3).fold(false, |acc, x| acc || x > 2);
1449 /// (0..3).any(|x| x > 2);
1451 #[clippy::version = "pre 1.29.0"]
1452 pub UNNECESSARY_FOLD,
1454 "using `fold` when a more succinct alternative exists"
1457 declare_clippy_lint! {
1458 /// ### What it does
1459 /// Checks for `filter_map` calls that could be replaced by `filter` or `map`.
1460 /// More specifically it checks if the closure provided is only performing one of the
1461 /// filter or map operations and suggests the appropriate option.
1463 /// ### Why is this bad?
1464 /// Complexity. The intent is also clearer if only a single
1465 /// operation is being performed.
1469 /// let _ = (0..3).filter_map(|x| if x > 2 { Some(x) } else { None });
1471 /// // As there is no transformation of the argument this could be written as:
1472 /// let _ = (0..3).filter(|&x| x > 2);
1476 /// let _ = (0..4).filter_map(|x| Some(x + 1));
1478 /// // As there is no conditional check on the argument this could be written as:
1479 /// let _ = (0..4).map(|x| x + 1);
1481 #[clippy::version = "1.31.0"]
1482 pub UNNECESSARY_FILTER_MAP,
1484 "using `filter_map` when a more succinct alternative exists"
1487 declare_clippy_lint! {
1488 /// ### What it does
1489 /// Checks for `find_map` calls that could be replaced by `find` or `map`. More
1490 /// specifically it checks if the closure provided is only performing one of the
1491 /// find or map operations and suggests the appropriate option.
1493 /// ### Why is this bad?
1494 /// Complexity. The intent is also clearer if only a single
1495 /// operation is being performed.
1499 /// let _ = (0..3).find_map(|x| if x > 2 { Some(x) } else { None });
1501 /// // As there is no transformation of the argument this could be written as:
1502 /// let _ = (0..3).find(|&x| x > 2);
1506 /// let _ = (0..4).find_map(|x| Some(x + 1));
1508 /// // As there is no conditional check on the argument this could be written as:
1509 /// let _ = (0..4).map(|x| x + 1).next();
1511 #[clippy::version = "1.61.0"]
1512 pub UNNECESSARY_FIND_MAP,
1514 "using `find_map` when a more succinct alternative exists"
1517 declare_clippy_lint! {
1518 /// ### What it does
1519 /// Checks for `into_iter` calls on references which should be replaced by `iter`
1522 /// ### Why is this bad?
1523 /// Readability. Calling `into_iter` on a reference will not move out its
1524 /// content into the resulting iterator, which is confusing. It is better just call `iter` or
1525 /// `iter_mut` directly.
1529 /// # let vec = vec![3, 4, 5];
1530 /// (&vec).into_iter();
1535 /// # let vec = vec![3, 4, 5];
1538 #[clippy::version = "1.32.0"]
1539 pub INTO_ITER_ON_REF,
1541 "using `.into_iter()` on a reference"
1544 declare_clippy_lint! {
1545 /// ### What it does
1546 /// Checks for calls to `map` followed by a `count`.
1548 /// ### Why is this bad?
1549 /// It looks suspicious. Maybe `map` was confused with `filter`.
1550 /// If the `map` call is intentional, this should be rewritten
1551 /// using `inspect`. Or, if you intend to drive the iterator to
1552 /// completion, you can just use `for_each` instead.
1556 /// let _ = (0..3).map(|x| x + 2).count();
1558 #[clippy::version = "1.39.0"]
1561 "suspicious usage of map"
1564 declare_clippy_lint! {
1565 /// ### What it does
1566 /// Checks for `MaybeUninit::uninit().assume_init()`.
1568 /// ### Why is this bad?
1569 /// For most types, this is undefined behavior.
1571 /// ### Known problems
1572 /// For now, we accept empty tuples and tuples / arrays
1573 /// of `MaybeUninit`. There may be other types that allow uninitialized
1574 /// data, but those are not yet rigorously defined.
1578 /// // Beware the UB
1579 /// use std::mem::MaybeUninit;
1581 /// let _: usize = unsafe { MaybeUninit::uninit().assume_init() };
1584 /// Note that the following is OK:
1587 /// use std::mem::MaybeUninit;
1589 /// let _: [MaybeUninit<bool>; 5] = unsafe {
1590 /// MaybeUninit::uninit().assume_init()
1593 #[clippy::version = "1.39.0"]
1594 pub UNINIT_ASSUMED_INIT,
1596 "`MaybeUninit::uninit().assume_init()`"
1599 declare_clippy_lint! {
1600 /// ### What it does
1601 /// Checks for `.checked_add/sub(x).unwrap_or(MAX/MIN)`.
1603 /// ### Why is this bad?
1604 /// These can be written simply with `saturating_add/sub` methods.
1608 /// # let y: u32 = 0;
1609 /// # let x: u32 = 100;
1610 /// let add = x.checked_add(y).unwrap_or(u32::MAX);
1611 /// let sub = x.checked_sub(y).unwrap_or(u32::MIN);
1614 /// can be written using dedicated methods for saturating addition/subtraction as:
1617 /// # let y: u32 = 0;
1618 /// # let x: u32 = 100;
1619 /// let add = x.saturating_add(y);
1620 /// let sub = x.saturating_sub(y);
1622 #[clippy::version = "1.39.0"]
1623 pub MANUAL_SATURATING_ARITHMETIC,
1625 "`.checked_add/sub(x).unwrap_or(MAX/MIN)`"
1628 declare_clippy_lint! {
1629 /// ### What it does
1630 /// Checks for `offset(_)`, `wrapping_`{`add`, `sub`}, etc. on raw pointers to
1631 /// zero-sized types
1633 /// ### Why is this bad?
1634 /// This is a no-op, and likely unintended
1638 /// unsafe { (&() as *const ()).offset(1) };
1640 #[clippy::version = "1.41.0"]
1643 "Check for offset calculations on raw pointers to zero-sized types"
1646 declare_clippy_lint! {
1647 /// ### What it does
1648 /// Checks for `FileType::is_file()`.
1650 /// ### Why is this bad?
1651 /// When people testing a file type with `FileType::is_file`
1652 /// they are testing whether a path is something they can get bytes from. But
1653 /// `is_file` doesn't cover special file types in unix-like systems, and doesn't cover
1654 /// symlink in windows. Using `!FileType::is_dir()` is a better way to that intention.
1659 /// let metadata = std::fs::metadata("foo.txt")?;
1660 /// let filetype = metadata.file_type();
1662 /// if filetype.is_file() {
1665 /// # Ok::<_, std::io::Error>(())
1669 /// should be written as:
1673 /// let metadata = std::fs::metadata("foo.txt")?;
1674 /// let filetype = metadata.file_type();
1676 /// if !filetype.is_dir() {
1679 /// # Ok::<_, std::io::Error>(())
1682 #[clippy::version = "1.42.0"]
1683 pub FILETYPE_IS_FILE,
1685 "`FileType::is_file` is not recommended to test for readable file type"
1688 declare_clippy_lint! {
1689 /// ### What it does
1690 /// Checks for usage of `_.as_ref().map(Deref::deref)` or it's aliases (such as String::as_str).
1692 /// ### Why is this bad?
1693 /// Readability, this can be written more concisely as
1698 /// # let opt = Some("".to_string());
1699 /// opt.as_ref().map(String::as_str)
1702 /// Can be written as
1704 /// # let opt = Some("".to_string());
1708 #[clippy::version = "1.42.0"]
1709 pub OPTION_AS_REF_DEREF,
1711 "using `as_ref().map(Deref::deref)`, which is more succinctly expressed as `as_deref()`"
1714 declare_clippy_lint! {
1715 /// ### What it does
1716 /// Checks for usage of `iter().next()` on a Slice or an Array
1718 /// ### Why is this bad?
1719 /// These can be shortened into `.get()`
1723 /// # let a = [1, 2, 3];
1724 /// # let b = vec![1, 2, 3];
1725 /// a[2..].iter().next();
1726 /// b.iter().next();
1728 /// should be written as:
1730 /// # let a = [1, 2, 3];
1731 /// # let b = vec![1, 2, 3];
1735 #[clippy::version = "1.46.0"]
1736 pub ITER_NEXT_SLICE,
1738 "using `.iter().next()` on a sliced array, which can be shortened to just `.get()`"
1741 declare_clippy_lint! {
1742 /// ### What it does
1743 /// Warns when using `push_str`/`insert_str` with a single-character string literal
1744 /// where `push`/`insert` with a `char` would work fine.
1746 /// ### Why is this bad?
1747 /// It's less clear that we are pushing a single character.
1751 /// # let mut string = String::new();
1752 /// string.insert_str(0, "R");
1753 /// string.push_str("R");
1758 /// # let mut string = String::new();
1759 /// string.insert(0, 'R');
1760 /// string.push('R');
1762 #[clippy::version = "1.49.0"]
1763 pub SINGLE_CHAR_ADD_STR,
1765 "`push_str()` or `insert_str()` used with a single-character string literal as parameter"
1768 declare_clippy_lint! {
1769 /// ### What it does
1770 /// As the counterpart to `or_fun_call`, this lint looks for unnecessary
1771 /// lazily evaluated closures on `Option` and `Result`.
1773 /// This lint suggests changing the following functions, when eager evaluation results in
1775 /// - `unwrap_or_else` to `unwrap_or`
1776 /// - `and_then` to `and`
1777 /// - `or_else` to `or`
1778 /// - `get_or_insert_with` to `get_or_insert`
1779 /// - `ok_or_else` to `ok_or`
1781 /// ### Why is this bad?
1782 /// Using eager evaluation is shorter and simpler in some cases.
1784 /// ### Known problems
1785 /// It is possible, but not recommended for `Deref` and `Index` to have
1786 /// side effects. Eagerly evaluating them can change the semantics of the program.
1790 /// // example code where clippy issues a warning
1791 /// let opt: Option<u32> = None;
1793 /// opt.unwrap_or_else(|| 42);
1797 /// let opt: Option<u32> = None;
1799 /// opt.unwrap_or(42);
1801 #[clippy::version = "1.48.0"]
1802 pub UNNECESSARY_LAZY_EVALUATIONS,
1804 "using unnecessary lazy evaluation, which can be replaced with simpler eager evaluation"
1807 declare_clippy_lint! {
1808 /// ### What it does
1809 /// Checks for usage of `_.map(_).collect::<Result<(), _>()`.
1811 /// ### Why is this bad?
1812 /// Using `try_for_each` instead is more readable and idiomatic.
1816 /// (0..3).map(|t| Err(t)).collect::<Result<(), _>>();
1820 /// (0..3).try_for_each(|t| Err(t));
1822 #[clippy::version = "1.49.0"]
1823 pub MAP_COLLECT_RESULT_UNIT,
1825 "using `.map(_).collect::<Result<(),_>()`, which can be replaced with `try_for_each`"
1828 declare_clippy_lint! {
1829 /// ### What it does
1830 /// Checks for `from_iter()` function calls on types that implement the `FromIterator`
1833 /// ### Why is this bad?
1834 /// It is recommended style to use collect. See
1835 /// [FromIterator documentation](https://doc.rust-lang.org/std/iter/trait.FromIterator.html)
1839 /// let five_fives = std::iter::repeat(5).take(5);
1841 /// let v = Vec::from_iter(five_fives);
1843 /// assert_eq!(v, vec![5, 5, 5, 5, 5]);
1847 /// let five_fives = std::iter::repeat(5).take(5);
1849 /// let v: Vec<i32> = five_fives.collect();
1851 /// assert_eq!(v, vec![5, 5, 5, 5, 5]);
1853 #[clippy::version = "1.49.0"]
1854 pub FROM_ITER_INSTEAD_OF_COLLECT,
1856 "use `.collect()` instead of `::from_iter()`"
1859 declare_clippy_lint! {
1860 /// ### What it does
1861 /// Checks for usage of `inspect().for_each()`.
1863 /// ### Why is this bad?
1864 /// It is the same as performing the computation
1865 /// inside `inspect` at the beginning of the closure in `for_each`.
1869 /// [1,2,3,4,5].iter()
1870 /// .inspect(|&x| println!("inspect the number: {}", x))
1871 /// .for_each(|&x| {
1872 /// assert!(x >= 0);
1875 /// Can be written as
1877 /// [1,2,3,4,5].iter()
1878 /// .for_each(|&x| {
1879 /// println!("inspect the number: {}", x);
1880 /// assert!(x >= 0);
1883 #[clippy::version = "1.51.0"]
1884 pub INSPECT_FOR_EACH,
1886 "using `.inspect().for_each()`, which can be replaced with `.for_each()`"
1889 declare_clippy_lint! {
1890 /// ### What it does
1891 /// Checks for usage of `filter_map(|x| x)`.
1893 /// ### Why is this bad?
1894 /// Readability, this can be written more concisely by using `flatten`.
1898 /// # let iter = vec![Some(1)].into_iter();
1899 /// iter.filter_map(|x| x);
1903 /// # let iter = vec![Some(1)].into_iter();
1906 #[clippy::version = "1.52.0"]
1907 pub FILTER_MAP_IDENTITY,
1909 "call to `filter_map` where `flatten` is sufficient"
1912 declare_clippy_lint! {
1913 /// ### What it does
1914 /// Checks for instances of `map(f)` where `f` is the identity function.
1916 /// ### Why is this bad?
1917 /// It can be written more concisely without the call to `map`.
1921 /// let x = [1, 2, 3];
1922 /// let y: Vec<_> = x.iter().map(|x| x).map(|x| 2*x).collect();
1926 /// let x = [1, 2, 3];
1927 /// let y: Vec<_> = x.iter().map(|x| 2*x).collect();
1929 #[clippy::version = "1.47.0"]
1932 "using iterator.map(|x| x)"
1935 declare_clippy_lint! {
1936 /// ### What it does
1937 /// Checks for the use of `.bytes().nth()`.
1939 /// ### Why is this bad?
1940 /// `.as_bytes().get()` is more efficient and more
1945 /// # #[allow(unused)]
1946 /// "Hello".bytes().nth(3);
1951 /// # #[allow(unused)]
1952 /// "Hello".as_bytes().get(3);
1954 #[clippy::version = "1.52.0"]
1957 "replace `.bytes().nth()` with `.as_bytes().get()`"
1960 declare_clippy_lint! {
1961 /// ### What it does
1962 /// Checks for the usage of `_.to_owned()`, `vec.to_vec()`, or similar when calling `_.clone()` would be clearer.
1964 /// ### Why is this bad?
1965 /// These methods do the same thing as `_.clone()` but may be confusing as
1966 /// to why we are calling `to_vec` on something that is already a `Vec` or calling `to_owned` on something that is already owned.
1970 /// let a = vec![1, 2, 3];
1971 /// let b = a.to_vec();
1972 /// let c = a.to_owned();
1976 /// let a = vec![1, 2, 3];
1977 /// let b = a.clone();
1978 /// let c = a.clone();
1980 #[clippy::version = "1.52.0"]
1983 "implicitly cloning a value by invoking a function on its dereferenced type"
1986 declare_clippy_lint! {
1987 /// ### What it does
1988 /// Checks for the use of `.iter().count()`.
1990 /// ### Why is this bad?
1991 /// `.len()` is more efficient and more
1996 /// # #![allow(unused)]
1997 /// let some_vec = vec![0, 1, 2, 3];
1999 /// some_vec.iter().count();
2000 /// &some_vec[..].iter().count();
2005 /// let some_vec = vec![0, 1, 2, 3];
2008 /// &some_vec[..].len();
2010 #[clippy::version = "1.52.0"]
2013 "replace `.iter().count()` with `.len()`"
2016 declare_clippy_lint! {
2017 /// ### What it does
2018 /// Checks for calls to [`splitn`]
2019 /// (https://doc.rust-lang.org/std/primitive.str.html#method.splitn) and
2020 /// related functions with either zero or one splits.
2022 /// ### Why is this bad?
2023 /// These calls don't actually split the value and are
2024 /// likely to be intended as a different number.
2029 /// for x in s.splitn(1, ":") {
2037 /// for x in s.splitn(2, ":") {
2041 #[clippy::version = "1.54.0"]
2042 pub SUSPICIOUS_SPLITN,
2044 "checks for `.splitn(0, ..)` and `.splitn(1, ..)`"
2047 declare_clippy_lint! {
2048 /// ### What it does
2049 /// Checks for manual implementations of `str::repeat`
2051 /// ### Why is this bad?
2052 /// These are both harder to read, as well as less performant.
2056 /// let x: String = std::iter::repeat('x').take(10).collect();
2061 /// let x: String = "x".repeat(10);
2063 #[clippy::version = "1.54.0"]
2064 pub MANUAL_STR_REPEAT,
2066 "manual implementation of `str::repeat`"
2069 declare_clippy_lint! {
2070 /// ### What it does
2071 /// Checks for usages of `str::splitn(2, _)`
2073 /// ### Why is this bad?
2074 /// `split_once` is both clearer in intent and slightly more efficient.
2078 /// let s = "key=value=add";
2079 /// let (key, value) = s.splitn(2, '=').next_tuple()?;
2080 /// let value = s.splitn(2, '=').nth(1)?;
2082 /// let mut parts = s.splitn(2, '=');
2083 /// let key = parts.next()?;
2084 /// let value = parts.next()?;
2089 /// let s = "key=value=add";
2090 /// let (key, value) = s.split_once('=')?;
2091 /// let value = s.split_once('=')?.1;
2093 /// let (key, value) = s.split_once('=')?;
2097 /// The multiple statement variant currently only detects `iter.next()?`/`iter.next().unwrap()`
2098 /// in two separate `let` statements that immediately follow the `splitn()`
2099 #[clippy::version = "1.57.0"]
2100 pub MANUAL_SPLIT_ONCE,
2102 "replace `.splitn(2, pat)` with `.split_once(pat)`"
2105 declare_clippy_lint! {
2106 /// ### What it does
2107 /// Checks for usages of `str::splitn` (or `str::rsplitn`) where using `str::split` would be the same.
2108 /// ### Why is this bad?
2109 /// The function `split` is simpler and there is no performance difference in these cases, considering
2110 /// that both functions return a lazy iterator.
2113 /// let str = "key=value=add";
2114 /// let _ = str.splitn(3, '=').next().unwrap();
2119 /// let str = "key=value=add";
2120 /// let _ = str.split('=').next().unwrap();
2122 #[clippy::version = "1.59.0"]
2123 pub NEEDLESS_SPLITN,
2125 "usages of `str::splitn` that can be replaced with `str::split`"
2128 declare_clippy_lint! {
2129 /// ### What it does
2130 /// Checks for unnecessary calls to [`ToOwned::to_owned`](https://doc.rust-lang.org/std/borrow/trait.ToOwned.html#tymethod.to_owned)
2131 /// and other `to_owned`-like functions.
2133 /// ### Why is this bad?
2134 /// The unnecessary calls result in useless allocations.
2136 /// ### Known problems
2137 /// `unnecessary_to_owned` can falsely trigger if `IntoIterator::into_iter` is applied to an
2138 /// owned copy of a resource and the resource is later used mutably. See
2139 /// [#8148](https://github.com/rust-lang/rust-clippy/issues/8148).
2143 /// let path = std::path::Path::new("x");
2144 /// foo(&path.to_string_lossy().to_string());
2145 /// fn foo(s: &str) {}
2149 /// let path = std::path::Path::new("x");
2150 /// foo(&path.to_string_lossy());
2151 /// fn foo(s: &str) {}
2153 #[clippy::version = "1.59.0"]
2154 pub UNNECESSARY_TO_OWNED,
2156 "unnecessary calls to `to_owned`-like functions"
2159 declare_clippy_lint! {
2160 /// ### What it does
2161 /// Checks for use of `.collect::<Vec<String>>().join("")` on iterators.
2163 /// ### Why is this bad?
2164 /// `.collect::<String>()` is more concise and might be more performant
2168 /// let vector = vec!["hello", "world"];
2169 /// let output = vector.iter().map(|item| item.to_uppercase()).collect::<Vec<String>>().join("");
2170 /// println!("{}", output);
2172 /// The correct use would be:
2174 /// let vector = vec!["hello", "world"];
2175 /// let output = vector.iter().map(|item| item.to_uppercase()).collect::<String>();
2176 /// println!("{}", output);
2178 /// ### Known problems
2179 /// While `.collect::<String>()` is sometimes more performant, there are cases where
2180 /// using `.collect::<String>()` over `.collect::<Vec<String>>().join("")`
2181 /// will prevent loop unrolling and will result in a negative performance impact.
2183 /// Additionally, differences have been observed between aarch64 and x86_64 assembly output,
2184 /// with aarch64 tending to producing faster assembly in more cases when using `.collect::<String>()`
2185 #[clippy::version = "1.61.0"]
2186 pub UNNECESSARY_JOIN,
2188 "using `.collect::<Vec<String>>().join(\"\")` on an iterator"
2191 declare_clippy_lint! {
2192 /// ### What it does
2193 /// Checks for no-op uses of `Option::{as_deref, as_deref_mut}`,
2194 /// for example, `Option<&T>::as_deref()` returns the same type.
2196 /// ### Why is this bad?
2197 /// Redundant code and improving readability.
2201 /// let a = Some(&1);
2202 /// let b = a.as_deref(); // goes from Option<&i32> to Option<&i32>
2207 /// let a = Some(&1);
2210 #[clippy::version = "1.57.0"]
2211 pub NEEDLESS_OPTION_AS_DEREF,
2213 "no-op use of `deref` or `deref_mut` method to `Option`."
2216 declare_clippy_lint! {
2217 /// ### What it does
2218 /// Finds usages of [`char::is_digit`](https://doc.rust-lang.org/stable/std/primitive.char.html#method.is_digit) that
2219 /// can be replaced with [`is_ascii_digit`](https://doc.rust-lang.org/stable/std/primitive.char.html#method.is_ascii_digit) or
2220 /// [`is_ascii_hexdigit`](https://doc.rust-lang.org/stable/std/primitive.char.html#method.is_ascii_hexdigit).
2222 /// ### Why is this bad?
2223 /// `is_digit(..)` is slower and requires specifying the radix.
2227 /// let c: char = '6';
2233 /// let c: char = '6';
2234 /// c.is_ascii_digit();
2235 /// c.is_ascii_hexdigit();
2237 #[clippy::version = "1.62.0"]
2238 pub IS_DIGIT_ASCII_RADIX,
2240 "use of `char::is_digit(..)` with literal radix of 10 or 16"
2243 declare_clippy_lint! {
2244 /// ### What it does
2245 /// Checks for calling `take` function after `as_ref`.
2247 /// ### Why is this bad?
2248 /// Redundant code. `take` writes `None` to its argument.
2249 /// In this case the modification is useless as it's a temporary that cannot be read from afterwards.
2253 /// let x = Some(3);
2254 /// x.as_ref().take();
2258 /// let x = Some(3);
2261 #[clippy::version = "1.62.0"]
2262 pub NEEDLESS_OPTION_TAKE,
2264 "using `.as_ref().take()` on a temporary value"
2267 declare_clippy_lint! {
2268 /// ### What it does
2269 /// Checks for `replace` statements which have no effect.
2271 /// ### Why is this bad?
2272 /// It's either a mistake or confusing.
2276 /// "1234".replace("12", "12");
2277 /// "1234".replacen("12", "12", 1);
2279 #[clippy::version = "1.63.0"]
2280 pub NO_EFFECT_REPLACE,
2282 "replace with no effect"
2285 declare_clippy_lint! {
2286 /// ### What it does
2287 /// Checks for usages of `.then_some(..).unwrap_or(..)`
2289 /// ### Why is this bad?
2290 /// This can be written more clearly with `if .. else ..`
2293 /// This lint currently only looks for usages of
2294 /// `.then_some(..).unwrap_or(..)`, but will be expanded
2295 /// to account for similar patterns.
2300 /// x.then_some("a").unwrap_or("b");
2305 /// if x { "a" } else { "b" };
2307 #[clippy::version = "1.64.0"]
2308 pub OBFUSCATED_IF_ELSE,
2310 "use of `.then_some(..).unwrap_or(..)` can be written \
2311 more clearly with `if .. else ..`"
2314 declare_clippy_lint! {
2315 /// ### What it does
2317 /// Checks for calls to `iter`, `iter_mut` or `into_iter` on collections containing a single item
2319 /// ### Why is this bad?
2321 /// It is simpler to use the once function from the standard library:
2326 /// let a = [123].iter();
2327 /// let b = Some(123).into_iter();
2332 /// let a = iter::once(&123);
2333 /// let b = iter::once(123);
2336 /// ### Known problems
2338 /// The type of the resulting iterator might become incompatible with its usage
2339 #[clippy::version = "1.64.0"]
2340 pub ITER_ON_SINGLE_ITEMS,
2342 "Iterator for array of length 1"
2345 declare_clippy_lint! {
2346 /// ### What it does
2348 /// Checks for calls to `iter`, `iter_mut` or `into_iter` on empty collections
2350 /// ### Why is this bad?
2352 /// It is simpler to use the empty function from the standard library:
2357 /// use std::{slice, option};
2358 /// let a: slice::Iter<i32> = [].iter();
2359 /// let f: option::IntoIter<i32> = None.into_iter();
2364 /// let a: iter::Empty<i32> = iter::empty();
2365 /// let b: iter::Empty<i32> = iter::empty();
2368 /// ### Known problems
2370 /// The type of the resulting iterator might become incompatible with its usage
2371 #[clippy::version = "1.64.0"]
2372 pub ITER_ON_EMPTY_COLLECTIONS,
2374 "Iterator for empty array"
2377 declare_clippy_lint! {
2378 /// ### What it does
2379 /// Checks for naive byte counts
2381 /// ### Why is this bad?
2382 /// The [`bytecount`](https://crates.io/crates/bytecount)
2383 /// crate has methods to count your bytes faster, especially for large slices.
2385 /// ### Known problems
2386 /// If you have predominantly small slices, the
2387 /// `bytecount::count(..)` method may actually be slower. However, if you can
2388 /// ensure that less than 2³²-1 matches arise, the `naive_count_32(..)` can be
2389 /// faster in those cases.
2393 /// # let vec = vec![1_u8];
2394 /// let count = vec.iter().filter(|x| **x == 0u8).count();
2399 /// # let vec = vec![1_u8];
2400 /// let count = bytecount::count(&vec, 0u8);
2402 #[clippy::version = "pre 1.29.0"]
2403 pub NAIVE_BYTECOUNT,
2405 "use of naive `<slice>.filter(|&x| x == y).count()` to count byte values"
2408 declare_clippy_lint! {
2409 /// ### What it does
2410 /// It checks for `str::bytes().count()` and suggests replacing it with
2413 /// ### Why is this bad?
2414 /// `str::bytes().count()` is longer and may not be as performant as using
2419 /// "hello".bytes().count();
2420 /// String::from("hello").bytes().count();
2425 /// String::from("hello").len();
2427 #[clippy::version = "1.62.0"]
2428 pub BYTES_COUNT_TO_LEN,
2430 "Using `bytes().count()` when `len()` performs the same functionality"
2433 declare_clippy_lint! {
2434 /// ### What it does
2435 /// Checks for calls to `ends_with` with possible file extensions
2436 /// and suggests to use a case-insensitive approach instead.
2438 /// ### Why is this bad?
2439 /// `ends_with` is case-sensitive and may not detect files with a valid extension.
2443 /// fn is_rust_file(filename: &str) -> bool {
2444 /// filename.ends_with(".rs")
2449 /// fn is_rust_file(filename: &str) -> bool {
2450 /// let filename = std::path::Path::new(filename);
2451 /// filename.extension()
2452 /// .map_or(false, |ext| ext.eq_ignore_ascii_case("rs"))
2455 #[clippy::version = "1.51.0"]
2456 pub CASE_SENSITIVE_FILE_EXTENSION_COMPARISONS,
2458 "Checks for calls to ends_with with case-sensitive file extensions"
2461 declare_clippy_lint! {
2462 /// ### What it does
2463 /// Checks for using `x.get(0)` instead of
2466 /// ### Why is this bad?
2467 /// Using `x.first()` is easier to read and has the same
2472 /// let x = vec![2, 3, 5];
2473 /// let first_element = x.get(0);
2478 /// let x = vec![2, 3, 5];
2479 /// let first_element = x.first();
2481 #[clippy::version = "1.63.0"]
2484 "Using `x.get(0)` when `x.first()` is simpler"
2487 pub struct Methods {
2488 avoid_breaking_exported_api: bool,
2489 msrv: Option<RustcVersion>,
2490 allow_expect_in_tests: bool,
2491 allow_unwrap_in_tests: bool,
2497 avoid_breaking_exported_api: bool,
2498 msrv: Option<RustcVersion>,
2499 allow_expect_in_tests: bool,
2500 allow_unwrap_in_tests: bool,
2503 avoid_breaking_exported_api,
2505 allow_expect_in_tests,
2506 allow_unwrap_in_tests,
2511 impl_lint_pass!(Methods => [
2514 SHOULD_IMPLEMENT_TRAIT,
2515 WRONG_SELF_CONVENTION,
2517 UNWRAP_OR_ELSE_DEFAULT,
2519 RESULT_MAP_OR_INTO_OPTION,
2521 BIND_INSTEAD_OF_MAP,
2530 ITER_OVEREAGER_CLONED,
2531 CLONED_INSTEAD_OF_COPIED,
2533 INEFFICIENT_TO_STRING,
2535 SINGLE_CHAR_PATTERN,
2536 SINGLE_CHAR_ADD_STR,
2540 FILTER_MAP_IDENTITY,
2548 ITERATOR_STEP_BY_ZERO,
2557 STRING_EXTEND_CHARS,
2558 ITER_CLONED_COLLECT,
2562 UNNECESSARY_FILTER_MAP,
2563 UNNECESSARY_FIND_MAP,
2566 UNINIT_ASSUMED_INIT,
2567 MANUAL_SATURATING_ARITHMETIC,
2570 OPTION_AS_REF_DEREF,
2571 UNNECESSARY_LAZY_EVALUATIONS,
2572 MAP_COLLECT_RESULT_UNIT,
2573 FROM_ITER_INSTEAD_OF_COLLECT,
2581 UNNECESSARY_TO_OWNED,
2584 NEEDLESS_OPTION_AS_DEREF,
2585 IS_DIGIT_ASCII_RADIX,
2586 NEEDLESS_OPTION_TAKE,
2589 ITER_ON_SINGLE_ITEMS,
2590 ITER_ON_EMPTY_COLLECTIONS,
2593 CASE_SENSITIVE_FILE_EXTENSION_COMPARISONS,
2597 /// Extracts a method call name, args, and `Span` of the method name.
2598 fn method_call<'tcx>(recv: &'tcx hir::Expr<'tcx>) -> Option<(&'tcx str, &'tcx [hir::Expr<'tcx>], Span)> {
2599 if let ExprKind::MethodCall(path, args, _) = recv.kind {
2600 if !args.iter().any(|e| e.span.from_expansion()) {
2601 let name = path.ident.name.as_str();
2602 return Some((name, args, path.ident.span));
2608 impl<'tcx> LateLintPass<'tcx> for Methods {
2609 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) {
2610 if expr.span.from_expansion() {
2614 self.check_methods(cx, expr);
2617 hir::ExprKind::Call(func, args) => {
2618 from_iter_instead_of_collect::check(cx, expr, args, func);
2620 hir::ExprKind::MethodCall(method_call, args, _) => {
2621 let method_span = method_call.ident.span;
2622 or_fun_call::check(cx, expr, method_span, method_call.ident.as_str(), args);
2623 expect_fun_call::check(cx, expr, method_span, method_call.ident.as_str(), args);
2624 clone_on_copy::check(cx, expr, method_call.ident.name, args);
2625 clone_on_ref_ptr::check(cx, expr, method_call.ident.name, args);
2626 inefficient_to_string::check(cx, expr, method_call.ident.name, args);
2627 single_char_add_str::check(cx, expr, args);
2628 into_iter_on_ref::check(cx, expr, method_span, method_call.ident.name, args);
2629 single_char_pattern::check(cx, expr, method_call.ident.name, args);
2630 unnecessary_to_owned::check(cx, expr, method_call.ident.name, args, self.msrv);
2632 hir::ExprKind::Binary(op, lhs, rhs) if op.node == hir::BinOpKind::Eq || op.node == hir::BinOpKind::Ne => {
2633 let mut info = BinaryExprInfo {
2637 eq: op.node == hir::BinOpKind::Eq,
2639 lint_binary_expr_with_method_call(cx, &mut info);
2645 #[allow(clippy::too_many_lines)]
2646 fn check_impl_item(&mut self, cx: &LateContext<'tcx>, impl_item: &'tcx hir::ImplItem<'_>) {
2647 if in_external_macro(cx.sess(), impl_item.span) {
2650 let name = impl_item.ident.name.as_str();
2651 let parent = cx.tcx.hir().get_parent_item(impl_item.hir_id());
2652 let item = cx.tcx.hir().expect_item(parent);
2653 let self_ty = cx.tcx.type_of(item.def_id);
2655 let implements_trait = matches!(item.kind, hir::ItemKind::Impl(hir::Impl { of_trait: Some(_), .. }));
2657 if let hir::ImplItemKind::Fn(ref sig, id) = impl_item.kind;
2658 if let Some(first_arg) = iter_input_pats(sig.decl, cx.tcx.hir().body(id)).next();
2660 let method_sig = cx.tcx.fn_sig(impl_item.def_id);
2661 let method_sig = cx.tcx.erase_late_bound_regions(method_sig);
2663 let first_arg_ty = method_sig.inputs().iter().next();
2665 // check conventions w.r.t. conversion method names and predicates
2666 if let Some(first_arg_ty) = first_arg_ty;
2669 // if this impl block implements a trait, lint in trait definition instead
2670 if !implements_trait && cx.access_levels.is_exported(impl_item.def_id) {
2671 // check missing trait implementations
2672 for method_config in &TRAIT_METHODS {
2673 if name == method_config.method_name &&
2674 sig.decl.inputs.len() == method_config.param_count &&
2675 method_config.output_type.matches(&sig.decl.output) &&
2676 method_config.self_kind.matches(cx, self_ty, *first_arg_ty) &&
2677 fn_header_equals(method_config.fn_header, sig.header) &&
2678 method_config.lifetime_param_cond(impl_item)
2682 SHOULD_IMPLEMENT_TRAIT,
2685 "method `{}` can be confused for the standard trait method `{}::{}`",
2686 method_config.method_name,
2687 method_config.trait_name,
2688 method_config.method_name
2692 "consider implementing the trait `{}` or choosing a less ambiguous method name",
2693 method_config.trait_name
2700 if sig.decl.implicit_self.has_implicit_self()
2701 && !(self.avoid_breaking_exported_api
2702 && cx.access_levels.is_exported(impl_item.def_id))
2704 wrong_self_convention::check(
2717 // if this impl block implements a trait, lint in trait definition instead
2718 if implements_trait {
2722 if let hir::ImplItemKind::Fn(_, _) = impl_item.kind {
2723 let ret_ty = return_ty(cx, impl_item.hir_id());
2725 // walk the return type and check for Self (this does not check associated types)
2726 if let Some(self_adt) = self_ty.ty_adt_def() {
2727 if contains_adt_constructor(ret_ty, self_adt) {
2730 } else if contains_ty(ret_ty, self_ty) {
2734 // if return type is impl trait, check the associated types
2735 if let ty::Opaque(def_id, _) = *ret_ty.kind() {
2736 // one of the associated types must be Self
2737 for &(predicate, _span) in cx.tcx.explicit_item_bounds(def_id) {
2738 if let ty::PredicateKind::Projection(projection_predicate) = predicate.kind().skip_binder() {
2739 let assoc_ty = match projection_predicate.term {
2740 ty::Term::Ty(ty) => ty,
2741 ty::Term::Const(_c) => continue,
2743 // walk the associated type and check for Self
2744 if let Some(self_adt) = self_ty.ty_adt_def() {
2745 if contains_adt_constructor(assoc_ty, self_adt) {
2748 } else if contains_ty(assoc_ty, self_ty) {
2755 if name == "new" && ret_ty != self_ty {
2760 "methods called `new` usually return `Self`",
2766 fn check_trait_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx TraitItem<'_>) {
2767 if in_external_macro(cx.tcx.sess, item.span) {
2772 if let TraitItemKind::Fn(ref sig, _) = item.kind;
2773 if sig.decl.implicit_self.has_implicit_self();
2774 if let Some(first_arg_ty) = sig.decl.inputs.iter().next();
2777 let first_arg_span = first_arg_ty.span;
2778 let first_arg_ty = hir_ty_to_ty(cx.tcx, first_arg_ty);
2779 let self_ty = TraitRef::identity(cx.tcx, item.def_id.to_def_id()).self_ty().skip_binder();
2780 wrong_self_convention::check(
2782 item.ident.name.as_str(),
2793 if item.ident.name == sym::new;
2794 if let TraitItemKind::Fn(_, _) = item.kind;
2795 let ret_ty = return_ty(cx, item.hir_id());
2796 let self_ty = TraitRef::identity(cx.tcx, item.def_id.to_def_id()).self_ty().skip_binder();
2797 if !contains_ty(ret_ty, self_ty);
2804 "methods called `new` usually return `Self`",
2810 extract_msrv_attr!(LateContext);
2814 #[allow(clippy::too_many_lines)]
2815 fn check_methods<'tcx>(&self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
2816 if let Some((name, [recv, args @ ..], span)) = method_call(expr) {
2817 match (name, args) {
2818 ("add" | "offset" | "sub" | "wrapping_offset" | "wrapping_add" | "wrapping_sub", [_arg]) => {
2819 zst_offset::check(cx, expr, recv);
2821 ("and_then", [arg]) => {
2822 let biom_option_linted = bind_instead_of_map::OptionAndThenSome::check(cx, expr, recv, arg);
2823 let biom_result_linted = bind_instead_of_map::ResultAndThenOk::check(cx, expr, recv, arg);
2824 if !biom_option_linted && !biom_result_linted {
2825 unnecessary_lazy_eval::check(cx, expr, recv, arg, "and");
2828 ("as_deref" | "as_deref_mut", []) => {
2829 needless_option_as_deref::check(cx, expr, recv, name);
2831 ("as_mut", []) => useless_asref::check(cx, expr, "as_mut", recv),
2832 ("as_ref", []) => useless_asref::check(cx, expr, "as_ref", recv),
2833 ("assume_init", []) => uninit_assumed_init::check(cx, expr, recv),
2834 ("cloned", []) => cloned_instead_of_copied::check(cx, expr, recv, span, self.msrv),
2835 ("collect", []) => match method_call(recv) {
2836 Some((name @ ("cloned" | "copied"), [recv2], _)) => {
2837 iter_cloned_collect::check(cx, name, expr, recv2);
2839 Some(("map", [m_recv, m_arg], _)) => {
2840 map_collect_result_unit::check(cx, expr, m_recv, m_arg, recv);
2842 Some(("take", [take_self_arg, take_arg], _)) => {
2843 if meets_msrv(self.msrv, msrvs::STR_REPEAT) {
2844 manual_str_repeat::check(cx, expr, recv, take_self_arg, take_arg);
2849 ("count", []) if is_trait_method(cx, expr, sym::Iterator) => match method_call(recv) {
2850 Some(("cloned", [recv2], _)) => iter_overeager_cloned::check(cx, expr, recv, recv2, true, false),
2851 Some((name2 @ ("into_iter" | "iter" | "iter_mut"), [recv2], _)) => {
2852 iter_count::check(cx, expr, recv2, name2);
2854 Some(("map", [_, arg], _)) => suspicious_map::check(cx, expr, recv, arg),
2855 Some(("filter", [recv2, arg], _)) => bytecount::check(cx, expr, recv2, arg),
2856 Some(("bytes", [recv2], _)) => bytes_count_to_len::check(cx, expr, recv, recv2),
2859 ("drain", [arg]) => {
2860 iter_with_drain::check(cx, expr, recv, span, arg);
2862 ("ends_with", [arg]) => {
2863 if let ExprKind::MethodCall(_, _, span) = expr.kind {
2864 case_sensitive_file_extension_comparisons::check(cx, expr, span, recv, arg);
2867 ("expect", [_]) => match method_call(recv) {
2868 Some(("ok", [recv], _)) => ok_expect::check(cx, expr, recv),
2869 Some(("err", [recv], err_span)) => err_expect::check(cx, expr, recv, self.msrv, span, err_span),
2870 _ => expect_used::check(cx, expr, recv, false, self.allow_expect_in_tests),
2872 ("expect_err", [_]) => expect_used::check(cx, expr, recv, true, self.allow_expect_in_tests),
2873 ("extend", [arg]) => {
2874 string_extend_chars::check(cx, expr, recv, arg);
2875 extend_with_drain::check(cx, expr, recv, arg);
2877 ("filter_map", [arg]) => {
2878 unnecessary_filter_map::check(cx, expr, arg, name);
2879 filter_map_identity::check(cx, expr, arg, span);
2881 ("find_map", [arg]) => {
2882 unnecessary_filter_map::check(cx, expr, arg, name);
2884 ("flat_map", [arg]) => {
2885 flat_map_identity::check(cx, expr, arg, span);
2886 flat_map_option::check(cx, expr, arg, span);
2888 ("flatten", []) => match method_call(recv) {
2889 Some(("map", [recv, map_arg], map_span)) => map_flatten::check(cx, expr, recv, map_arg, map_span),
2890 Some(("cloned", [recv2], _)) => iter_overeager_cloned::check(cx, expr, recv, recv2, false, true),
2893 ("fold", [init, acc]) => unnecessary_fold::check(cx, expr, init, acc, span),
2894 ("for_each", [_]) => {
2895 if let Some(("inspect", [_, _], span2)) = method_call(recv) {
2896 inspect_for_each::check(cx, expr, span2);
2900 get_first::check(cx, expr, recv, arg);
2901 get_last_with_len::check(cx, expr, recv, arg);
2903 ("get_or_insert_with", [arg]) => unnecessary_lazy_eval::check(cx, expr, recv, arg, "get_or_insert"),
2904 ("is_file", []) => filetype_is_file::check(cx, expr, recv),
2905 ("is_digit", [radix]) => is_digit_ascii_radix::check(cx, expr, recv, radix, self.msrv),
2906 ("is_none", []) => check_is_some_is_none(cx, expr, recv, false),
2907 ("is_some", []) => check_is_some_is_none(cx, expr, recv, true),
2908 ("iter" | "iter_mut" | "into_iter", []) => {
2909 iter_on_single_or_empty_collections::check(cx, expr, name, recv);
2911 ("join", [join_arg]) => {
2912 if let Some(("collect", _, span)) = method_call(recv) {
2913 unnecessary_join::check(cx, expr, recv, join_arg, span);
2916 ("last", []) | ("skip", [_]) => {
2917 if let Some((name2, [recv2, args2 @ ..], _span2)) = method_call(recv) {
2918 if let ("cloned", []) = (name2, args2) {
2919 iter_overeager_cloned::check(cx, expr, recv, recv2, false, false);
2923 (name @ ("map" | "map_err"), [m_arg]) => {
2924 if let Some((name, [recv2, args @ ..], span2)) = method_call(recv) {
2925 match (name, args) {
2926 ("as_mut", []) => option_as_ref_deref::check(cx, expr, recv2, m_arg, true, self.msrv),
2927 ("as_ref", []) => option_as_ref_deref::check(cx, expr, recv2, m_arg, false, self.msrv),
2928 ("filter", [f_arg]) => {
2929 filter_map::check(cx, expr, recv2, f_arg, span2, recv, m_arg, span, false);
2931 ("find", [f_arg]) => {
2932 filter_map::check(cx, expr, recv2, f_arg, span2, recv, m_arg, span, true);
2937 map_identity::check(cx, expr, recv, m_arg, name, span);
2939 ("map_or", [def, map]) => option_map_or_none::check(cx, expr, recv, def, map),
2941 if let Some((name2, [recv2, args2 @ ..], _)) = method_call(recv) {
2942 match (name2, args2) {
2943 ("cloned", []) => iter_overeager_cloned::check(cx, expr, recv, recv2, false, false),
2944 ("filter", [arg]) => filter_next::check(cx, expr, recv2, arg),
2945 ("filter_map", [arg]) => filter_map_next::check(cx, expr, recv2, arg, self.msrv),
2946 ("iter", []) => iter_next_slice::check(cx, expr, recv2),
2947 ("skip", [arg]) => iter_skip_next::check(cx, expr, recv2, arg),
2948 ("skip_while", [_]) => skip_while_next::check(cx, expr),
2953 ("nth", [n_arg]) => match method_call(recv) {
2954 Some(("bytes", [recv2], _)) => bytes_nth::check(cx, expr, recv2, n_arg),
2955 Some(("cloned", [recv2], _)) => iter_overeager_cloned::check(cx, expr, recv, recv2, false, false),
2956 Some(("iter", [recv2], _)) => iter_nth::check(cx, expr, recv2, recv, n_arg, false),
2957 Some(("iter_mut", [recv2], _)) => iter_nth::check(cx, expr, recv2, recv, n_arg, true),
2958 _ => iter_nth_zero::check(cx, expr, recv, n_arg),
2960 ("ok_or_else", [arg]) => unnecessary_lazy_eval::check(cx, expr, recv, arg, "ok_or"),
2961 ("or_else", [arg]) => {
2962 if !bind_instead_of_map::ResultOrElseErrInfo::check(cx, expr, recv, arg) {
2963 unnecessary_lazy_eval::check(cx, expr, recv, arg, "or");
2966 ("splitn" | "rsplitn", [count_arg, pat_arg]) => {
2967 if let Some((Constant::Int(count), _)) = constant(cx, cx.typeck_results(), count_arg) {
2968 suspicious_splitn::check(cx, name, expr, recv, count);
2969 str_splitn::check(cx, name, expr, recv, pat_arg, count, self.msrv);
2972 ("splitn_mut" | "rsplitn_mut", [count_arg, _]) => {
2973 if let Some((Constant::Int(count), _)) = constant(cx, cx.typeck_results(), count_arg) {
2974 suspicious_splitn::check(cx, name, expr, recv, count);
2977 ("step_by", [arg]) => iterator_step_by_zero::check(cx, expr, arg),
2978 ("take", [_arg]) => {
2979 if let Some((name2, [recv2, args2 @ ..], _span2)) = method_call(recv) {
2980 if let ("cloned", []) = (name2, args2) {
2981 iter_overeager_cloned::check(cx, expr, recv, recv2, false, false);
2985 ("take", []) => needless_option_take::check(cx, expr, recv),
2986 ("then", [arg]) => {
2987 if !meets_msrv(self.msrv, msrvs::BOOL_THEN_SOME) {
2990 unnecessary_lazy_eval::check(cx, expr, recv, arg, "then_some");
2992 ("to_os_string" | "to_owned" | "to_path_buf" | "to_vec", []) => {
2993 implicit_clone::check(cx, name, expr, recv);
2996 match method_call(recv) {
2997 Some(("get", [recv, get_arg], _)) => {
2998 get_unwrap::check(cx, expr, recv, get_arg, false);
3000 Some(("get_mut", [recv, get_arg], _)) => {
3001 get_unwrap::check(cx, expr, recv, get_arg, true);
3003 Some(("or", [recv, or_arg], or_span)) => {
3004 or_then_unwrap::check(cx, expr, recv, or_arg, or_span);
3008 unwrap_used::check(cx, expr, recv, false, self.allow_unwrap_in_tests);
3010 ("unwrap_err", []) => unwrap_used::check(cx, expr, recv, true, self.allow_unwrap_in_tests),
3011 ("unwrap_or", [u_arg]) => match method_call(recv) {
3012 Some((arith @ ("checked_add" | "checked_sub" | "checked_mul"), [lhs, rhs], _)) => {
3013 manual_saturating_arithmetic::check(cx, expr, lhs, rhs, u_arg, &arith["checked_".len()..]);
3015 Some(("map", [m_recv, m_arg], span)) => {
3016 option_map_unwrap_or::check(cx, expr, m_recv, m_arg, recv, u_arg, span);
3018 Some(("then_some", [t_recv, t_arg], _)) => {
3019 obfuscated_if_else::check(cx, expr, t_recv, t_arg, u_arg);
3023 ("unwrap_or_else", [u_arg]) => match method_call(recv) {
3024 Some(("map", [recv, map_arg], _))
3025 if map_unwrap_or::check(cx, expr, recv, map_arg, u_arg, self.msrv) => {},
3027 unwrap_or_else_default::check(cx, expr, recv, u_arg);
3028 unnecessary_lazy_eval::check(cx, expr, recv, u_arg, "unwrap_or");
3031 ("replace" | "replacen", [arg1, arg2] | [arg1, arg2, _]) => {
3032 no_effect_replace::check(cx, expr, arg1, arg2);
3040 fn check_is_some_is_none(cx: &LateContext<'_>, expr: &Expr<'_>, recv: &Expr<'_>, is_some: bool) {
3041 if let Some((name @ ("find" | "position" | "rposition"), [f_recv, arg], span)) = method_call(recv) {
3042 search_is_some::check(cx, expr, name, is_some, f_recv, arg, recv, span);
3046 /// Used for `lint_binary_expr_with_method_call`.
3047 #[derive(Copy, Clone)]
3048 struct BinaryExprInfo<'a> {
3049 expr: &'a hir::Expr<'a>,
3050 chain: &'a hir::Expr<'a>,
3051 other: &'a hir::Expr<'a>,
3055 /// Checks for the `CHARS_NEXT_CMP` and `CHARS_LAST_CMP` lints.
3056 fn lint_binary_expr_with_method_call(cx: &LateContext<'_>, info: &mut BinaryExprInfo<'_>) {
3057 macro_rules! lint_with_both_lhs_and_rhs {
3058 ($func:expr, $cx:expr, $info:ident) => {
3059 if !$func($cx, $info) {
3060 ::std::mem::swap(&mut $info.chain, &mut $info.other);
3061 if $func($cx, $info) {
3068 lint_with_both_lhs_and_rhs!(chars_next_cmp::check, cx, info);
3069 lint_with_both_lhs_and_rhs!(chars_last_cmp::check, cx, info);
3070 lint_with_both_lhs_and_rhs!(chars_next_cmp_with_unwrap::check, cx, info);
3071 lint_with_both_lhs_and_rhs!(chars_last_cmp_with_unwrap::check, cx, info);
3074 const FN_HEADER: hir::FnHeader = hir::FnHeader {
3075 unsafety: hir::Unsafety::Normal,
3076 constness: hir::Constness::NotConst,
3077 asyncness: hir::IsAsync::NotAsync,
3078 abi: rustc_target::spec::abi::Abi::Rust,
3081 struct ShouldImplTraitCase {
3082 trait_name: &'static str,
3083 method_name: &'static str,
3085 fn_header: hir::FnHeader,
3086 // implicit self kind expected (none, self, &self, ...)
3087 self_kind: SelfKind,
3088 // checks against the output type
3089 output_type: OutType,
3090 // certain methods with explicit lifetimes can't implement the equivalent trait method
3091 lint_explicit_lifetime: bool,
3093 impl ShouldImplTraitCase {
3095 trait_name: &'static str,
3096 method_name: &'static str,
3098 fn_header: hir::FnHeader,
3099 self_kind: SelfKind,
3100 output_type: OutType,
3101 lint_explicit_lifetime: bool,
3102 ) -> ShouldImplTraitCase {
3103 ShouldImplTraitCase {
3110 lint_explicit_lifetime,
3114 fn lifetime_param_cond(&self, impl_item: &hir::ImplItem<'_>) -> bool {
3115 self.lint_explicit_lifetime
3116 || !impl_item.generics.params.iter().any(|p| {
3119 hir::GenericParamKind::Lifetime {
3120 kind: hir::LifetimeParamKind::Explicit
3128 const TRAIT_METHODS: [ShouldImplTraitCase; 30] = [
3129 ShouldImplTraitCase::new("std::ops::Add", "add", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3130 ShouldImplTraitCase::new("std::convert::AsMut", "as_mut", 1, FN_HEADER, SelfKind::RefMut, OutType::Ref, true),
3131 ShouldImplTraitCase::new("std::convert::AsRef", "as_ref", 1, FN_HEADER, SelfKind::Ref, OutType::Ref, true),
3132 ShouldImplTraitCase::new("std::ops::BitAnd", "bitand", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3133 ShouldImplTraitCase::new("std::ops::BitOr", "bitor", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3134 ShouldImplTraitCase::new("std::ops::BitXor", "bitxor", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3135 ShouldImplTraitCase::new("std::borrow::Borrow", "borrow", 1, FN_HEADER, SelfKind::Ref, OutType::Ref, true),
3136 ShouldImplTraitCase::new("std::borrow::BorrowMut", "borrow_mut", 1, FN_HEADER, SelfKind::RefMut, OutType::Ref, true),
3137 ShouldImplTraitCase::new("std::clone::Clone", "clone", 1, FN_HEADER, SelfKind::Ref, OutType::Any, true),
3138 ShouldImplTraitCase::new("std::cmp::Ord", "cmp", 2, FN_HEADER, SelfKind::Ref, OutType::Any, true),
3139 // FIXME: default doesn't work
3140 ShouldImplTraitCase::new("std::default::Default", "default", 0, FN_HEADER, SelfKind::No, OutType::Any, true),
3141 ShouldImplTraitCase::new("std::ops::Deref", "deref", 1, FN_HEADER, SelfKind::Ref, OutType::Ref, true),
3142 ShouldImplTraitCase::new("std::ops::DerefMut", "deref_mut", 1, FN_HEADER, SelfKind::RefMut, OutType::Ref, true),
3143 ShouldImplTraitCase::new("std::ops::Div", "div", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3144 ShouldImplTraitCase::new("std::ops::Drop", "drop", 1, FN_HEADER, SelfKind::RefMut, OutType::Unit, true),
3145 ShouldImplTraitCase::new("std::cmp::PartialEq", "eq", 2, FN_HEADER, SelfKind::Ref, OutType::Bool, true),
3146 ShouldImplTraitCase::new("std::iter::FromIterator", "from_iter", 1, FN_HEADER, SelfKind::No, OutType::Any, true),
3147 ShouldImplTraitCase::new("std::str::FromStr", "from_str", 1, FN_HEADER, SelfKind::No, OutType::Any, true),
3148 ShouldImplTraitCase::new("std::hash::Hash", "hash", 2, FN_HEADER, SelfKind::Ref, OutType::Unit, true),
3149 ShouldImplTraitCase::new("std::ops::Index", "index", 2, FN_HEADER, SelfKind::Ref, OutType::Ref, true),
3150 ShouldImplTraitCase::new("std::ops::IndexMut", "index_mut", 2, FN_HEADER, SelfKind::RefMut, OutType::Ref, true),
3151 ShouldImplTraitCase::new("std::iter::IntoIterator", "into_iter", 1, FN_HEADER, SelfKind::Value, OutType::Any, true),
3152 ShouldImplTraitCase::new("std::ops::Mul", "mul", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3153 ShouldImplTraitCase::new("std::ops::Neg", "neg", 1, FN_HEADER, SelfKind::Value, OutType::Any, true),
3154 ShouldImplTraitCase::new("std::iter::Iterator", "next", 1, FN_HEADER, SelfKind::RefMut, OutType::Any, false),
3155 ShouldImplTraitCase::new("std::ops::Not", "not", 1, FN_HEADER, SelfKind::Value, OutType::Any, true),
3156 ShouldImplTraitCase::new("std::ops::Rem", "rem", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3157 ShouldImplTraitCase::new("std::ops::Shl", "shl", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3158 ShouldImplTraitCase::new("std::ops::Shr", "shr", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3159 ShouldImplTraitCase::new("std::ops::Sub", "sub", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3162 #[derive(Clone, Copy, PartialEq, Eq, Debug)]
3171 fn matches<'a>(self, cx: &LateContext<'a>, parent_ty: Ty<'a>, ty: Ty<'a>) -> bool {
3172 fn matches_value<'a>(cx: &LateContext<'a>, parent_ty: Ty<'a>, ty: Ty<'a>) -> bool {
3173 if ty == parent_ty {
3175 } else if ty.is_box() {
3176 ty.boxed_ty() == parent_ty
3177 } else if is_type_diagnostic_item(cx, ty, sym::Rc) || is_type_diagnostic_item(cx, ty, sym::Arc) {
3178 if let ty::Adt(_, substs) = ty.kind() {
3179 substs.types().next().map_or(false, |t| t == parent_ty)
3188 fn matches_ref<'a>(cx: &LateContext<'a>, mutability: hir::Mutability, parent_ty: Ty<'a>, ty: Ty<'a>) -> bool {
3189 if let ty::Ref(_, t, m) = *ty.kind() {
3190 return m == mutability && t == parent_ty;
3193 let trait_path = match mutability {
3194 hir::Mutability::Not => &paths::ASREF_TRAIT,
3195 hir::Mutability::Mut => &paths::ASMUT_TRAIT,
3198 let trait_def_id = match get_trait_def_id(cx, trait_path) {
3200 None => return false,
3202 implements_trait(cx, ty, trait_def_id, &[parent_ty.into()])
3205 fn matches_none<'a>(cx: &LateContext<'a>, parent_ty: Ty<'a>, ty: Ty<'a>) -> bool {
3206 !matches_value(cx, parent_ty, ty)
3207 && !matches_ref(cx, hir::Mutability::Not, parent_ty, ty)
3208 && !matches_ref(cx, hir::Mutability::Mut, parent_ty, ty)
3212 Self::Value => matches_value(cx, parent_ty, ty),
3213 Self::Ref => matches_ref(cx, hir::Mutability::Not, parent_ty, ty) || ty == parent_ty && is_copy(cx, ty),
3214 Self::RefMut => matches_ref(cx, hir::Mutability::Mut, parent_ty, ty),
3215 Self::No => matches_none(cx, parent_ty, ty),
3220 fn description(self) -> &'static str {
3222 Self::Value => "`self` by value",
3223 Self::Ref => "`self` by reference",
3224 Self::RefMut => "`self` by mutable reference",
3225 Self::No => "no `self`",
3230 #[derive(Clone, Copy)]
3239 fn matches(self, ty: &hir::FnRetTy<'_>) -> bool {
3240 let is_unit = |ty: &hir::Ty<'_>| matches!(ty.kind, hir::TyKind::Tup(&[]));
3242 (Self::Unit, &hir::FnRetTy::DefaultReturn(_)) => true,
3243 (Self::Unit, &hir::FnRetTy::Return(ty)) if is_unit(ty) => true,
3244 (Self::Bool, &hir::FnRetTy::Return(ty)) if is_bool(ty) => true,
3245 (Self::Any, &hir::FnRetTy::Return(ty)) if !is_unit(ty) => true,
3246 (Self::Ref, &hir::FnRetTy::Return(ty)) => matches!(ty.kind, hir::TyKind::Rptr(_, _)),
3252 fn is_bool(ty: &hir::Ty<'_>) -> bool {
3253 if let hir::TyKind::Path(QPath::Resolved(_, path)) = ty.kind {
3254 matches!(path.res, Res::PrimTy(PrimTy::Bool))
3260 fn fn_header_equals(expected: hir::FnHeader, actual: hir::FnHeader) -> bool {
3261 expected.constness == actual.constness
3262 && expected.unsafety == actual.unsafety
3263 && expected.asyncness == actual.asyncness