1 mod bind_instead_of_map;
3 mod bytes_count_to_len;
5 mod case_sensitive_file_extension_comparisons;
7 mod chars_cmp_with_unwrap;
9 mod chars_last_cmp_with_unwrap;
11 mod chars_next_cmp_with_unwrap;
14 mod cloned_instead_of_copied;
18 mod extend_with_drain;
21 mod filter_map_identity;
24 mod flat_map_identity;
26 mod from_iter_instead_of_collect;
28 mod get_last_with_len;
31 mod inefficient_to_string;
34 mod is_digit_ascii_radix;
35 mod iter_cloned_collect;
40 mod iter_on_single_or_empty_collections;
41 mod iter_overeager_cloned;
44 mod iterator_step_by_zero;
46 mod manual_saturating_arithmetic;
47 mod manual_str_repeat;
49 mod map_collect_result_unit;
55 mod needless_option_as_deref;
56 mod needless_option_take;
57 mod no_effect_replace;
58 mod obfuscated_if_else;
61 mod option_as_ref_deref;
62 mod option_map_or_none;
63 mod option_map_unwrap_or;
66 mod path_buf_push_overwrite;
67 mod range_zip_with_len;
70 mod single_char_add_str;
71 mod single_char_insert_string;
72 mod single_char_pattern;
73 mod single_char_push_string;
75 mod stable_sort_primitive;
77 mod string_extend_chars;
79 mod suspicious_splitn;
80 mod uninit_assumed_init;
82 mod unnecessary_filter_map;
84 mod unnecessary_iter_cloned;
86 mod unnecessary_lazy_eval;
87 mod unnecessary_sort_by;
88 mod unnecessary_to_owned;
89 mod unwrap_or_else_default;
93 mod wrong_self_convention;
96 use bind_instead_of_map::BindInsteadOfMap;
97 use clippy_utils::consts::{constant, Constant};
98 use clippy_utils::diagnostics::{span_lint, span_lint_and_help};
99 use clippy_utils::ty::{contains_adt_constructor, contains_ty, implements_trait, is_copy, is_type_diagnostic_item};
101 contains_return, get_trait_def_id, is_trait_method, iter_input_pats, meets_msrv, msrvs, paths, return_ty,
103 use if_chain::if_chain;
104 use rustc_hir as hir;
105 use rustc_hir::def::Res;
106 use rustc_hir::{Expr, ExprKind, PrimTy, QPath, TraitItem, TraitItemKind};
107 use rustc_lint::{LateContext, LateLintPass, LintContext};
108 use rustc_middle::lint::in_external_macro;
109 use rustc_middle::ty::{self, TraitRef, Ty};
110 use rustc_semver::RustcVersion;
111 use rustc_session::{declare_tool_lint, impl_lint_pass};
112 use rustc_span::{sym, Span};
113 use rustc_typeck::hir_ty_to_ty;
115 declare_clippy_lint! {
117 /// Checks for usages of `cloned()` on an `Iterator` or `Option` where
118 /// `copied()` could be used instead.
120 /// ### Why is this bad?
121 /// `copied()` is better because it guarantees that the type being cloned
122 /// implements `Copy`.
126 /// [1, 2, 3].iter().cloned();
130 /// [1, 2, 3].iter().copied();
132 #[clippy::version = "1.53.0"]
133 pub CLONED_INSTEAD_OF_COPIED,
135 "used `cloned` where `copied` could be used instead"
138 declare_clippy_lint! {
140 /// Checks for usage of `_.cloned().<func>()` where call to `.cloned()` can be postponed.
142 /// ### Why is this bad?
143 /// It's often inefficient to clone all elements of an iterator, when eventually, only some
144 /// of them will be consumed.
146 /// ### Known Problems
147 /// This `lint` removes the side of effect of cloning items in the iterator.
148 /// A code that relies on that side-effect could fail.
152 /// # let vec = vec!["string".to_string()];
153 /// vec.iter().cloned().take(10);
154 /// vec.iter().cloned().last();
159 /// # let vec = vec!["string".to_string()];
160 /// vec.iter().take(10).cloned();
161 /// vec.iter().last().cloned();
163 #[clippy::version = "1.60.0"]
164 pub ITER_OVEREAGER_CLONED,
166 "using `cloned()` early with `Iterator::iter()` can lead to some performance inefficiencies"
169 declare_clippy_lint! {
171 /// Checks for usages of `Iterator::flat_map()` where `filter_map()` could be
174 /// ### Why is this bad?
175 /// When applicable, `filter_map()` is more clear since it shows that
176 /// `Option` is used to produce 0 or 1 items.
180 /// let nums: Vec<i32> = ["1", "2", "whee!"].iter().flat_map(|x| x.parse().ok()).collect();
184 /// let nums: Vec<i32> = ["1", "2", "whee!"].iter().filter_map(|x| x.parse().ok()).collect();
186 #[clippy::version = "1.53.0"]
189 "used `flat_map` where `filter_map` could be used instead"
192 declare_clippy_lint! {
194 /// Checks for `.unwrap()` or `.unwrap_err()` calls on `Result`s and `.unwrap()` call on `Option`s.
196 /// ### Why is this bad?
197 /// It is better to handle the `None` or `Err` case,
198 /// or at least call `.expect(_)` with a more helpful message. Still, for a lot of
199 /// quick-and-dirty code, `unwrap` is a good choice, which is why this lint is
200 /// `Allow` by default.
202 /// `result.unwrap()` will let the thread panic on `Err` values.
203 /// Normally, you want to implement more sophisticated error handling,
204 /// and propagate errors upwards with `?` operator.
206 /// Even if you want to panic on errors, not all `Error`s implement good
207 /// messages on display. Therefore, it may be beneficial to look at the places
208 /// where they may get displayed. Activate this lint to do just that.
212 /// # let option = Some(1);
213 /// # let result: Result<usize, ()> = Ok(1);
220 /// # let option = Some(1);
221 /// # let result: Result<usize, ()> = Ok(1);
222 /// option.expect("more helpful message");
223 /// result.expect("more helpful message");
226 /// If [expect_used](#expect_used) is enabled, instead:
228 /// # let option = Some(1);
229 /// # let result: Result<usize, ()> = Ok(1);
236 #[clippy::version = "1.45.0"]
239 "using `.unwrap()` on `Result` or `Option`, which should at least get a better message using `expect()`"
242 declare_clippy_lint! {
244 /// Checks for `.expect()` or `.expect_err()` calls on `Result`s and `.expect()` call on `Option`s.
246 /// ### Why is this bad?
247 /// Usually it is better to handle the `None` or `Err` case.
248 /// Still, for a lot of quick-and-dirty code, `expect` is a good choice, which is why
249 /// this lint is `Allow` by default.
251 /// `result.expect()` will let the thread panic on `Err`
252 /// values. Normally, you want to implement more sophisticated error handling,
253 /// and propagate errors upwards with `?` operator.
257 /// # let option = Some(1);
258 /// # let result: Result<usize, ()> = Ok(1);
259 /// option.expect("one");
260 /// result.expect("one");
265 /// # let option = Some(1);
266 /// # let result: Result<usize, ()> = Ok(1);
273 #[clippy::version = "1.45.0"]
276 "using `.expect()` on `Result` or `Option`, which might be better handled"
279 declare_clippy_lint! {
281 /// Checks for methods that should live in a trait
282 /// implementation of a `std` trait (see [llogiq's blog
283 /// post](http://llogiq.github.io/2015/07/30/traits.html) for further
284 /// information) instead of an inherent implementation.
286 /// ### Why is this bad?
287 /// Implementing the traits improve ergonomics for users of
288 /// the code, often with very little cost. Also people seeing a `mul(...)`
290 /// may expect `*` to work equally, so you should have good reason to disappoint
297 /// fn add(&self, other: &X) -> X {
303 #[clippy::version = "pre 1.29.0"]
304 pub SHOULD_IMPLEMENT_TRAIT,
306 "defining a method that should be implementing a std trait"
309 declare_clippy_lint! {
311 /// Checks for methods with certain name prefixes and which
312 /// doesn't match how self is taken. The actual rules are:
314 /// |Prefix |Postfix |`self` taken | `self` type |
315 /// |-------|------------|-------------------------------|--------------|
316 /// |`as_` | none |`&self` or `&mut self` | any |
317 /// |`from_`| none | none | any |
318 /// |`into_`| none |`self` | any |
319 /// |`is_` | none |`&mut self` or `&self` or none | any |
320 /// |`to_` | `_mut` |`&mut self` | any |
321 /// |`to_` | not `_mut` |`self` | `Copy` |
322 /// |`to_` | not `_mut` |`&self` | not `Copy` |
324 /// Note: Clippy doesn't trigger methods with `to_` prefix in:
325 /// - Traits definition.
326 /// Clippy can not tell if a type that implements a trait is `Copy` or not.
327 /// - Traits implementation, when `&self` is taken.
328 /// The method signature is controlled by the trait and often `&self` is required for all types that implement the trait
329 /// (see e.g. the `std::string::ToString` trait).
331 /// Clippy allows `Pin<&Self>` and `Pin<&mut Self>` if `&self` and `&mut self` is required.
333 /// Please find more info here:
334 /// https://rust-lang.github.io/api-guidelines/naming.html#ad-hoc-conversions-follow-as_-to_-into_-conventions-c-conv
336 /// ### Why is this bad?
337 /// Consistency breeds readability. If you follow the
338 /// conventions, your users won't be surprised that they, e.g., need to supply a
339 /// mutable reference to a `as_..` function.
345 /// fn as_str(self) -> &'static str {
351 #[clippy::version = "pre 1.29.0"]
352 pub WRONG_SELF_CONVENTION,
354 "defining a method named with an established prefix (like \"into_\") that takes `self` with the wrong convention"
357 declare_clippy_lint! {
359 /// Checks for usage of `ok().expect(..)`.
361 /// ### Why is this bad?
362 /// Because you usually call `expect()` on the `Result`
363 /// directly to get a better error message.
365 /// ### Known problems
366 /// The error type needs to implement `Debug`
370 /// # let x = Ok::<_, ()>(());
371 /// x.ok().expect("why did I do this again?");
376 /// # let x = Ok::<_, ()>(());
377 /// x.expect("why did I do this again?");
379 #[clippy::version = "pre 1.29.0"]
382 "using `ok().expect()`, which gives worse error messages than calling `expect` directly on the Result"
385 declare_clippy_lint! {
387 /// Checks for `.err().expect()` calls on the `Result` type.
389 /// ### Why is this bad?
390 /// `.expect_err()` can be called directly to avoid the extra type conversion from `err()`.
394 /// let x: Result<u32, &str> = Ok(10);
395 /// x.err().expect("Testing err().expect()");
399 /// let x: Result<u32, &str> = Ok(10);
400 /// x.expect_err("Testing expect_err");
402 #[clippy::version = "1.62.0"]
405 r#"using `.err().expect("")` when `.expect_err("")` can be used"#
408 declare_clippy_lint! {
410 /// Checks for usages of `_.unwrap_or_else(Default::default)` on `Option` and
413 /// ### Why is this bad?
414 /// Readability, these can be written as `_.unwrap_or_default`, which is
415 /// simpler and more concise.
419 /// # let x = Some(1);
420 /// x.unwrap_or_else(Default::default);
421 /// x.unwrap_or_else(u32::default);
426 /// # let x = Some(1);
427 /// x.unwrap_or_default();
429 #[clippy::version = "1.56.0"]
430 pub UNWRAP_OR_ELSE_DEFAULT,
432 "using `.unwrap_or_else(Default::default)`, which is more succinctly expressed as `.unwrap_or_default()`"
435 declare_clippy_lint! {
437 /// Checks for usage of `option.map(_).unwrap_or(_)` or `option.map(_).unwrap_or_else(_)` or
438 /// `result.map(_).unwrap_or_else(_)`.
440 /// ### Why is this bad?
441 /// Readability, these can be written more concisely (resp.) as
442 /// `option.map_or(_, _)`, `option.map_or_else(_, _)` and `result.map_or_else(_, _)`.
444 /// ### Known problems
445 /// The order of the arguments is not in execution order
449 /// # let option = Some(1);
450 /// # let result: Result<usize, ()> = Ok(1);
451 /// # fn some_function(foo: ()) -> usize { 1 }
452 /// option.map(|a| a + 1).unwrap_or(0);
453 /// result.map(|a| a + 1).unwrap_or_else(some_function);
458 /// # let option = Some(1);
459 /// # let result: Result<usize, ()> = Ok(1);
460 /// # fn some_function(foo: ()) -> usize { 1 }
461 /// option.map_or(0, |a| a + 1);
462 /// result.map_or_else(some_function, |a| a + 1);
464 #[clippy::version = "1.45.0"]
467 "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)`"
470 declare_clippy_lint! {
472 /// Checks for usage of `_.map_or(None, _)`.
474 /// ### Why is this bad?
475 /// Readability, this can be written more concisely as
478 /// ### Known problems
479 /// The order of the arguments is not in execution order.
483 /// # let opt = Some(1);
484 /// opt.map_or(None, |a| Some(a + 1));
489 /// # let opt = Some(1);
490 /// opt.and_then(|a| Some(a + 1));
492 #[clippy::version = "pre 1.29.0"]
493 pub OPTION_MAP_OR_NONE,
495 "using `Option.map_or(None, f)`, which is more succinctly expressed as `and_then(f)`"
498 declare_clippy_lint! {
500 /// Checks for usage of `_.map_or(None, Some)`.
502 /// ### Why is this bad?
503 /// Readability, this can be written more concisely as
508 /// # let r: Result<u32, &str> = Ok(1);
509 /// assert_eq!(Some(1), r.map_or(None, Some));
514 /// # let r: Result<u32, &str> = Ok(1);
515 /// assert_eq!(Some(1), r.ok());
517 #[clippy::version = "1.44.0"]
518 pub RESULT_MAP_OR_INTO_OPTION,
520 "using `Result.map_or(None, Some)`, which is more succinctly expressed as `ok()`"
523 declare_clippy_lint! {
525 /// Checks for usage of `_.and_then(|x| Some(y))`, `_.and_then(|x| Ok(y))` or
526 /// `_.or_else(|x| Err(y))`.
528 /// ### Why is this bad?
529 /// Readability, this can be written more concisely as
530 /// `_.map(|x| y)` or `_.map_err(|x| y)`.
534 /// # fn opt() -> Option<&'static str> { Some("42") }
535 /// # fn res() -> Result<&'static str, &'static str> { Ok("42") }
536 /// let _ = opt().and_then(|s| Some(s.len()));
537 /// let _ = res().and_then(|s| if s.len() == 42 { Ok(10) } else { Ok(20) });
538 /// let _ = res().or_else(|s| if s.len() == 42 { Err(10) } else { Err(20) });
541 /// The correct use would be:
544 /// # fn opt() -> Option<&'static str> { Some("42") }
545 /// # fn res() -> Result<&'static str, &'static str> { Ok("42") }
546 /// let _ = opt().map(|s| s.len());
547 /// let _ = res().map(|s| if s.len() == 42 { 10 } else { 20 });
548 /// let _ = res().map_err(|s| if s.len() == 42 { 10 } else { 20 });
550 #[clippy::version = "1.45.0"]
551 pub BIND_INSTEAD_OF_MAP,
553 "using `Option.and_then(|x| Some(y))`, which is more succinctly expressed as `map(|x| y)`"
556 declare_clippy_lint! {
558 /// Checks for usage of `_.filter(_).next()`.
560 /// ### Why is this bad?
561 /// Readability, this can be written more concisely as
566 /// # let vec = vec![1];
567 /// vec.iter().filter(|x| **x == 0).next();
572 /// # let vec = vec![1];
573 /// vec.iter().find(|x| **x == 0);
575 #[clippy::version = "pre 1.29.0"]
578 "using `filter(p).next()`, which is more succinctly expressed as `.find(p)`"
581 declare_clippy_lint! {
583 /// Checks for usage of `_.skip_while(condition).next()`.
585 /// ### Why is this bad?
586 /// Readability, this can be written more concisely as
587 /// `_.find(!condition)`.
591 /// # let vec = vec![1];
592 /// vec.iter().skip_while(|x| **x == 0).next();
597 /// # let vec = vec![1];
598 /// vec.iter().find(|x| **x != 0);
600 #[clippy::version = "1.42.0"]
603 "using `skip_while(p).next()`, which is more succinctly expressed as `.find(!p)`"
606 declare_clippy_lint! {
608 /// Checks for usage of `_.map(_).flatten(_)` on `Iterator` and `Option`
610 /// ### Why is this bad?
611 /// Readability, this can be written more concisely as
612 /// `_.flat_map(_)` for `Iterator` or `_.and_then(_)` for `Option`
616 /// let vec = vec![vec![1]];
617 /// let opt = Some(5);
619 /// vec.iter().map(|x| x.iter()).flatten();
620 /// opt.map(|x| Some(x * 2)).flatten();
625 /// # let vec = vec![vec![1]];
626 /// # let opt = Some(5);
627 /// vec.iter().flat_map(|x| x.iter());
628 /// opt.and_then(|x| Some(x * 2));
630 #[clippy::version = "1.31.0"]
633 "using combinations of `flatten` and `map` which can usually be written as a single method call"
636 declare_clippy_lint! {
638 /// Checks for usage of `_.filter(_).map(_)` that can be written more simply
639 /// as `filter_map(_)`.
641 /// ### Why is this bad?
642 /// Redundant code in the `filter` and `map` operations is poor style and
647 /// # #![allow(unused)]
649 /// .filter(|n| n.checked_add(1).is_some())
650 /// .map(|n| n.checked_add(1).unwrap());
655 /// # #[allow(unused)]
656 /// (0_i32..10).filter_map(|n| n.checked_add(1));
658 #[clippy::version = "1.51.0"]
659 pub MANUAL_FILTER_MAP,
661 "using `_.filter(_).map(_)` in a way that can be written more simply as `filter_map(_)`"
664 declare_clippy_lint! {
666 /// Checks for usage of `_.find(_).map(_)` that can be written more simply
667 /// as `find_map(_)`.
669 /// ### Why is this bad?
670 /// Redundant code in the `find` and `map` operations is poor style and
676 /// .find(|n| n.checked_add(1).is_some())
677 /// .map(|n| n.checked_add(1).unwrap());
682 /// (0_i32..10).find_map(|n| n.checked_add(1));
684 #[clippy::version = "1.51.0"]
687 "using `_.find(_).map(_)` in a way that can be written more simply as `find_map(_)`"
690 declare_clippy_lint! {
692 /// Checks for usage of `_.filter_map(_).next()`.
694 /// ### Why is this bad?
695 /// Readability, this can be written more concisely as
700 /// (0..3).filter_map(|x| if x == 2 { Some(x) } else { None }).next();
702 /// Can be written as
705 /// (0..3).find_map(|x| if x == 2 { Some(x) } else { None });
707 #[clippy::version = "1.36.0"]
710 "using combination of `filter_map` and `next` which can usually be written as a single method call"
713 declare_clippy_lint! {
715 /// Checks for usage of `flat_map(|x| x)`.
717 /// ### Why is this bad?
718 /// Readability, this can be written more concisely by using `flatten`.
722 /// # let iter = vec![vec![0]].into_iter();
723 /// iter.flat_map(|x| x);
725 /// Can be written as
727 /// # let iter = vec![vec![0]].into_iter();
730 #[clippy::version = "1.39.0"]
731 pub FLAT_MAP_IDENTITY,
733 "call to `flat_map` where `flatten` is sufficient"
736 declare_clippy_lint! {
738 /// Checks for an iterator or string search (such as `find()`,
739 /// `position()`, or `rposition()`) followed by a call to `is_some()` or `is_none()`.
741 /// ### Why is this bad?
742 /// Readability, this can be written more concisely as:
743 /// * `_.any(_)`, or `_.contains(_)` for `is_some()`,
744 /// * `!_.any(_)`, or `!_.contains(_)` for `is_none()`.
748 /// # #![allow(unused)]
749 /// let vec = vec![1];
750 /// vec.iter().find(|x| **x == 0).is_some();
752 /// "hello world".find("world").is_none();
757 /// let vec = vec![1];
758 /// vec.iter().any(|x| *x == 0);
760 /// # #[allow(unused)]
761 /// !"hello world".contains("world");
763 #[clippy::version = "pre 1.29.0"]
766 "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()`)"
769 declare_clippy_lint! {
771 /// Checks for usage of `.chars().next()` on a `str` to check
772 /// if it starts with a given char.
774 /// ### Why is this bad?
775 /// Readability, this can be written more concisely as
776 /// `_.starts_with(_)`.
780 /// let name = "foo";
781 /// if name.chars().next() == Some('_') {};
786 /// let name = "foo";
787 /// if name.starts_with('_') {};
789 #[clippy::version = "pre 1.29.0"]
792 "using `.chars().next()` to check if a string starts with a char"
795 declare_clippy_lint! {
797 /// Checks for calls to `.or(foo(..))`, `.unwrap_or(foo(..))`,
798 /// etc., and suggests to use `or_else`, `unwrap_or_else`, etc., or
799 /// `unwrap_or_default` instead.
801 /// ### Why is this bad?
802 /// The function will always be called and potentially
803 /// allocate an object acting as the default.
805 /// ### Known problems
806 /// If the function has side-effects, not calling it will
807 /// change the semantic of the program, but you shouldn't rely on that anyway.
811 /// # let foo = Some(String::new());
812 /// foo.unwrap_or(String::new());
817 /// # let foo = Some(String::new());
818 /// foo.unwrap_or_else(String::new);
822 /// # let foo = Some(String::new());
823 /// foo.unwrap_or_default();
825 #[clippy::version = "pre 1.29.0"]
828 "using any `*or` method with a function call, which suggests `*or_else`"
831 declare_clippy_lint! {
833 /// Checks for `.or(…).unwrap()` calls to Options and Results.
835 /// ### Why is this bad?
836 /// You should use `.unwrap_or(…)` instead for clarity.
840 /// # let fallback = "fallback";
842 /// # type Error = &'static str;
843 /// # let result: Result<&str, Error> = Err("error");
844 /// let value = result.or::<Error>(Ok(fallback)).unwrap();
847 /// # let option: Option<&str> = None;
848 /// let value = option.or(Some(fallback)).unwrap();
852 /// # let fallback = "fallback";
854 /// # let result: Result<&str, &str> = Err("error");
855 /// let value = result.unwrap_or(fallback);
858 /// # let option: Option<&str> = None;
859 /// let value = option.unwrap_or(fallback);
861 #[clippy::version = "1.61.0"]
864 "checks for `.or(…).unwrap()` calls to Options and Results."
867 declare_clippy_lint! {
869 /// Checks for calls to `.expect(&format!(...))`, `.expect(foo(..))`,
870 /// etc., and suggests to use `unwrap_or_else` instead
872 /// ### Why is this bad?
873 /// The function will always be called.
875 /// ### Known problems
876 /// If the function has side-effects, not calling it will
877 /// change the semantics of the program, but you shouldn't rely on that anyway.
881 /// # let foo = Some(String::new());
882 /// # let err_code = "418";
883 /// # let err_msg = "I'm a teapot";
884 /// foo.expect(&format!("Err {}: {}", err_code, err_msg));
888 /// # let foo = Some(String::new());
889 /// foo.expect(format!("Err {}: {}", err_code, err_msg).as_str());
894 /// # let foo = Some(String::new());
895 /// # let err_code = "418";
896 /// # let err_msg = "I'm a teapot";
897 /// foo.unwrap_or_else(|| panic!("Err {}: {}", err_code, err_msg));
899 #[clippy::version = "pre 1.29.0"]
902 "using any `expect` method with a function call"
905 declare_clippy_lint! {
907 /// Checks for usage of `.clone()` on a `Copy` type.
909 /// ### Why is this bad?
910 /// The only reason `Copy` types implement `Clone` is for
911 /// generics, not for using the `clone` method on a concrete type.
917 #[clippy::version = "pre 1.29.0"]
920 "using `clone` on a `Copy` type"
923 declare_clippy_lint! {
925 /// Checks for usage of `.clone()` on a ref-counted pointer,
926 /// (`Rc`, `Arc`, `rc::Weak`, or `sync::Weak`), and suggests calling Clone via unified
927 /// function syntax instead (e.g., `Rc::clone(foo)`).
929 /// ### Why is this bad?
930 /// Calling '.clone()' on an Rc, Arc, or Weak
931 /// can obscure the fact that only the pointer is being cloned, not the underlying
936 /// # use std::rc::Rc;
937 /// let x = Rc::new(1);
944 /// # use std::rc::Rc;
945 /// # let x = Rc::new(1);
948 #[clippy::version = "pre 1.29.0"]
949 pub CLONE_ON_REF_PTR,
951 "using 'clone' on a ref-counted pointer"
954 declare_clippy_lint! {
956 /// Checks for usage of `.clone()` on an `&&T`.
958 /// ### Why is this bad?
959 /// Cloning an `&&T` copies the inner `&T`, instead of
960 /// cloning the underlying `T`.
967 /// let z = y.clone();
968 /// println!("{:p} {:p}", *y, z); // prints out the same pointer
971 #[clippy::version = "pre 1.29.0"]
972 pub CLONE_DOUBLE_REF,
974 "using `clone` on `&&T`"
977 declare_clippy_lint! {
979 /// Checks for usage of `.to_string()` on an `&&T` where
980 /// `T` implements `ToString` directly (like `&&str` or `&&String`).
982 /// ### Why is this bad?
983 /// This bypasses the specialized implementation of
984 /// `ToString` and instead goes through the more expensive string formatting
989 /// // Generic implementation for `T: Display` is used (slow)
990 /// ["foo", "bar"].iter().map(|s| s.to_string());
992 /// // OK, the specialized impl is used
993 /// ["foo", "bar"].iter().map(|&s| s.to_string());
995 #[clippy::version = "1.40.0"]
996 pub INEFFICIENT_TO_STRING,
998 "using `to_string` on `&&T` where `T: ToString`"
1001 declare_clippy_lint! {
1002 /// ### What it does
1003 /// Checks for `new` not returning a type that contains `Self`.
1005 /// ### Why is this bad?
1006 /// As a convention, `new` methods are used to make a new
1007 /// instance of a type.
1010 /// In an impl block:
1013 /// # struct NotAFoo;
1015 /// fn new() -> NotAFoo {
1023 /// struct Bar(Foo);
1025 /// // Bad. The type name must contain `Self`
1026 /// fn new() -> Bar {
1034 /// # struct FooError;
1036 /// // Good. Return type contains `Self`
1037 /// fn new() -> Result<Foo, FooError> {
1043 /// Or in a trait definition:
1045 /// pub trait Trait {
1046 /// // Bad. The type name must contain `Self`
1052 /// pub trait Trait {
1053 /// // Good. Return type contains `Self`
1054 /// fn new() -> Self;
1057 #[clippy::version = "pre 1.29.0"]
1058 pub NEW_RET_NO_SELF,
1060 "not returning type containing `Self` in a `new` method"
1063 declare_clippy_lint! {
1064 /// ### What it does
1065 /// Checks for string methods that receive a single-character
1066 /// `str` as an argument, e.g., `_.split("x")`.
1068 /// ### Why is this bad?
1069 /// Performing these methods using a `char` is faster than
1072 /// ### Known problems
1073 /// Does not catch multi-byte unicode characters.
1084 #[clippy::version = "pre 1.29.0"]
1085 pub SINGLE_CHAR_PATTERN,
1087 "using a single-character str where a char could be used, e.g., `_.split(\"x\")`"
1090 declare_clippy_lint! {
1091 /// ### What it does
1092 /// Checks for calling `.step_by(0)` on iterators which panics.
1094 /// ### Why is this bad?
1095 /// This very much looks like an oversight. Use `panic!()` instead if you
1096 /// actually intend to panic.
1099 /// ```rust,should_panic
1100 /// for x in (0..100).step_by(0) {
1104 #[clippy::version = "pre 1.29.0"]
1105 pub ITERATOR_STEP_BY_ZERO,
1107 "using `Iterator::step_by(0)`, which will panic at runtime"
1110 declare_clippy_lint! {
1111 /// ### What it does
1112 /// Checks for indirect collection of populated `Option`
1114 /// ### Why is this bad?
1115 /// `Option` is like a collection of 0-1 things, so `flatten`
1116 /// automatically does this without suspicious-looking `unwrap` calls.
1120 /// let _ = std::iter::empty::<Option<i32>>().filter(Option::is_some).map(Option::unwrap);
1124 /// let _ = std::iter::empty::<Option<i32>>().flatten();
1126 #[clippy::version = "1.53.0"]
1127 pub OPTION_FILTER_MAP,
1129 "filtering `Option` for `Some` then force-unwrapping, which can be one type-safe operation"
1132 declare_clippy_lint! {
1133 /// ### What it does
1134 /// Checks for the use of `iter.nth(0)`.
1136 /// ### Why is this bad?
1137 /// `iter.next()` is equivalent to
1138 /// `iter.nth(0)`, as they both consume the next element,
1139 /// but is more readable.
1143 /// # use std::collections::HashSet;
1144 /// # let mut s = HashSet::new();
1146 /// let x = s.iter().nth(0);
1151 /// # use std::collections::HashSet;
1152 /// # let mut s = HashSet::new();
1154 /// let x = s.iter().next();
1156 #[clippy::version = "1.42.0"]
1159 "replace `iter.nth(0)` with `iter.next()`"
1162 declare_clippy_lint! {
1163 /// ### What it does
1164 /// Checks for use of `.iter().nth()` (and the related
1165 /// `.iter_mut().nth()`) on standard library types with *O*(1) element access.
1167 /// ### Why is this bad?
1168 /// `.get()` and `.get_mut()` are more efficient and more
1173 /// let some_vec = vec![0, 1, 2, 3];
1174 /// let bad_vec = some_vec.iter().nth(3);
1175 /// let bad_slice = &some_vec[..].iter().nth(3);
1177 /// The correct use would be:
1179 /// let some_vec = vec![0, 1, 2, 3];
1180 /// let bad_vec = some_vec.get(3);
1181 /// let bad_slice = &some_vec[..].get(3);
1183 #[clippy::version = "pre 1.29.0"]
1186 "using `.iter().nth()` on a standard library type with O(1) element access"
1189 declare_clippy_lint! {
1190 /// ### What it does
1191 /// Checks for use of `.skip(x).next()` on iterators.
1193 /// ### Why is this bad?
1194 /// `.nth(x)` is cleaner
1198 /// let some_vec = vec![0, 1, 2, 3];
1199 /// let bad_vec = some_vec.iter().skip(3).next();
1200 /// let bad_slice = &some_vec[..].iter().skip(3).next();
1202 /// The correct use would be:
1204 /// let some_vec = vec![0, 1, 2, 3];
1205 /// let bad_vec = some_vec.iter().nth(3);
1206 /// let bad_slice = &some_vec[..].iter().nth(3);
1208 #[clippy::version = "pre 1.29.0"]
1211 "using `.skip(x).next()` on an iterator"
1214 declare_clippy_lint! {
1215 /// ### What it does
1216 /// Checks for use of `.drain(..)` on `Vec` and `VecDeque` for iteration.
1218 /// ### Why is this bad?
1219 /// `.into_iter()` is simpler with better performance.
1223 /// # use std::collections::HashSet;
1224 /// let mut foo = vec![0, 1, 2, 3];
1225 /// let bar: HashSet<usize> = foo.drain(..).collect();
1229 /// # use std::collections::HashSet;
1230 /// let foo = vec![0, 1, 2, 3];
1231 /// let bar: HashSet<usize> = foo.into_iter().collect();
1233 #[clippy::version = "1.61.0"]
1234 pub ITER_WITH_DRAIN,
1236 "replace `.drain(..)` with `.into_iter()`"
1239 declare_clippy_lint! {
1240 /// ### What it does
1241 /// Checks for using `x.get(x.len() - 1)` instead of
1244 /// ### Why is this bad?
1245 /// Using `x.last()` is easier to read and has the same
1248 /// Note that using `x[x.len() - 1]` is semantically different from
1249 /// `x.last()`. Indexing into the array will panic on out-of-bounds
1250 /// accesses, while `x.get()` and `x.last()` will return `None`.
1252 /// There is another lint (get_unwrap) that covers the case of using
1253 /// `x.get(index).unwrap()` instead of `x[index]`.
1257 /// let x = vec![2, 3, 5];
1258 /// let last_element = x.get(x.len() - 1);
1263 /// let x = vec![2, 3, 5];
1264 /// let last_element = x.last();
1266 #[clippy::version = "1.37.0"]
1267 pub GET_LAST_WITH_LEN,
1269 "Using `x.get(x.len() - 1)` when `x.last()` is correct and simpler"
1272 declare_clippy_lint! {
1273 /// ### What it does
1274 /// Checks for use of `.get().unwrap()` (or
1275 /// `.get_mut().unwrap`) on a standard library type which implements `Index`
1277 /// ### Why is this bad?
1278 /// Using the Index trait (`[]`) is more clear and more
1281 /// ### Known problems
1282 /// Not a replacement for error handling: Using either
1283 /// `.unwrap()` or the Index trait (`[]`) carries the risk of causing a `panic`
1284 /// if the value being accessed is `None`. If the use of `.get().unwrap()` is a
1285 /// temporary placeholder for dealing with the `Option` type, then this does
1286 /// not mitigate the need for error handling. If there is a chance that `.get()`
1287 /// will be `None` in your program, then it is advisable that the `None` case
1288 /// is handled in a future refactor instead of using `.unwrap()` or the Index
1293 /// let mut some_vec = vec![0, 1, 2, 3];
1294 /// let last = some_vec.get(3).unwrap();
1295 /// *some_vec.get_mut(0).unwrap() = 1;
1297 /// The correct use would be:
1299 /// let mut some_vec = vec![0, 1, 2, 3];
1300 /// let last = some_vec[3];
1301 /// some_vec[0] = 1;
1303 #[clippy::version = "pre 1.29.0"]
1306 "using `.get().unwrap()` or `.get_mut().unwrap()` when using `[]` would work instead"
1309 declare_clippy_lint! {
1310 /// ### What it does
1311 /// Checks for occurrences where one vector gets extended instead of append
1313 /// ### Why is this bad?
1314 /// Using `append` instead of `extend` is more concise and faster
1318 /// let mut a = vec![1, 2, 3];
1319 /// let mut b = vec![4, 5, 6];
1321 /// a.extend(b.drain(..));
1326 /// let mut a = vec![1, 2, 3];
1327 /// let mut b = vec![4, 5, 6];
1329 /// a.append(&mut b);
1331 #[clippy::version = "1.55.0"]
1332 pub EXTEND_WITH_DRAIN,
1334 "using vec.append(&mut vec) to move the full range of a vector to another"
1337 declare_clippy_lint! {
1338 /// ### What it does
1339 /// Checks for the use of `.extend(s.chars())` where s is a
1340 /// `&str` or `String`.
1342 /// ### Why is this bad?
1343 /// `.push_str(s)` is clearer
1347 /// let abc = "abc";
1348 /// let def = String::from("def");
1349 /// let mut s = String::new();
1350 /// s.extend(abc.chars());
1351 /// s.extend(def.chars());
1353 /// The correct use would be:
1355 /// let abc = "abc";
1356 /// let def = String::from("def");
1357 /// let mut s = String::new();
1358 /// s.push_str(abc);
1359 /// s.push_str(&def);
1361 #[clippy::version = "pre 1.29.0"]
1362 pub STRING_EXTEND_CHARS,
1364 "using `x.extend(s.chars())` where s is a `&str` or `String`"
1367 declare_clippy_lint! {
1368 /// ### What it does
1369 /// Checks for the use of `.cloned().collect()` on slice to
1372 /// ### Why is this bad?
1373 /// `.to_vec()` is clearer
1377 /// let s = [1, 2, 3, 4, 5];
1378 /// let s2: Vec<isize> = s[..].iter().cloned().collect();
1380 /// The better use would be:
1382 /// let s = [1, 2, 3, 4, 5];
1383 /// let s2: Vec<isize> = s.to_vec();
1385 #[clippy::version = "pre 1.29.0"]
1386 pub ITER_CLONED_COLLECT,
1388 "using `.cloned().collect()` on slice to create a `Vec`"
1391 declare_clippy_lint! {
1392 /// ### What it does
1393 /// Checks for usage of `_.chars().last()` or
1394 /// `_.chars().next_back()` on a `str` to check if it ends with a given char.
1396 /// ### Why is this bad?
1397 /// Readability, this can be written more concisely as
1398 /// `_.ends_with(_)`.
1402 /// # let name = "_";
1403 /// name.chars().last() == Some('_') || name.chars().next_back() == Some('-');
1408 /// # let name = "_";
1409 /// name.ends_with('_') || name.ends_with('-');
1411 #[clippy::version = "pre 1.29.0"]
1414 "using `.chars().last()` or `.chars().next_back()` to check if a string ends with a char"
1417 declare_clippy_lint! {
1418 /// ### What it does
1419 /// Checks for usage of `.as_ref()` or `.as_mut()` where the
1420 /// types before and after the call are the same.
1422 /// ### Why is this bad?
1423 /// The call is unnecessary.
1427 /// # fn do_stuff(x: &[i32]) {}
1428 /// let x: &[i32] = &[1, 2, 3, 4, 5];
1429 /// do_stuff(x.as_ref());
1431 /// The correct use would be:
1433 /// # fn do_stuff(x: &[i32]) {}
1434 /// let x: &[i32] = &[1, 2, 3, 4, 5];
1437 #[clippy::version = "pre 1.29.0"]
1440 "using `as_ref` where the types before and after the call are the same"
1443 declare_clippy_lint! {
1444 /// ### What it does
1445 /// Checks for using `fold` when a more succinct alternative exists.
1446 /// Specifically, this checks for `fold`s which could be replaced by `any`, `all`,
1447 /// `sum` or `product`.
1449 /// ### Why is this bad?
1454 /// # #[allow(unused)]
1455 /// (0..3).fold(false, |acc, x| acc || x > 2);
1460 /// (0..3).any(|x| x > 2);
1462 #[clippy::version = "pre 1.29.0"]
1463 pub UNNECESSARY_FOLD,
1465 "using `fold` when a more succinct alternative exists"
1468 declare_clippy_lint! {
1469 /// ### What it does
1470 /// Checks for `filter_map` calls that could be replaced by `filter` or `map`.
1471 /// More specifically it checks if the closure provided is only performing one of the
1472 /// filter or map operations and suggests the appropriate option.
1474 /// ### Why is this bad?
1475 /// Complexity. The intent is also clearer if only a single
1476 /// operation is being performed.
1480 /// let _ = (0..3).filter_map(|x| if x > 2 { Some(x) } else { None });
1482 /// // As there is no transformation of the argument this could be written as:
1483 /// let _ = (0..3).filter(|&x| x > 2);
1487 /// let _ = (0..4).filter_map(|x| Some(x + 1));
1489 /// // As there is no conditional check on the argument this could be written as:
1490 /// let _ = (0..4).map(|x| x + 1);
1492 #[clippy::version = "1.31.0"]
1493 pub UNNECESSARY_FILTER_MAP,
1495 "using `filter_map` when a more succinct alternative exists"
1498 declare_clippy_lint! {
1499 /// ### What it does
1500 /// Checks for `find_map` calls that could be replaced by `find` or `map`. More
1501 /// specifically it checks if the closure provided is only performing one of the
1502 /// find or map operations and suggests the appropriate option.
1504 /// ### Why is this bad?
1505 /// Complexity. The intent is also clearer if only a single
1506 /// operation is being performed.
1510 /// let _ = (0..3).find_map(|x| if x > 2 { Some(x) } else { None });
1512 /// // As there is no transformation of the argument this could be written as:
1513 /// let _ = (0..3).find(|&x| x > 2);
1517 /// let _ = (0..4).find_map(|x| Some(x + 1));
1519 /// // As there is no conditional check on the argument this could be written as:
1520 /// let _ = (0..4).map(|x| x + 1).next();
1522 #[clippy::version = "1.61.0"]
1523 pub UNNECESSARY_FIND_MAP,
1525 "using `find_map` when a more succinct alternative exists"
1528 declare_clippy_lint! {
1529 /// ### What it does
1530 /// Checks for `into_iter` calls on references which should be replaced by `iter`
1533 /// ### Why is this bad?
1534 /// Readability. Calling `into_iter` on a reference will not move out its
1535 /// content into the resulting iterator, which is confusing. It is better just call `iter` or
1536 /// `iter_mut` directly.
1540 /// # let vec = vec![3, 4, 5];
1541 /// (&vec).into_iter();
1546 /// # let vec = vec![3, 4, 5];
1549 #[clippy::version = "1.32.0"]
1550 pub INTO_ITER_ON_REF,
1552 "using `.into_iter()` on a reference"
1555 declare_clippy_lint! {
1556 /// ### What it does
1557 /// Checks for calls to `map` followed by a `count`.
1559 /// ### Why is this bad?
1560 /// It looks suspicious. Maybe `map` was confused with `filter`.
1561 /// If the `map` call is intentional, this should be rewritten
1562 /// using `inspect`. Or, if you intend to drive the iterator to
1563 /// completion, you can just use `for_each` instead.
1567 /// let _ = (0..3).map(|x| x + 2).count();
1569 #[clippy::version = "1.39.0"]
1572 "suspicious usage of map"
1575 declare_clippy_lint! {
1576 /// ### What it does
1577 /// Checks for `MaybeUninit::uninit().assume_init()`.
1579 /// ### Why is this bad?
1580 /// For most types, this is undefined behavior.
1582 /// ### Known problems
1583 /// For now, we accept empty tuples and tuples / arrays
1584 /// of `MaybeUninit`. There may be other types that allow uninitialized
1585 /// data, but those are not yet rigorously defined.
1589 /// // Beware the UB
1590 /// use std::mem::MaybeUninit;
1592 /// let _: usize = unsafe { MaybeUninit::uninit().assume_init() };
1595 /// Note that the following is OK:
1598 /// use std::mem::MaybeUninit;
1600 /// let _: [MaybeUninit<bool>; 5] = unsafe {
1601 /// MaybeUninit::uninit().assume_init()
1604 #[clippy::version = "1.39.0"]
1605 pub UNINIT_ASSUMED_INIT,
1607 "`MaybeUninit::uninit().assume_init()`"
1610 declare_clippy_lint! {
1611 /// ### What it does
1612 /// Checks for `.checked_add/sub(x).unwrap_or(MAX/MIN)`.
1614 /// ### Why is this bad?
1615 /// These can be written simply with `saturating_add/sub` methods.
1619 /// # let y: u32 = 0;
1620 /// # let x: u32 = 100;
1621 /// let add = x.checked_add(y).unwrap_or(u32::MAX);
1622 /// let sub = x.checked_sub(y).unwrap_or(u32::MIN);
1625 /// can be written using dedicated methods for saturating addition/subtraction as:
1628 /// # let y: u32 = 0;
1629 /// # let x: u32 = 100;
1630 /// let add = x.saturating_add(y);
1631 /// let sub = x.saturating_sub(y);
1633 #[clippy::version = "1.39.0"]
1634 pub MANUAL_SATURATING_ARITHMETIC,
1636 "`.checked_add/sub(x).unwrap_or(MAX/MIN)`"
1639 declare_clippy_lint! {
1640 /// ### What it does
1641 /// Checks for `offset(_)`, `wrapping_`{`add`, `sub`}, etc. on raw pointers to
1642 /// zero-sized types
1644 /// ### Why is this bad?
1645 /// This is a no-op, and likely unintended
1649 /// unsafe { (&() as *const ()).offset(1) };
1651 #[clippy::version = "1.41.0"]
1654 "Check for offset calculations on raw pointers to zero-sized types"
1657 declare_clippy_lint! {
1658 /// ### What it does
1659 /// Checks for `FileType::is_file()`.
1661 /// ### Why is this bad?
1662 /// When people testing a file type with `FileType::is_file`
1663 /// they are testing whether a path is something they can get bytes from. But
1664 /// `is_file` doesn't cover special file types in unix-like systems, and doesn't cover
1665 /// symlink in windows. Using `!FileType::is_dir()` is a better way to that intention.
1670 /// let metadata = std::fs::metadata("foo.txt")?;
1671 /// let filetype = metadata.file_type();
1673 /// if filetype.is_file() {
1676 /// # Ok::<_, std::io::Error>(())
1680 /// should be written as:
1684 /// let metadata = std::fs::metadata("foo.txt")?;
1685 /// let filetype = metadata.file_type();
1687 /// if !filetype.is_dir() {
1690 /// # Ok::<_, std::io::Error>(())
1693 #[clippy::version = "1.42.0"]
1694 pub FILETYPE_IS_FILE,
1696 "`FileType::is_file` is not recommended to test for readable file type"
1699 declare_clippy_lint! {
1700 /// ### What it does
1701 /// Checks for usage of `_.as_ref().map(Deref::deref)` or it's aliases (such as String::as_str).
1703 /// ### Why is this bad?
1704 /// Readability, this can be written more concisely as
1709 /// # let opt = Some("".to_string());
1710 /// opt.as_ref().map(String::as_str)
1713 /// Can be written as
1715 /// # let opt = Some("".to_string());
1719 #[clippy::version = "1.42.0"]
1720 pub OPTION_AS_REF_DEREF,
1722 "using `as_ref().map(Deref::deref)`, which is more succinctly expressed as `as_deref()`"
1725 declare_clippy_lint! {
1726 /// ### What it does
1727 /// Checks for usage of `iter().next()` on a Slice or an Array
1729 /// ### Why is this bad?
1730 /// These can be shortened into `.get()`
1734 /// # let a = [1, 2, 3];
1735 /// # let b = vec![1, 2, 3];
1736 /// a[2..].iter().next();
1737 /// b.iter().next();
1739 /// should be written as:
1741 /// # let a = [1, 2, 3];
1742 /// # let b = vec![1, 2, 3];
1746 #[clippy::version = "1.46.0"]
1747 pub ITER_NEXT_SLICE,
1749 "using `.iter().next()` on a sliced array, which can be shortened to just `.get()`"
1752 declare_clippy_lint! {
1753 /// ### What it does
1754 /// Warns when using `push_str`/`insert_str` with a single-character string literal
1755 /// where `push`/`insert` with a `char` would work fine.
1757 /// ### Why is this bad?
1758 /// It's less clear that we are pushing a single character.
1762 /// # let mut string = String::new();
1763 /// string.insert_str(0, "R");
1764 /// string.push_str("R");
1769 /// # let mut string = String::new();
1770 /// string.insert(0, 'R');
1771 /// string.push('R');
1773 #[clippy::version = "1.49.0"]
1774 pub SINGLE_CHAR_ADD_STR,
1776 "`push_str()` or `insert_str()` used with a single-character string literal as parameter"
1779 declare_clippy_lint! {
1780 /// ### What it does
1781 /// As the counterpart to `or_fun_call`, this lint looks for unnecessary
1782 /// lazily evaluated closures on `Option` and `Result`.
1784 /// This lint suggests changing the following functions, when eager evaluation results in
1786 /// - `unwrap_or_else` to `unwrap_or`
1787 /// - `and_then` to `and`
1788 /// - `or_else` to `or`
1789 /// - `get_or_insert_with` to `get_or_insert`
1790 /// - `ok_or_else` to `ok_or`
1792 /// ### Why is this bad?
1793 /// Using eager evaluation is shorter and simpler in some cases.
1795 /// ### Known problems
1796 /// It is possible, but not recommended for `Deref` and `Index` to have
1797 /// side effects. Eagerly evaluating them can change the semantics of the program.
1801 /// // example code where clippy issues a warning
1802 /// let opt: Option<u32> = None;
1804 /// opt.unwrap_or_else(|| 42);
1808 /// let opt: Option<u32> = None;
1810 /// opt.unwrap_or(42);
1812 #[clippy::version = "1.48.0"]
1813 pub UNNECESSARY_LAZY_EVALUATIONS,
1815 "using unnecessary lazy evaluation, which can be replaced with simpler eager evaluation"
1818 declare_clippy_lint! {
1819 /// ### What it does
1820 /// Checks for usage of `_.map(_).collect::<Result<(), _>()`.
1822 /// ### Why is this bad?
1823 /// Using `try_for_each` instead is more readable and idiomatic.
1827 /// (0..3).map(|t| Err(t)).collect::<Result<(), _>>();
1831 /// (0..3).try_for_each(|t| Err(t));
1833 #[clippy::version = "1.49.0"]
1834 pub MAP_COLLECT_RESULT_UNIT,
1836 "using `.map(_).collect::<Result<(),_>()`, which can be replaced with `try_for_each`"
1839 declare_clippy_lint! {
1840 /// ### What it does
1841 /// Checks for `from_iter()` function calls on types that implement the `FromIterator`
1844 /// ### Why is this bad?
1845 /// It is recommended style to use collect. See
1846 /// [FromIterator documentation](https://doc.rust-lang.org/std/iter/trait.FromIterator.html)
1850 /// let five_fives = std::iter::repeat(5).take(5);
1852 /// let v = Vec::from_iter(five_fives);
1854 /// assert_eq!(v, vec![5, 5, 5, 5, 5]);
1858 /// let five_fives = std::iter::repeat(5).take(5);
1860 /// let v: Vec<i32> = five_fives.collect();
1862 /// assert_eq!(v, vec![5, 5, 5, 5, 5]);
1864 #[clippy::version = "1.49.0"]
1865 pub FROM_ITER_INSTEAD_OF_COLLECT,
1867 "use `.collect()` instead of `::from_iter()`"
1870 declare_clippy_lint! {
1871 /// ### What it does
1872 /// Checks for usage of `inspect().for_each()`.
1874 /// ### Why is this bad?
1875 /// It is the same as performing the computation
1876 /// inside `inspect` at the beginning of the closure in `for_each`.
1880 /// [1,2,3,4,5].iter()
1881 /// .inspect(|&x| println!("inspect the number: {}", x))
1882 /// .for_each(|&x| {
1883 /// assert!(x >= 0);
1886 /// Can be written as
1888 /// [1,2,3,4,5].iter()
1889 /// .for_each(|&x| {
1890 /// println!("inspect the number: {}", x);
1891 /// assert!(x >= 0);
1894 #[clippy::version = "1.51.0"]
1895 pub INSPECT_FOR_EACH,
1897 "using `.inspect().for_each()`, which can be replaced with `.for_each()`"
1900 declare_clippy_lint! {
1901 /// ### What it does
1902 /// Checks for usage of `filter_map(|x| x)`.
1904 /// ### Why is this bad?
1905 /// Readability, this can be written more concisely by using `flatten`.
1909 /// # let iter = vec![Some(1)].into_iter();
1910 /// iter.filter_map(|x| x);
1914 /// # let iter = vec![Some(1)].into_iter();
1917 #[clippy::version = "1.52.0"]
1918 pub FILTER_MAP_IDENTITY,
1920 "call to `filter_map` where `flatten` is sufficient"
1923 declare_clippy_lint! {
1924 /// ### What it does
1925 /// Checks for instances of `map(f)` where `f` is the identity function.
1927 /// ### Why is this bad?
1928 /// It can be written more concisely without the call to `map`.
1932 /// let x = [1, 2, 3];
1933 /// let y: Vec<_> = x.iter().map(|x| x).map(|x| 2*x).collect();
1937 /// let x = [1, 2, 3];
1938 /// let y: Vec<_> = x.iter().map(|x| 2*x).collect();
1940 #[clippy::version = "1.47.0"]
1943 "using iterator.map(|x| x)"
1946 declare_clippy_lint! {
1947 /// ### What it does
1948 /// Checks for the use of `.bytes().nth()`.
1950 /// ### Why is this bad?
1951 /// `.as_bytes().get()` is more efficient and more
1956 /// # #[allow(unused)]
1957 /// "Hello".bytes().nth(3);
1962 /// # #[allow(unused)]
1963 /// "Hello".as_bytes().get(3);
1965 #[clippy::version = "1.52.0"]
1968 "replace `.bytes().nth()` with `.as_bytes().get()`"
1971 declare_clippy_lint! {
1972 /// ### What it does
1973 /// Checks for the usage of `_.to_owned()`, `vec.to_vec()`, or similar when calling `_.clone()` would be clearer.
1975 /// ### Why is this bad?
1976 /// These methods do the same thing as `_.clone()` but may be confusing as
1977 /// to why we are calling `to_vec` on something that is already a `Vec` or calling `to_owned` on something that is already owned.
1981 /// let a = vec![1, 2, 3];
1982 /// let b = a.to_vec();
1983 /// let c = a.to_owned();
1987 /// let a = vec![1, 2, 3];
1988 /// let b = a.clone();
1989 /// let c = a.clone();
1991 #[clippy::version = "1.52.0"]
1994 "implicitly cloning a value by invoking a function on its dereferenced type"
1997 declare_clippy_lint! {
1998 /// ### What it does
1999 /// Checks for the use of `.iter().count()`.
2001 /// ### Why is this bad?
2002 /// `.len()` is more efficient and more
2007 /// # #![allow(unused)]
2008 /// let some_vec = vec![0, 1, 2, 3];
2010 /// some_vec.iter().count();
2011 /// &some_vec[..].iter().count();
2016 /// let some_vec = vec![0, 1, 2, 3];
2019 /// &some_vec[..].len();
2021 #[clippy::version = "1.52.0"]
2024 "replace `.iter().count()` with `.len()`"
2027 declare_clippy_lint! {
2028 /// ### What it does
2029 /// Checks for calls to [`splitn`]
2030 /// (https://doc.rust-lang.org/std/primitive.str.html#method.splitn) and
2031 /// related functions with either zero or one splits.
2033 /// ### Why is this bad?
2034 /// These calls don't actually split the value and are
2035 /// likely to be intended as a different number.
2040 /// for x in s.splitn(1, ":") {
2048 /// for x in s.splitn(2, ":") {
2052 #[clippy::version = "1.54.0"]
2053 pub SUSPICIOUS_SPLITN,
2055 "checks for `.splitn(0, ..)` and `.splitn(1, ..)`"
2058 declare_clippy_lint! {
2059 /// ### What it does
2060 /// Checks for manual implementations of `str::repeat`
2062 /// ### Why is this bad?
2063 /// These are both harder to read, as well as less performant.
2067 /// let x: String = std::iter::repeat('x').take(10).collect();
2072 /// let x: String = "x".repeat(10);
2074 #[clippy::version = "1.54.0"]
2075 pub MANUAL_STR_REPEAT,
2077 "manual implementation of `str::repeat`"
2080 declare_clippy_lint! {
2081 /// ### What it does
2082 /// Checks for usages of `str::splitn(2, _)`
2084 /// ### Why is this bad?
2085 /// `split_once` is both clearer in intent and slightly more efficient.
2089 /// let s = "key=value=add";
2090 /// let (key, value) = s.splitn(2, '=').next_tuple()?;
2091 /// let value = s.splitn(2, '=').nth(1)?;
2093 /// let mut parts = s.splitn(2, '=');
2094 /// let key = parts.next()?;
2095 /// let value = parts.next()?;
2100 /// let s = "key=value=add";
2101 /// let (key, value) = s.split_once('=')?;
2102 /// let value = s.split_once('=')?.1;
2104 /// let (key, value) = s.split_once('=')?;
2108 /// The multiple statement variant currently only detects `iter.next()?`/`iter.next().unwrap()`
2109 /// in two separate `let` statements that immediately follow the `splitn()`
2110 #[clippy::version = "1.57.0"]
2111 pub MANUAL_SPLIT_ONCE,
2113 "replace `.splitn(2, pat)` with `.split_once(pat)`"
2116 declare_clippy_lint! {
2117 /// ### What it does
2118 /// Checks for usages of `str::splitn` (or `str::rsplitn`) where using `str::split` would be the same.
2119 /// ### Why is this bad?
2120 /// The function `split` is simpler and there is no performance difference in these cases, considering
2121 /// that both functions return a lazy iterator.
2124 /// let str = "key=value=add";
2125 /// let _ = str.splitn(3, '=').next().unwrap();
2130 /// let str = "key=value=add";
2131 /// let _ = str.split('=').next().unwrap();
2133 #[clippy::version = "1.59.0"]
2134 pub NEEDLESS_SPLITN,
2136 "usages of `str::splitn` that can be replaced with `str::split`"
2139 declare_clippy_lint! {
2140 /// ### What it does
2141 /// Checks for unnecessary calls to [`ToOwned::to_owned`](https://doc.rust-lang.org/std/borrow/trait.ToOwned.html#tymethod.to_owned)
2142 /// and other `to_owned`-like functions.
2144 /// ### Why is this bad?
2145 /// The unnecessary calls result in useless allocations.
2147 /// ### Known problems
2148 /// `unnecessary_to_owned` can falsely trigger if `IntoIterator::into_iter` is applied to an
2149 /// owned copy of a resource and the resource is later used mutably. See
2150 /// [#8148](https://github.com/rust-lang/rust-clippy/issues/8148).
2154 /// let path = std::path::Path::new("x");
2155 /// foo(&path.to_string_lossy().to_string());
2156 /// fn foo(s: &str) {}
2160 /// let path = std::path::Path::new("x");
2161 /// foo(&path.to_string_lossy());
2162 /// fn foo(s: &str) {}
2164 #[clippy::version = "1.59.0"]
2165 pub UNNECESSARY_TO_OWNED,
2167 "unnecessary calls to `to_owned`-like functions"
2170 declare_clippy_lint! {
2171 /// ### What it does
2172 /// Checks for use of `.collect::<Vec<String>>().join("")` on iterators.
2174 /// ### Why is this bad?
2175 /// `.collect::<String>()` is more concise and might be more performant
2179 /// let vector = vec!["hello", "world"];
2180 /// let output = vector.iter().map(|item| item.to_uppercase()).collect::<Vec<String>>().join("");
2181 /// println!("{}", output);
2183 /// The correct use would be:
2185 /// let vector = vec!["hello", "world"];
2186 /// let output = vector.iter().map(|item| item.to_uppercase()).collect::<String>();
2187 /// println!("{}", output);
2189 /// ### Known problems
2190 /// While `.collect::<String>()` is sometimes more performant, there are cases where
2191 /// using `.collect::<String>()` over `.collect::<Vec<String>>().join("")`
2192 /// will prevent loop unrolling and will result in a negative performance impact.
2194 /// Additionally, differences have been observed between aarch64 and x86_64 assembly output,
2195 /// with aarch64 tending to producing faster assembly in more cases when using `.collect::<String>()`
2196 #[clippy::version = "1.61.0"]
2197 pub UNNECESSARY_JOIN,
2199 "using `.collect::<Vec<String>>().join(\"\")` on an iterator"
2202 declare_clippy_lint! {
2203 /// ### What it does
2204 /// Checks for no-op uses of `Option::{as_deref, as_deref_mut}`,
2205 /// for example, `Option<&T>::as_deref()` returns the same type.
2207 /// ### Why is this bad?
2208 /// Redundant code and improving readability.
2212 /// let a = Some(&1);
2213 /// let b = a.as_deref(); // goes from Option<&i32> to Option<&i32>
2218 /// let a = Some(&1);
2221 #[clippy::version = "1.57.0"]
2222 pub NEEDLESS_OPTION_AS_DEREF,
2224 "no-op use of `deref` or `deref_mut` method to `Option`."
2227 declare_clippy_lint! {
2228 /// ### What it does
2229 /// Finds usages of [`char::is_digit`](https://doc.rust-lang.org/stable/std/primitive.char.html#method.is_digit) that
2230 /// can be replaced with [`is_ascii_digit`](https://doc.rust-lang.org/stable/std/primitive.char.html#method.is_ascii_digit) or
2231 /// [`is_ascii_hexdigit`](https://doc.rust-lang.org/stable/std/primitive.char.html#method.is_ascii_hexdigit).
2233 /// ### Why is this bad?
2234 /// `is_digit(..)` is slower and requires specifying the radix.
2238 /// let c: char = '6';
2244 /// let c: char = '6';
2245 /// c.is_ascii_digit();
2246 /// c.is_ascii_hexdigit();
2248 #[clippy::version = "1.62.0"]
2249 pub IS_DIGIT_ASCII_RADIX,
2251 "use of `char::is_digit(..)` with literal radix of 10 or 16"
2254 declare_clippy_lint! {
2255 /// ### What it does
2256 /// Checks for calling `take` function after `as_ref`.
2258 /// ### Why is this bad?
2259 /// Redundant code. `take` writes `None` to its argument.
2260 /// In this case the modification is useless as it's a temporary that cannot be read from afterwards.
2264 /// let x = Some(3);
2265 /// x.as_ref().take();
2269 /// let x = Some(3);
2272 #[clippy::version = "1.62.0"]
2273 pub NEEDLESS_OPTION_TAKE,
2275 "using `.as_ref().take()` on a temporary value"
2278 declare_clippy_lint! {
2279 /// ### What it does
2280 /// Checks for `replace` statements which have no effect.
2282 /// ### Why is this bad?
2283 /// It's either a mistake or confusing.
2287 /// "1234".replace("12", "12");
2288 /// "1234".replacen("12", "12", 1);
2290 #[clippy::version = "1.63.0"]
2291 pub NO_EFFECT_REPLACE,
2293 "replace with no effect"
2296 declare_clippy_lint! {
2297 /// ### What it does
2298 /// Checks for usages of `.then_some(..).unwrap_or(..)`
2300 /// ### Why is this bad?
2301 /// This can be written more clearly with `if .. else ..`
2304 /// This lint currently only looks for usages of
2305 /// `.then_some(..).unwrap_or(..)`, but will be expanded
2306 /// to account for similar patterns.
2311 /// x.then_some("a").unwrap_or("b");
2316 /// if x { "a" } else { "b" };
2318 #[clippy::version = "1.64.0"]
2319 pub OBFUSCATED_IF_ELSE,
2321 "use of `.then_some(..).unwrap_or(..)` can be written \
2322 more clearly with `if .. else ..`"
2325 declare_clippy_lint! {
2326 /// ### What it does
2328 /// Checks for calls to `iter`, `iter_mut` or `into_iter` on collections containing a single item
2330 /// ### Why is this bad?
2332 /// It is simpler to use the once function from the standard library:
2337 /// let a = [123].iter();
2338 /// let b = Some(123).into_iter();
2343 /// let a = iter::once(&123);
2344 /// let b = iter::once(123);
2347 /// ### Known problems
2349 /// The type of the resulting iterator might become incompatible with its usage
2350 #[clippy::version = "1.64.0"]
2351 pub ITER_ON_SINGLE_ITEMS,
2353 "Iterator for array of length 1"
2356 declare_clippy_lint! {
2357 /// ### What it does
2359 /// Checks for calls to `iter`, `iter_mut` or `into_iter` on empty collections
2361 /// ### Why is this bad?
2363 /// It is simpler to use the empty function from the standard library:
2368 /// use std::{slice, option};
2369 /// let a: slice::Iter<i32> = [].iter();
2370 /// let f: option::IntoIter<i32> = None.into_iter();
2375 /// let a: iter::Empty<i32> = iter::empty();
2376 /// let b: iter::Empty<i32> = iter::empty();
2379 /// ### Known problems
2381 /// The type of the resulting iterator might become incompatible with its usage
2382 #[clippy::version = "1.64.0"]
2383 pub ITER_ON_EMPTY_COLLECTIONS,
2385 "Iterator for empty array"
2388 declare_clippy_lint! {
2389 /// ### What it does
2390 /// Checks for naive byte counts
2392 /// ### Why is this bad?
2393 /// The [`bytecount`](https://crates.io/crates/bytecount)
2394 /// crate has methods to count your bytes faster, especially for large slices.
2396 /// ### Known problems
2397 /// If you have predominantly small slices, the
2398 /// `bytecount::count(..)` method may actually be slower. However, if you can
2399 /// ensure that less than 2³²-1 matches arise, the `naive_count_32(..)` can be
2400 /// faster in those cases.
2404 /// # let vec = vec![1_u8];
2405 /// let count = vec.iter().filter(|x| **x == 0u8).count();
2410 /// # let vec = vec![1_u8];
2411 /// let count = bytecount::count(&vec, 0u8);
2413 #[clippy::version = "pre 1.29.0"]
2414 pub NAIVE_BYTECOUNT,
2416 "use of naive `<slice>.filter(|&x| x == y).count()` to count byte values"
2419 declare_clippy_lint! {
2420 /// ### What it does
2421 /// It checks for `str::bytes().count()` and suggests replacing it with
2424 /// ### Why is this bad?
2425 /// `str::bytes().count()` is longer and may not be as performant as using
2430 /// "hello".bytes().count();
2431 /// String::from("hello").bytes().count();
2436 /// String::from("hello").len();
2438 #[clippy::version = "1.62.0"]
2439 pub BYTES_COUNT_TO_LEN,
2441 "Using `bytes().count()` when `len()` performs the same functionality"
2444 declare_clippy_lint! {
2445 /// ### What it does
2446 /// Checks for calls to `ends_with` with possible file extensions
2447 /// and suggests to use a case-insensitive approach instead.
2449 /// ### Why is this bad?
2450 /// `ends_with` is case-sensitive and may not detect files with a valid extension.
2454 /// fn is_rust_file(filename: &str) -> bool {
2455 /// filename.ends_with(".rs")
2460 /// fn is_rust_file(filename: &str) -> bool {
2461 /// let filename = std::path::Path::new(filename);
2462 /// filename.extension()
2463 /// .map_or(false, |ext| ext.eq_ignore_ascii_case("rs"))
2466 #[clippy::version = "1.51.0"]
2467 pub CASE_SENSITIVE_FILE_EXTENSION_COMPARISONS,
2469 "Checks for calls to ends_with with case-sensitive file extensions"
2472 declare_clippy_lint! {
2473 /// ### What it does
2474 /// Checks for using `x.get(0)` instead of
2477 /// ### Why is this bad?
2478 /// Using `x.first()` is easier to read and has the same
2483 /// let x = vec![2, 3, 5];
2484 /// let first_element = x.get(0);
2489 /// let x = vec![2, 3, 5];
2490 /// let first_element = x.first();
2492 #[clippy::version = "1.63.0"]
2495 "Using `x.get(0)` when `x.first()` is simpler"
2498 declare_clippy_lint! {
2499 /// ### What it does
2501 /// Finds patterns that reimplement `Option::ok_or`.
2503 /// ### Why is this bad?
2505 /// Concise code helps focusing on behavior instead of boilerplate.
2509 /// let foo: Option<i32> = None;
2510 /// foo.map_or(Err("error"), |v| Ok(v));
2515 /// let foo: Option<i32> = None;
2516 /// foo.ok_or("error");
2518 #[clippy::version = "1.49.0"]
2521 "finds patterns that can be encoded more concisely with `Option::ok_or`"
2524 declare_clippy_lint! {
2525 /// ### What it does
2526 /// Checks for usage of `map(|x| x.clone())` or
2527 /// dereferencing closures for `Copy` types, on `Iterator` or `Option`,
2528 /// and suggests `cloned()` or `copied()` instead
2530 /// ### Why is this bad?
2531 /// Readability, this can be written more concisely
2535 /// let x = vec![42, 43];
2536 /// let y = x.iter();
2537 /// let z = y.map(|i| *i);
2540 /// The correct use would be:
2543 /// let x = vec![42, 43];
2544 /// let y = x.iter();
2545 /// let z = y.cloned();
2547 #[clippy::version = "pre 1.29.0"]
2550 "using `iterator.map(|x| x.clone())`, or dereferencing closures for `Copy` types"
2553 declare_clippy_lint! {
2554 /// ### What it does
2555 /// Checks for instances of `map_err(|_| Some::Enum)`
2557 /// ### Why is this bad?
2558 /// This `map_err` throws away the original error rather than allowing the enum to contain and report the cause of the error
2565 /// #[derive(Debug)]
2571 /// impl fmt::Display for Error {
2572 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2574 /// Error::Indivisible => write!(f, "could not divide input by three"),
2575 /// Error::Remainder(remainder) => write!(
2577 /// "input is not divisible by three, remainder = {}",
2584 /// impl std::error::Error for Error {}
2586 /// fn divisible_by_3(input: &str) -> Result<(), Error> {
2589 /// .map_err(|_| Error::Indivisible)
2591 /// .and_then(|remainder| {
2592 /// if remainder == 0 {
2595 /// Err(Error::Remainder(remainder as u8))
2603 /// use std::{fmt, num::ParseIntError};
2605 /// #[derive(Debug)]
2607 /// Indivisible(ParseIntError),
2611 /// impl fmt::Display for Error {
2612 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2614 /// Error::Indivisible(_) => write!(f, "could not divide input by three"),
2615 /// Error::Remainder(remainder) => write!(
2617 /// "input is not divisible by three, remainder = {}",
2624 /// impl std::error::Error for Error {
2625 /// fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
2627 /// Error::Indivisible(source) => Some(source),
2633 /// fn divisible_by_3(input: &str) -> Result<(), Error> {
2636 /// .map_err(Error::Indivisible)
2638 /// .and_then(|remainder| {
2639 /// if remainder == 0 {
2642 /// Err(Error::Remainder(remainder as u8))
2647 #[clippy::version = "1.48.0"]
2650 "`map_err` should not ignore the original error"
2653 declare_clippy_lint! {
2654 /// ### What it does
2655 /// Checks for `&mut Mutex::lock` calls
2657 /// ### Why is this bad?
2658 /// `Mutex::lock` is less efficient than
2659 /// calling `Mutex::get_mut`. In addition you also have a statically
2660 /// guarantee that the mutex isn't locked, instead of just a runtime
2665 /// use std::sync::{Arc, Mutex};
2667 /// let mut value_rc = Arc::new(Mutex::new(42_u8));
2668 /// let value_mutex = Arc::get_mut(&mut value_rc).unwrap();
2670 /// let mut value = value_mutex.lock().unwrap();
2675 /// use std::sync::{Arc, Mutex};
2677 /// let mut value_rc = Arc::new(Mutex::new(42_u8));
2678 /// let value_mutex = Arc::get_mut(&mut value_rc).unwrap();
2680 /// let value = value_mutex.get_mut().unwrap();
2683 #[clippy::version = "1.49.0"]
2686 "`&mut Mutex::lock` does unnecessary locking"
2689 declare_clippy_lint! {
2690 /// ### What it does
2691 /// Checks for duplicate open options as well as combinations
2692 /// that make no sense.
2694 /// ### Why is this bad?
2695 /// In the best case, the code will be harder to read than
2696 /// necessary. I don't know the worst case.
2700 /// use std::fs::OpenOptions;
2702 /// OpenOptions::new().read(true).truncate(true);
2704 #[clippy::version = "pre 1.29.0"]
2705 pub NONSENSICAL_OPEN_OPTIONS,
2707 "nonsensical combination of options for opening a file"
2710 declare_clippy_lint! {
2711 /// ### What it does
2712 ///* Checks for [push](https://doc.rust-lang.org/std/path/struct.PathBuf.html#method.push)
2713 /// calls on `PathBuf` that can cause overwrites.
2715 /// ### Why is this bad?
2716 /// Calling `push` with a root path at the start can overwrite the
2717 /// previous defined path.
2721 /// use std::path::PathBuf;
2723 /// let mut x = PathBuf::from("/foo");
2725 /// assert_eq!(x, PathBuf::from("/bar"));
2727 /// Could be written:
2730 /// use std::path::PathBuf;
2732 /// let mut x = PathBuf::from("/foo");
2734 /// assert_eq!(x, PathBuf::from("/foo/bar"));
2736 #[clippy::version = "1.36.0"]
2737 pub PATH_BUF_PUSH_OVERWRITE,
2739 "calling `push` with file system root on `PathBuf` can overwrite it"
2742 declare_clippy_lint! {
2743 /// ### What it does
2744 /// Checks for zipping a collection with the range of
2747 /// ### Why is this bad?
2748 /// The code is better expressed with `.enumerate()`.
2752 /// # let x = vec![1];
2753 /// let _ = x.iter().zip(0..x.len());
2758 /// # let x = vec![1];
2759 /// let _ = x.iter().enumerate();
2761 #[clippy::version = "pre 1.29.0"]
2762 pub RANGE_ZIP_WITH_LEN,
2764 "zipping iterator with a range when `enumerate()` would do"
2767 declare_clippy_lint! {
2768 /// ### What it does
2769 /// Checks for usage of `.repeat(1)` and suggest the following method for each types.
2770 /// - `.to_string()` for `str`
2771 /// - `.clone()` for `String`
2772 /// - `.to_vec()` for `slice`
2774 /// The lint will evaluate constant expressions and values as arguments of `.repeat(..)` and emit a message if
2775 /// they are equivalent to `1`. (Related discussion in [rust-clippy#7306](https://github.com/rust-lang/rust-clippy/issues/7306))
2777 /// ### Why is this bad?
2778 /// For example, `String.repeat(1)` is equivalent to `.clone()`. If cloning
2779 /// the string is the intention behind this, `clone()` should be used.
2784 /// let x = String::from("hello world").repeat(1);
2790 /// let x = String::from("hello world").clone();
2793 #[clippy::version = "1.47.0"]
2796 "using `.repeat(1)` instead of `String.clone()`, `str.to_string()` or `slice.to_vec()` "
2799 declare_clippy_lint! {
2800 /// ### What it does
2801 /// When sorting primitive values (integers, bools, chars, as well
2802 /// as arrays, slices, and tuples of such items), it is typically better to
2803 /// use an unstable sort than a stable sort.
2805 /// ### Why is this bad?
2806 /// Typically, using a stable sort consumes more memory and cpu cycles.
2807 /// Because values which compare equal are identical, preserving their
2808 /// relative order (the guarantee that a stable sort provides) means
2809 /// nothing, while the extra costs still apply.
2811 /// ### Known problems
2813 /// As pointed out in
2814 /// [issue #8241](https://github.com/rust-lang/rust-clippy/issues/8241),
2815 /// a stable sort can instead be significantly faster for certain scenarios
2816 /// (eg. when a sorted vector is extended with new data and resorted).
2818 /// For more information and benchmarking results, please refer to the
2819 /// issue linked above.
2823 /// let mut vec = vec![2, 1, 3];
2828 /// let mut vec = vec![2, 1, 3];
2829 /// vec.sort_unstable();
2831 #[clippy::version = "1.47.0"]
2832 pub STABLE_SORT_PRIMITIVE,
2834 "use of sort() when sort_unstable() is equivalent"
2837 declare_clippy_lint! {
2838 /// ### What it does
2839 /// Detects `().hash(_)`.
2841 /// ### Why is this bad?
2842 /// Hashing a unit value doesn't do anything as the implementation of `Hash` for `()` is a no-op.
2846 /// # use std::hash::Hash;
2847 /// # use std::collections::hash_map::DefaultHasher;
2848 /// # enum Foo { Empty, WithValue(u8) }
2850 /// # let mut state = DefaultHasher::new();
2851 /// # let my_enum = Foo::Empty;
2853 /// Empty => ().hash(&mut state),
2854 /// WithValue(x) => x.hash(&mut state),
2859 /// # use std::hash::Hash;
2860 /// # use std::collections::hash_map::DefaultHasher;
2861 /// # enum Foo { Empty, WithValue(u8) }
2863 /// # let mut state = DefaultHasher::new();
2864 /// # let my_enum = Foo::Empty;
2866 /// Empty => 0_u8.hash(&mut state),
2867 /// WithValue(x) => x.hash(&mut state),
2870 #[clippy::version = "1.58.0"]
2873 "hashing a unit value, which does nothing"
2876 declare_clippy_lint! {
2877 /// ### What it does
2878 /// Detects uses of `Vec::sort_by` passing in a closure
2879 /// which compares the two arguments, either directly or indirectly.
2881 /// ### Why is this bad?
2882 /// It is more clear to use `Vec::sort_by_key` (or `Vec::sort` if
2883 /// possible) than to use `Vec::sort_by` and a more complicated
2886 /// ### Known problems
2887 /// If the suggested `Vec::sort_by_key` uses Reverse and it isn't already
2888 /// imported by a use statement, then it will need to be added manually.
2893 /// # impl A { fn foo(&self) {} }
2894 /// # let mut vec: Vec<A> = Vec::new();
2895 /// vec.sort_by(|a, b| a.foo().cmp(&b.foo()));
2900 /// # impl A { fn foo(&self) {} }
2901 /// # let mut vec: Vec<A> = Vec::new();
2902 /// vec.sort_by_key(|a| a.foo());
2904 #[clippy::version = "1.46.0"]
2905 pub UNNECESSARY_SORT_BY,
2907 "Use of `Vec::sort_by` when `Vec::sort_by_key` or `Vec::sort` would be clearer"
2910 pub struct Methods {
2911 avoid_breaking_exported_api: bool,
2912 msrv: Option<RustcVersion>,
2913 allow_expect_in_tests: bool,
2914 allow_unwrap_in_tests: bool,
2920 avoid_breaking_exported_api: bool,
2921 msrv: Option<RustcVersion>,
2922 allow_expect_in_tests: bool,
2923 allow_unwrap_in_tests: bool,
2926 avoid_breaking_exported_api,
2928 allow_expect_in_tests,
2929 allow_unwrap_in_tests,
2934 impl_lint_pass!(Methods => [
2937 SHOULD_IMPLEMENT_TRAIT,
2938 WRONG_SELF_CONVENTION,
2940 UNWRAP_OR_ELSE_DEFAULT,
2942 RESULT_MAP_OR_INTO_OPTION,
2944 BIND_INSTEAD_OF_MAP,
2953 ITER_OVEREAGER_CLONED,
2954 CLONED_INSTEAD_OF_COPIED,
2956 INEFFICIENT_TO_STRING,
2958 SINGLE_CHAR_PATTERN,
2959 SINGLE_CHAR_ADD_STR,
2963 FILTER_MAP_IDENTITY,
2971 ITERATOR_STEP_BY_ZERO,
2980 STRING_EXTEND_CHARS,
2981 ITER_CLONED_COLLECT,
2985 UNNECESSARY_FILTER_MAP,
2986 UNNECESSARY_FIND_MAP,
2989 UNINIT_ASSUMED_INIT,
2990 MANUAL_SATURATING_ARITHMETIC,
2993 OPTION_AS_REF_DEREF,
2994 UNNECESSARY_LAZY_EVALUATIONS,
2995 MAP_COLLECT_RESULT_UNIT,
2996 FROM_ITER_INSTEAD_OF_COLLECT,
3004 UNNECESSARY_TO_OWNED,
3007 NEEDLESS_OPTION_AS_DEREF,
3008 IS_DIGIT_ASCII_RADIX,
3009 NEEDLESS_OPTION_TAKE,
3012 ITER_ON_SINGLE_ITEMS,
3013 ITER_ON_EMPTY_COLLECTIONS,
3016 CASE_SENSITIVE_FILE_EXTENSION_COMPARISONS,
3022 NONSENSICAL_OPEN_OPTIONS,
3023 PATH_BUF_PUSH_OVERWRITE,
3026 STABLE_SORT_PRIMITIVE,
3028 UNNECESSARY_SORT_BY,
3031 /// Extracts a method call name, args, and `Span` of the method name.
3032 fn method_call<'tcx>(recv: &'tcx hir::Expr<'tcx>) -> Option<(&'tcx str, &'tcx [hir::Expr<'tcx>], Span)> {
3033 if let ExprKind::MethodCall(path, args, _) = recv.kind {
3034 if !args.iter().any(|e| e.span.from_expansion()) {
3035 let name = path.ident.name.as_str();
3036 return Some((name, args, path.ident.span));
3042 impl<'tcx> LateLintPass<'tcx> for Methods {
3043 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) {
3044 if expr.span.from_expansion() {
3048 self.check_methods(cx, expr);
3051 hir::ExprKind::Call(func, args) => {
3052 from_iter_instead_of_collect::check(cx, expr, args, func);
3054 hir::ExprKind::MethodCall(method_call, args, _) => {
3055 let method_span = method_call.ident.span;
3056 or_fun_call::check(cx, expr, method_span, method_call.ident.as_str(), args);
3057 expect_fun_call::check(cx, expr, method_span, method_call.ident.as_str(), args);
3058 clone_on_copy::check(cx, expr, method_call.ident.name, args);
3059 clone_on_ref_ptr::check(cx, expr, method_call.ident.name, args);
3060 inefficient_to_string::check(cx, expr, method_call.ident.name, args);
3061 single_char_add_str::check(cx, expr, args);
3062 into_iter_on_ref::check(cx, expr, method_span, method_call.ident.name, args);
3063 single_char_pattern::check(cx, expr, method_call.ident.name, args);
3064 unnecessary_to_owned::check(cx, expr, method_call.ident.name, args, self.msrv);
3066 hir::ExprKind::Binary(op, lhs, rhs) if op.node == hir::BinOpKind::Eq || op.node == hir::BinOpKind::Ne => {
3067 let mut info = BinaryExprInfo {
3071 eq: op.node == hir::BinOpKind::Eq,
3073 lint_binary_expr_with_method_call(cx, &mut info);
3079 #[allow(clippy::too_many_lines)]
3080 fn check_impl_item(&mut self, cx: &LateContext<'tcx>, impl_item: &'tcx hir::ImplItem<'_>) {
3081 if in_external_macro(cx.sess(), impl_item.span) {
3084 let name = impl_item.ident.name.as_str();
3085 let parent = cx.tcx.hir().get_parent_item(impl_item.hir_id());
3086 let item = cx.tcx.hir().expect_item(parent);
3087 let self_ty = cx.tcx.type_of(item.def_id);
3089 let implements_trait = matches!(item.kind, hir::ItemKind::Impl(hir::Impl { of_trait: Some(_), .. }));
3091 if let hir::ImplItemKind::Fn(ref sig, id) = impl_item.kind;
3092 if let Some(first_arg) = iter_input_pats(sig.decl, cx.tcx.hir().body(id)).next();
3094 let method_sig = cx.tcx.fn_sig(impl_item.def_id);
3095 let method_sig = cx.tcx.erase_late_bound_regions(method_sig);
3097 let first_arg_ty = method_sig.inputs().iter().next();
3099 // check conventions w.r.t. conversion method names and predicates
3100 if let Some(first_arg_ty) = first_arg_ty;
3103 // if this impl block implements a trait, lint in trait definition instead
3104 if !implements_trait && cx.access_levels.is_exported(impl_item.def_id) {
3105 // check missing trait implementations
3106 for method_config in &TRAIT_METHODS {
3107 if name == method_config.method_name &&
3108 sig.decl.inputs.len() == method_config.param_count &&
3109 method_config.output_type.matches(&sig.decl.output) &&
3110 method_config.self_kind.matches(cx, self_ty, *first_arg_ty) &&
3111 fn_header_equals(method_config.fn_header, sig.header) &&
3112 method_config.lifetime_param_cond(impl_item)
3116 SHOULD_IMPLEMENT_TRAIT,
3119 "method `{}` can be confused for the standard trait method `{}::{}`",
3120 method_config.method_name,
3121 method_config.trait_name,
3122 method_config.method_name
3126 "consider implementing the trait `{}` or choosing a less ambiguous method name",
3127 method_config.trait_name
3134 if sig.decl.implicit_self.has_implicit_self()
3135 && !(self.avoid_breaking_exported_api
3136 && cx.access_levels.is_exported(impl_item.def_id))
3138 wrong_self_convention::check(
3151 // if this impl block implements a trait, lint in trait definition instead
3152 if implements_trait {
3156 if let hir::ImplItemKind::Fn(_, _) = impl_item.kind {
3157 let ret_ty = return_ty(cx, impl_item.hir_id());
3159 // walk the return type and check for Self (this does not check associated types)
3160 if let Some(self_adt) = self_ty.ty_adt_def() {
3161 if contains_adt_constructor(ret_ty, self_adt) {
3164 } else if contains_ty(ret_ty, self_ty) {
3168 // if return type is impl trait, check the associated types
3169 if let ty::Opaque(def_id, _) = *ret_ty.kind() {
3170 // one of the associated types must be Self
3171 for &(predicate, _span) in cx.tcx.explicit_item_bounds(def_id) {
3172 if let ty::PredicateKind::Projection(projection_predicate) = predicate.kind().skip_binder() {
3173 let assoc_ty = match projection_predicate.term {
3174 ty::Term::Ty(ty) => ty,
3175 ty::Term::Const(_c) => continue,
3177 // walk the associated type and check for Self
3178 if let Some(self_adt) = self_ty.ty_adt_def() {
3179 if contains_adt_constructor(assoc_ty, self_adt) {
3182 } else if contains_ty(assoc_ty, self_ty) {
3189 if name == "new" && ret_ty != self_ty {
3194 "methods called `new` usually return `Self`",
3200 fn check_trait_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx TraitItem<'_>) {
3201 if in_external_macro(cx.tcx.sess, item.span) {
3206 if let TraitItemKind::Fn(ref sig, _) = item.kind;
3207 if sig.decl.implicit_self.has_implicit_self();
3208 if let Some(first_arg_ty) = sig.decl.inputs.iter().next();
3211 let first_arg_span = first_arg_ty.span;
3212 let first_arg_ty = hir_ty_to_ty(cx.tcx, first_arg_ty);
3213 let self_ty = TraitRef::identity(cx.tcx, item.def_id.to_def_id()).self_ty().skip_binder();
3214 wrong_self_convention::check(
3216 item.ident.name.as_str(),
3227 if item.ident.name == sym::new;
3228 if let TraitItemKind::Fn(_, _) = item.kind;
3229 let ret_ty = return_ty(cx, item.hir_id());
3230 let self_ty = TraitRef::identity(cx.tcx, item.def_id.to_def_id()).self_ty().skip_binder();
3231 if !contains_ty(ret_ty, self_ty);
3238 "methods called `new` usually return `Self`",
3244 extract_msrv_attr!(LateContext);
3248 #[allow(clippy::too_many_lines)]
3249 fn check_methods<'tcx>(&self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
3250 if let Some((name, [recv, args @ ..], span)) = method_call(expr) {
3251 match (name, args) {
3252 ("add" | "offset" | "sub" | "wrapping_offset" | "wrapping_add" | "wrapping_sub", [_arg]) => {
3253 zst_offset::check(cx, expr, recv);
3255 ("and_then", [arg]) => {
3256 let biom_option_linted = bind_instead_of_map::OptionAndThenSome::check(cx, expr, recv, arg);
3257 let biom_result_linted = bind_instead_of_map::ResultAndThenOk::check(cx, expr, recv, arg);
3258 if !biom_option_linted && !biom_result_linted {
3259 unnecessary_lazy_eval::check(cx, expr, recv, arg, "and");
3262 ("as_deref" | "as_deref_mut", []) => {
3263 needless_option_as_deref::check(cx, expr, recv, name);
3265 ("as_mut", []) => useless_asref::check(cx, expr, "as_mut", recv),
3266 ("as_ref", []) => useless_asref::check(cx, expr, "as_ref", recv),
3267 ("assume_init", []) => uninit_assumed_init::check(cx, expr, recv),
3268 ("cloned", []) => cloned_instead_of_copied::check(cx, expr, recv, span, self.msrv),
3269 ("collect", []) => match method_call(recv) {
3270 Some((name @ ("cloned" | "copied"), [recv2], _)) => {
3271 iter_cloned_collect::check(cx, name, expr, recv2);
3273 Some(("map", [m_recv, m_arg], _)) => {
3274 map_collect_result_unit::check(cx, expr, m_recv, m_arg, recv);
3276 Some(("take", [take_self_arg, take_arg], _)) => {
3277 if meets_msrv(self.msrv, msrvs::STR_REPEAT) {
3278 manual_str_repeat::check(cx, expr, recv, take_self_arg, take_arg);
3283 ("count", []) if is_trait_method(cx, expr, sym::Iterator) => match method_call(recv) {
3284 Some(("cloned", [recv2], _)) => iter_overeager_cloned::check(cx, expr, recv, recv2, true, false),
3285 Some((name2 @ ("into_iter" | "iter" | "iter_mut"), [recv2], _)) => {
3286 iter_count::check(cx, expr, recv2, name2);
3288 Some(("map", [_, arg], _)) => suspicious_map::check(cx, expr, recv, arg),
3289 Some(("filter", [recv2, arg], _)) => bytecount::check(cx, expr, recv2, arg),
3290 Some(("bytes", [recv2], _)) => bytes_count_to_len::check(cx, expr, recv, recv2),
3293 ("drain", [arg]) => {
3294 iter_with_drain::check(cx, expr, recv, span, arg);
3296 ("ends_with", [arg]) => {
3297 if let ExprKind::MethodCall(_, _, span) = expr.kind {
3298 case_sensitive_file_extension_comparisons::check(cx, expr, span, recv, arg);
3301 ("expect", [_]) => match method_call(recv) {
3302 Some(("ok", [recv], _)) => ok_expect::check(cx, expr, recv),
3303 Some(("err", [recv], err_span)) => err_expect::check(cx, expr, recv, self.msrv, span, err_span),
3304 _ => expect_used::check(cx, expr, recv, false, self.allow_expect_in_tests),
3306 ("expect_err", [_]) => expect_used::check(cx, expr, recv, true, self.allow_expect_in_tests),
3307 ("extend", [arg]) => {
3308 string_extend_chars::check(cx, expr, recv, arg);
3309 extend_with_drain::check(cx, expr, recv, arg);
3311 ("filter_map", [arg]) => {
3312 unnecessary_filter_map::check(cx, expr, arg, name);
3313 filter_map_identity::check(cx, expr, arg, span);
3315 ("find_map", [arg]) => {
3316 unnecessary_filter_map::check(cx, expr, arg, name);
3318 ("flat_map", [arg]) => {
3319 flat_map_identity::check(cx, expr, arg, span);
3320 flat_map_option::check(cx, expr, arg, span);
3322 ("flatten", []) => match method_call(recv) {
3323 Some(("map", [recv, map_arg], map_span)) => map_flatten::check(cx, expr, recv, map_arg, map_span),
3324 Some(("cloned", [recv2], _)) => iter_overeager_cloned::check(cx, expr, recv, recv2, false, true),
3327 ("fold", [init, acc]) => unnecessary_fold::check(cx, expr, init, acc, span),
3328 ("for_each", [_]) => {
3329 if let Some(("inspect", [_, _], span2)) = method_call(recv) {
3330 inspect_for_each::check(cx, expr, span2);
3334 get_first::check(cx, expr, recv, arg);
3335 get_last_with_len::check(cx, expr, recv, arg);
3337 ("get_or_insert_with", [arg]) => unnecessary_lazy_eval::check(cx, expr, recv, arg, "get_or_insert"),
3338 ("hash", [arg]) => {
3339 unit_hash::check(cx, expr, recv, arg);
3341 ("is_file", []) => filetype_is_file::check(cx, expr, recv),
3342 ("is_digit", [radix]) => is_digit_ascii_radix::check(cx, expr, recv, radix, self.msrv),
3343 ("is_none", []) => check_is_some_is_none(cx, expr, recv, false),
3344 ("is_some", []) => check_is_some_is_none(cx, expr, recv, true),
3345 ("iter" | "iter_mut" | "into_iter", []) => {
3346 iter_on_single_or_empty_collections::check(cx, expr, name, recv);
3348 ("join", [join_arg]) => {
3349 if let Some(("collect", _, span)) = method_call(recv) {
3350 unnecessary_join::check(cx, expr, recv, join_arg, span);
3353 ("last", []) | ("skip", [_]) => {
3354 if let Some((name2, [recv2, args2 @ ..], _span2)) = method_call(recv) {
3355 if let ("cloned", []) = (name2, args2) {
3356 iter_overeager_cloned::check(cx, expr, recv, recv2, false, false);
3361 mut_mutex_lock::check(cx, expr, recv, span);
3363 (name @ ("map" | "map_err"), [m_arg]) => {
3365 map_clone::check(cx, expr, recv, m_arg, self.msrv);
3367 map_err_ignore::check(cx, expr, m_arg);
3369 if let Some((name, [recv2, args @ ..], span2)) = method_call(recv) {
3370 match (name, args) {
3371 ("as_mut", []) => option_as_ref_deref::check(cx, expr, recv2, m_arg, true, self.msrv),
3372 ("as_ref", []) => option_as_ref_deref::check(cx, expr, recv2, m_arg, false, self.msrv),
3373 ("filter", [f_arg]) => {
3374 filter_map::check(cx, expr, recv2, f_arg, span2, recv, m_arg, span, false);
3376 ("find", [f_arg]) => {
3377 filter_map::check(cx, expr, recv2, f_arg, span2, recv, m_arg, span, true);
3382 map_identity::check(cx, expr, recv, m_arg, name, span);
3384 ("map_or", [def, map]) => {
3385 option_map_or_none::check(cx, expr, recv, def, map);
3386 manual_ok_or::check(cx, expr, recv, def, map);
3389 if let Some((name2, [recv2, args2 @ ..], _)) = method_call(recv) {
3390 match (name2, args2) {
3391 ("cloned", []) => iter_overeager_cloned::check(cx, expr, recv, recv2, false, false),
3392 ("filter", [arg]) => filter_next::check(cx, expr, recv2, arg),
3393 ("filter_map", [arg]) => filter_map_next::check(cx, expr, recv2, arg, self.msrv),
3394 ("iter", []) => iter_next_slice::check(cx, expr, recv2),
3395 ("skip", [arg]) => iter_skip_next::check(cx, expr, recv2, arg),
3396 ("skip_while", [_]) => skip_while_next::check(cx, expr),
3401 ("nth", [n_arg]) => match method_call(recv) {
3402 Some(("bytes", [recv2], _)) => bytes_nth::check(cx, expr, recv2, n_arg),
3403 Some(("cloned", [recv2], _)) => iter_overeager_cloned::check(cx, expr, recv, recv2, false, false),
3404 Some(("iter", [recv2], _)) => iter_nth::check(cx, expr, recv2, recv, n_arg, false),
3405 Some(("iter_mut", [recv2], _)) => iter_nth::check(cx, expr, recv2, recv, n_arg, true),
3406 _ => iter_nth_zero::check(cx, expr, recv, n_arg),
3408 ("ok_or_else", [arg]) => unnecessary_lazy_eval::check(cx, expr, recv, arg, "ok_or"),
3410 open_options::check(cx, expr, recv);
3412 ("or_else", [arg]) => {
3413 if !bind_instead_of_map::ResultOrElseErrInfo::check(cx, expr, recv, arg) {
3414 unnecessary_lazy_eval::check(cx, expr, recv, arg, "or");
3417 ("push", [arg]) => {
3418 path_buf_push_overwrite::check(cx, expr, arg);
3420 ("repeat", [arg]) => {
3421 repeat_once::check(cx, expr, recv, arg);
3424 stable_sort_primitive::check(cx, expr, recv);
3426 ("sort_by", [arg]) => {
3427 unnecessary_sort_by::check(cx, expr, recv, arg, false);
3429 ("sort_unstable_by", [arg]) => {
3430 unnecessary_sort_by::check(cx, expr, recv, arg, true);
3432 ("splitn" | "rsplitn", [count_arg, pat_arg]) => {
3433 if let Some((Constant::Int(count), _)) = constant(cx, cx.typeck_results(), count_arg) {
3434 suspicious_splitn::check(cx, name, expr, recv, count);
3435 str_splitn::check(cx, name, expr, recv, pat_arg, count, self.msrv);
3438 ("splitn_mut" | "rsplitn_mut", [count_arg, _]) => {
3439 if let Some((Constant::Int(count), _)) = constant(cx, cx.typeck_results(), count_arg) {
3440 suspicious_splitn::check(cx, name, expr, recv, count);
3443 ("step_by", [arg]) => iterator_step_by_zero::check(cx, expr, arg),
3444 ("take", [_arg]) => {
3445 if let Some((name2, [recv2, args2 @ ..], _span2)) = method_call(recv) {
3446 if let ("cloned", []) = (name2, args2) {
3447 iter_overeager_cloned::check(cx, expr, recv, recv2, false, false);
3451 ("take", []) => needless_option_take::check(cx, expr, recv),
3452 ("then", [arg]) => {
3453 if !meets_msrv(self.msrv, msrvs::BOOL_THEN_SOME) {
3456 unnecessary_lazy_eval::check(cx, expr, recv, arg, "then_some");
3458 ("to_os_string" | "to_owned" | "to_path_buf" | "to_vec", []) => {
3459 implicit_clone::check(cx, name, expr, recv);
3462 match method_call(recv) {
3463 Some(("get", [recv, get_arg], _)) => {
3464 get_unwrap::check(cx, expr, recv, get_arg, false);
3466 Some(("get_mut", [recv, get_arg], _)) => {
3467 get_unwrap::check(cx, expr, recv, get_arg, true);
3469 Some(("or", [recv, or_arg], or_span)) => {
3470 or_then_unwrap::check(cx, expr, recv, or_arg, or_span);
3474 unwrap_used::check(cx, expr, recv, false, self.allow_unwrap_in_tests);
3476 ("unwrap_err", []) => unwrap_used::check(cx, expr, recv, true, self.allow_unwrap_in_tests),
3477 ("unwrap_or", [u_arg]) => match method_call(recv) {
3478 Some((arith @ ("checked_add" | "checked_sub" | "checked_mul"), [lhs, rhs], _)) => {
3479 manual_saturating_arithmetic::check(cx, expr, lhs, rhs, u_arg, &arith["checked_".len()..]);
3481 Some(("map", [m_recv, m_arg], span)) => {
3482 option_map_unwrap_or::check(cx, expr, m_recv, m_arg, recv, u_arg, span);
3484 Some(("then_some", [t_recv, t_arg], _)) => {
3485 obfuscated_if_else::check(cx, expr, t_recv, t_arg, u_arg);
3489 ("unwrap_or_else", [u_arg]) => match method_call(recv) {
3490 Some(("map", [recv, map_arg], _))
3491 if map_unwrap_or::check(cx, expr, recv, map_arg, u_arg, self.msrv) => {},
3493 unwrap_or_else_default::check(cx, expr, recv, u_arg);
3494 unnecessary_lazy_eval::check(cx, expr, recv, u_arg, "unwrap_or");
3497 ("replace" | "replacen", [arg1, arg2] | [arg1, arg2, _]) => {
3498 no_effect_replace::check(cx, expr, arg1, arg2);
3501 if let ExprKind::MethodCall(name, [iter_recv], _) = recv.kind
3502 && name.ident.name == sym::iter
3504 range_zip_with_len::check(cx, expr, iter_recv, arg);
3513 fn check_is_some_is_none(cx: &LateContext<'_>, expr: &Expr<'_>, recv: &Expr<'_>, is_some: bool) {
3514 if let Some((name @ ("find" | "position" | "rposition"), [f_recv, arg], span)) = method_call(recv) {
3515 search_is_some::check(cx, expr, name, is_some, f_recv, arg, recv, span);
3519 /// Used for `lint_binary_expr_with_method_call`.
3520 #[derive(Copy, Clone)]
3521 struct BinaryExprInfo<'a> {
3522 expr: &'a hir::Expr<'a>,
3523 chain: &'a hir::Expr<'a>,
3524 other: &'a hir::Expr<'a>,
3528 /// Checks for the `CHARS_NEXT_CMP` and `CHARS_LAST_CMP` lints.
3529 fn lint_binary_expr_with_method_call(cx: &LateContext<'_>, info: &mut BinaryExprInfo<'_>) {
3530 macro_rules! lint_with_both_lhs_and_rhs {
3531 ($func:expr, $cx:expr, $info:ident) => {
3532 if !$func($cx, $info) {
3533 ::std::mem::swap(&mut $info.chain, &mut $info.other);
3534 if $func($cx, $info) {
3541 lint_with_both_lhs_and_rhs!(chars_next_cmp::check, cx, info);
3542 lint_with_both_lhs_and_rhs!(chars_last_cmp::check, cx, info);
3543 lint_with_both_lhs_and_rhs!(chars_next_cmp_with_unwrap::check, cx, info);
3544 lint_with_both_lhs_and_rhs!(chars_last_cmp_with_unwrap::check, cx, info);
3547 const FN_HEADER: hir::FnHeader = hir::FnHeader {
3548 unsafety: hir::Unsafety::Normal,
3549 constness: hir::Constness::NotConst,
3550 asyncness: hir::IsAsync::NotAsync,
3551 abi: rustc_target::spec::abi::Abi::Rust,
3554 struct ShouldImplTraitCase {
3555 trait_name: &'static str,
3556 method_name: &'static str,
3558 fn_header: hir::FnHeader,
3559 // implicit self kind expected (none, self, &self, ...)
3560 self_kind: SelfKind,
3561 // checks against the output type
3562 output_type: OutType,
3563 // certain methods with explicit lifetimes can't implement the equivalent trait method
3564 lint_explicit_lifetime: bool,
3566 impl ShouldImplTraitCase {
3568 trait_name: &'static str,
3569 method_name: &'static str,
3571 fn_header: hir::FnHeader,
3572 self_kind: SelfKind,
3573 output_type: OutType,
3574 lint_explicit_lifetime: bool,
3575 ) -> ShouldImplTraitCase {
3576 ShouldImplTraitCase {
3583 lint_explicit_lifetime,
3587 fn lifetime_param_cond(&self, impl_item: &hir::ImplItem<'_>) -> bool {
3588 self.lint_explicit_lifetime
3589 || !impl_item.generics.params.iter().any(|p| {
3592 hir::GenericParamKind::Lifetime {
3593 kind: hir::LifetimeParamKind::Explicit
3601 const TRAIT_METHODS: [ShouldImplTraitCase; 30] = [
3602 ShouldImplTraitCase::new("std::ops::Add", "add", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3603 ShouldImplTraitCase::new("std::convert::AsMut", "as_mut", 1, FN_HEADER, SelfKind::RefMut, OutType::Ref, true),
3604 ShouldImplTraitCase::new("std::convert::AsRef", "as_ref", 1, FN_HEADER, SelfKind::Ref, OutType::Ref, true),
3605 ShouldImplTraitCase::new("std::ops::BitAnd", "bitand", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3606 ShouldImplTraitCase::new("std::ops::BitOr", "bitor", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3607 ShouldImplTraitCase::new("std::ops::BitXor", "bitxor", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3608 ShouldImplTraitCase::new("std::borrow::Borrow", "borrow", 1, FN_HEADER, SelfKind::Ref, OutType::Ref, true),
3609 ShouldImplTraitCase::new("std::borrow::BorrowMut", "borrow_mut", 1, FN_HEADER, SelfKind::RefMut, OutType::Ref, true),
3610 ShouldImplTraitCase::new("std::clone::Clone", "clone", 1, FN_HEADER, SelfKind::Ref, OutType::Any, true),
3611 ShouldImplTraitCase::new("std::cmp::Ord", "cmp", 2, FN_HEADER, SelfKind::Ref, OutType::Any, true),
3612 // FIXME: default doesn't work
3613 ShouldImplTraitCase::new("std::default::Default", "default", 0, FN_HEADER, SelfKind::No, OutType::Any, true),
3614 ShouldImplTraitCase::new("std::ops::Deref", "deref", 1, FN_HEADER, SelfKind::Ref, OutType::Ref, true),
3615 ShouldImplTraitCase::new("std::ops::DerefMut", "deref_mut", 1, FN_HEADER, SelfKind::RefMut, OutType::Ref, true),
3616 ShouldImplTraitCase::new("std::ops::Div", "div", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3617 ShouldImplTraitCase::new("std::ops::Drop", "drop", 1, FN_HEADER, SelfKind::RefMut, OutType::Unit, true),
3618 ShouldImplTraitCase::new("std::cmp::PartialEq", "eq", 2, FN_HEADER, SelfKind::Ref, OutType::Bool, true),
3619 ShouldImplTraitCase::new("std::iter::FromIterator", "from_iter", 1, FN_HEADER, SelfKind::No, OutType::Any, true),
3620 ShouldImplTraitCase::new("std::str::FromStr", "from_str", 1, FN_HEADER, SelfKind::No, OutType::Any, true),
3621 ShouldImplTraitCase::new("std::hash::Hash", "hash", 2, FN_HEADER, SelfKind::Ref, OutType::Unit, true),
3622 ShouldImplTraitCase::new("std::ops::Index", "index", 2, FN_HEADER, SelfKind::Ref, OutType::Ref, true),
3623 ShouldImplTraitCase::new("std::ops::IndexMut", "index_mut", 2, FN_HEADER, SelfKind::RefMut, OutType::Ref, true),
3624 ShouldImplTraitCase::new("std::iter::IntoIterator", "into_iter", 1, FN_HEADER, SelfKind::Value, OutType::Any, true),
3625 ShouldImplTraitCase::new("std::ops::Mul", "mul", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3626 ShouldImplTraitCase::new("std::ops::Neg", "neg", 1, FN_HEADER, SelfKind::Value, OutType::Any, true),
3627 ShouldImplTraitCase::new("std::iter::Iterator", "next", 1, FN_HEADER, SelfKind::RefMut, OutType::Any, false),
3628 ShouldImplTraitCase::new("std::ops::Not", "not", 1, FN_HEADER, SelfKind::Value, OutType::Any, true),
3629 ShouldImplTraitCase::new("std::ops::Rem", "rem", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3630 ShouldImplTraitCase::new("std::ops::Shl", "shl", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3631 ShouldImplTraitCase::new("std::ops::Shr", "shr", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3632 ShouldImplTraitCase::new("std::ops::Sub", "sub", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3635 #[derive(Clone, Copy, PartialEq, Eq, Debug)]
3644 fn matches<'a>(self, cx: &LateContext<'a>, parent_ty: Ty<'a>, ty: Ty<'a>) -> bool {
3645 fn matches_value<'a>(cx: &LateContext<'a>, parent_ty: Ty<'a>, ty: Ty<'a>) -> bool {
3646 if ty == parent_ty {
3648 } else if ty.is_box() {
3649 ty.boxed_ty() == parent_ty
3650 } else if is_type_diagnostic_item(cx, ty, sym::Rc) || is_type_diagnostic_item(cx, ty, sym::Arc) {
3651 if let ty::Adt(_, substs) = ty.kind() {
3652 substs.types().next().map_or(false, |t| t == parent_ty)
3661 fn matches_ref<'a>(cx: &LateContext<'a>, mutability: hir::Mutability, parent_ty: Ty<'a>, ty: Ty<'a>) -> bool {
3662 if let ty::Ref(_, t, m) = *ty.kind() {
3663 return m == mutability && t == parent_ty;
3666 let trait_path = match mutability {
3667 hir::Mutability::Not => &paths::ASREF_TRAIT,
3668 hir::Mutability::Mut => &paths::ASMUT_TRAIT,
3671 let trait_def_id = match get_trait_def_id(cx, trait_path) {
3673 None => return false,
3675 implements_trait(cx, ty, trait_def_id, &[parent_ty.into()])
3678 fn matches_none<'a>(cx: &LateContext<'a>, parent_ty: Ty<'a>, ty: Ty<'a>) -> bool {
3679 !matches_value(cx, parent_ty, ty)
3680 && !matches_ref(cx, hir::Mutability::Not, parent_ty, ty)
3681 && !matches_ref(cx, hir::Mutability::Mut, parent_ty, ty)
3685 Self::Value => matches_value(cx, parent_ty, ty),
3686 Self::Ref => matches_ref(cx, hir::Mutability::Not, parent_ty, ty) || ty == parent_ty && is_copy(cx, ty),
3687 Self::RefMut => matches_ref(cx, hir::Mutability::Mut, parent_ty, ty),
3688 Self::No => matches_none(cx, parent_ty, ty),
3693 fn description(self) -> &'static str {
3695 Self::Value => "`self` by value",
3696 Self::Ref => "`self` by reference",
3697 Self::RefMut => "`self` by mutable reference",
3698 Self::No => "no `self`",
3703 #[derive(Clone, Copy)]
3712 fn matches(self, ty: &hir::FnRetTy<'_>) -> bool {
3713 let is_unit = |ty: &hir::Ty<'_>| matches!(ty.kind, hir::TyKind::Tup(&[]));
3715 (Self::Unit, &hir::FnRetTy::DefaultReturn(_)) => true,
3716 (Self::Unit, &hir::FnRetTy::Return(ty)) if is_unit(ty) => true,
3717 (Self::Bool, &hir::FnRetTy::Return(ty)) if is_bool(ty) => true,
3718 (Self::Any, &hir::FnRetTy::Return(ty)) if !is_unit(ty) => true,
3719 (Self::Ref, &hir::FnRetTy::Return(ty)) => matches!(ty.kind, hir::TyKind::Rptr(_, _)),
3725 fn is_bool(ty: &hir::Ty<'_>) -> bool {
3726 if let hir::TyKind::Path(QPath::Resolved(_, path)) = ty.kind {
3727 matches!(path.res, Res::PrimTy(PrimTy::Bool))
3733 fn fn_header_equals(expected: hir::FnHeader, actual: hir::FnHeader) -> bool {
3734 expected.constness == actual.constness
3735 && expected.unsafety == actual.unsafety
3736 && expected.asyncness == actual.asyncness