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 vec_resize_to_zero;
94 mod verbose_file_reads;
95 mod wrong_self_convention;
98 use bind_instead_of_map::BindInsteadOfMap;
99 use clippy_utils::consts::{constant, Constant};
100 use clippy_utils::diagnostics::{span_lint, span_lint_and_help};
101 use clippy_utils::ty::{contains_adt_constructor, contains_ty, implements_trait, is_copy, is_type_diagnostic_item};
103 contains_return, get_trait_def_id, is_trait_method, iter_input_pats, meets_msrv, msrvs, paths, return_ty,
105 use if_chain::if_chain;
106 use rustc_hir as hir;
107 use rustc_hir::def::Res;
108 use rustc_hir::{Expr, ExprKind, PrimTy, QPath, TraitItem, TraitItemKind};
109 use rustc_lint::{LateContext, LateLintPass, LintContext};
110 use rustc_middle::lint::in_external_macro;
111 use rustc_middle::ty::{self, TraitRef, Ty};
112 use rustc_semver::RustcVersion;
113 use rustc_session::{declare_tool_lint, impl_lint_pass};
114 use rustc_span::{sym, Span};
115 use rustc_typeck::hir_ty_to_ty;
117 declare_clippy_lint! {
119 /// Checks for usages of `cloned()` on an `Iterator` or `Option` where
120 /// `copied()` could be used instead.
122 /// ### Why is this bad?
123 /// `copied()` is better because it guarantees that the type being cloned
124 /// implements `Copy`.
128 /// [1, 2, 3].iter().cloned();
132 /// [1, 2, 3].iter().copied();
134 #[clippy::version = "1.53.0"]
135 pub CLONED_INSTEAD_OF_COPIED,
137 "used `cloned` where `copied` could be used instead"
140 declare_clippy_lint! {
142 /// Checks for usage of `_.cloned().<func>()` where call to `.cloned()` can be postponed.
144 /// ### Why is this bad?
145 /// It's often inefficient to clone all elements of an iterator, when eventually, only some
146 /// of them will be consumed.
148 /// ### Known Problems
149 /// This `lint` removes the side of effect of cloning items in the iterator.
150 /// A code that relies on that side-effect could fail.
154 /// # let vec = vec!["string".to_string()];
155 /// vec.iter().cloned().take(10);
156 /// vec.iter().cloned().last();
161 /// # let vec = vec!["string".to_string()];
162 /// vec.iter().take(10).cloned();
163 /// vec.iter().last().cloned();
165 #[clippy::version = "1.60.0"]
166 pub ITER_OVEREAGER_CLONED,
168 "using `cloned()` early with `Iterator::iter()` can lead to some performance inefficiencies"
171 declare_clippy_lint! {
173 /// Checks for usages of `Iterator::flat_map()` where `filter_map()` could be
176 /// ### Why is this bad?
177 /// When applicable, `filter_map()` is more clear since it shows that
178 /// `Option` is used to produce 0 or 1 items.
182 /// let nums: Vec<i32> = ["1", "2", "whee!"].iter().flat_map(|x| x.parse().ok()).collect();
186 /// let nums: Vec<i32> = ["1", "2", "whee!"].iter().filter_map(|x| x.parse().ok()).collect();
188 #[clippy::version = "1.53.0"]
191 "used `flat_map` where `filter_map` could be used instead"
194 declare_clippy_lint! {
196 /// Checks for `.unwrap()` or `.unwrap_err()` calls on `Result`s and `.unwrap()` call on `Option`s.
198 /// ### Why is this bad?
199 /// It is better to handle the `None` or `Err` case,
200 /// or at least call `.expect(_)` with a more helpful message. Still, for a lot of
201 /// quick-and-dirty code, `unwrap` is a good choice, which is why this lint is
202 /// `Allow` by default.
204 /// `result.unwrap()` will let the thread panic on `Err` values.
205 /// Normally, you want to implement more sophisticated error handling,
206 /// and propagate errors upwards with `?` operator.
208 /// Even if you want to panic on errors, not all `Error`s implement good
209 /// messages on display. Therefore, it may be beneficial to look at the places
210 /// where they may get displayed. Activate this lint to do just that.
214 /// # let option = Some(1);
215 /// # let result: Result<usize, ()> = Ok(1);
222 /// # let option = Some(1);
223 /// # let result: Result<usize, ()> = Ok(1);
224 /// option.expect("more helpful message");
225 /// result.expect("more helpful message");
228 /// If [expect_used](#expect_used) is enabled, instead:
230 /// # let option = Some(1);
231 /// # let result: Result<usize, ()> = Ok(1);
238 #[clippy::version = "1.45.0"]
241 "using `.unwrap()` on `Result` or `Option`, which should at least get a better message using `expect()`"
244 declare_clippy_lint! {
246 /// Checks for `.expect()` or `.expect_err()` calls on `Result`s and `.expect()` call on `Option`s.
248 /// ### Why is this bad?
249 /// Usually it is better to handle the `None` or `Err` case.
250 /// Still, for a lot of quick-and-dirty code, `expect` is a good choice, which is why
251 /// this lint is `Allow` by default.
253 /// `result.expect()` will let the thread panic on `Err`
254 /// values. Normally, you want to implement more sophisticated error handling,
255 /// and propagate errors upwards with `?` operator.
259 /// # let option = Some(1);
260 /// # let result: Result<usize, ()> = Ok(1);
261 /// option.expect("one");
262 /// result.expect("one");
267 /// # let option = Some(1);
268 /// # let result: Result<usize, ()> = Ok(1);
275 #[clippy::version = "1.45.0"]
278 "using `.expect()` on `Result` or `Option`, which might be better handled"
281 declare_clippy_lint! {
283 /// Checks for methods that should live in a trait
284 /// implementation of a `std` trait (see [llogiq's blog
285 /// post](http://llogiq.github.io/2015/07/30/traits.html) for further
286 /// information) instead of an inherent implementation.
288 /// ### Why is this bad?
289 /// Implementing the traits improve ergonomics for users of
290 /// the code, often with very little cost. Also people seeing a `mul(...)`
292 /// may expect `*` to work equally, so you should have good reason to disappoint
299 /// fn add(&self, other: &X) -> X {
305 #[clippy::version = "pre 1.29.0"]
306 pub SHOULD_IMPLEMENT_TRAIT,
308 "defining a method that should be implementing a std trait"
311 declare_clippy_lint! {
313 /// Checks for methods with certain name prefixes and which
314 /// doesn't match how self is taken. The actual rules are:
316 /// |Prefix |Postfix |`self` taken | `self` type |
317 /// |-------|------------|-------------------------------|--------------|
318 /// |`as_` | none |`&self` or `&mut self` | any |
319 /// |`from_`| none | none | any |
320 /// |`into_`| none |`self` | any |
321 /// |`is_` | none |`&mut self` or `&self` or none | any |
322 /// |`to_` | `_mut` |`&mut self` | any |
323 /// |`to_` | not `_mut` |`self` | `Copy` |
324 /// |`to_` | not `_mut` |`&self` | not `Copy` |
326 /// Note: Clippy doesn't trigger methods with `to_` prefix in:
327 /// - Traits definition.
328 /// Clippy can not tell if a type that implements a trait is `Copy` or not.
329 /// - Traits implementation, when `&self` is taken.
330 /// The method signature is controlled by the trait and often `&self` is required for all types that implement the trait
331 /// (see e.g. the `std::string::ToString` trait).
333 /// Clippy allows `Pin<&Self>` and `Pin<&mut Self>` if `&self` and `&mut self` is required.
335 /// Please find more info here:
336 /// https://rust-lang.github.io/api-guidelines/naming.html#ad-hoc-conversions-follow-as_-to_-into_-conventions-c-conv
338 /// ### Why is this bad?
339 /// Consistency breeds readability. If you follow the
340 /// conventions, your users won't be surprised that they, e.g., need to supply a
341 /// mutable reference to a `as_..` function.
347 /// fn as_str(self) -> &'static str {
353 #[clippy::version = "pre 1.29.0"]
354 pub WRONG_SELF_CONVENTION,
356 "defining a method named with an established prefix (like \"into_\") that takes `self` with the wrong convention"
359 declare_clippy_lint! {
361 /// Checks for usage of `ok().expect(..)`.
363 /// ### Why is this bad?
364 /// Because you usually call `expect()` on the `Result`
365 /// directly to get a better error message.
367 /// ### Known problems
368 /// The error type needs to implement `Debug`
372 /// # let x = Ok::<_, ()>(());
373 /// x.ok().expect("why did I do this again?");
378 /// # let x = Ok::<_, ()>(());
379 /// x.expect("why did I do this again?");
381 #[clippy::version = "pre 1.29.0"]
384 "using `ok().expect()`, which gives worse error messages than calling `expect` directly on the Result"
387 declare_clippy_lint! {
389 /// Checks for `.err().expect()` calls on the `Result` type.
391 /// ### Why is this bad?
392 /// `.expect_err()` can be called directly to avoid the extra type conversion from `err()`.
396 /// let x: Result<u32, &str> = Ok(10);
397 /// x.err().expect("Testing err().expect()");
401 /// let x: Result<u32, &str> = Ok(10);
402 /// x.expect_err("Testing expect_err");
404 #[clippy::version = "1.62.0"]
407 r#"using `.err().expect("")` when `.expect_err("")` can be used"#
410 declare_clippy_lint! {
412 /// Checks for usages of `_.unwrap_or_else(Default::default)` on `Option` and
415 /// ### Why is this bad?
416 /// Readability, these can be written as `_.unwrap_or_default`, which is
417 /// simpler and more concise.
421 /// # let x = Some(1);
422 /// x.unwrap_or_else(Default::default);
423 /// x.unwrap_or_else(u32::default);
428 /// # let x = Some(1);
429 /// x.unwrap_or_default();
431 #[clippy::version = "1.56.0"]
432 pub UNWRAP_OR_ELSE_DEFAULT,
434 "using `.unwrap_or_else(Default::default)`, which is more succinctly expressed as `.unwrap_or_default()`"
437 declare_clippy_lint! {
439 /// Checks for usage of `option.map(_).unwrap_or(_)` or `option.map(_).unwrap_or_else(_)` or
440 /// `result.map(_).unwrap_or_else(_)`.
442 /// ### Why is this bad?
443 /// Readability, these can be written more concisely (resp.) as
444 /// `option.map_or(_, _)`, `option.map_or_else(_, _)` and `result.map_or_else(_, _)`.
446 /// ### Known problems
447 /// The order of the arguments is not in execution order
451 /// # let option = Some(1);
452 /// # let result: Result<usize, ()> = Ok(1);
453 /// # fn some_function(foo: ()) -> usize { 1 }
454 /// option.map(|a| a + 1).unwrap_or(0);
455 /// result.map(|a| a + 1).unwrap_or_else(some_function);
460 /// # let option = Some(1);
461 /// # let result: Result<usize, ()> = Ok(1);
462 /// # fn some_function(foo: ()) -> usize { 1 }
463 /// option.map_or(0, |a| a + 1);
464 /// result.map_or_else(some_function, |a| a + 1);
466 #[clippy::version = "1.45.0"]
469 "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)`"
472 declare_clippy_lint! {
474 /// Checks for usage of `_.map_or(None, _)`.
476 /// ### Why is this bad?
477 /// Readability, this can be written more concisely as
480 /// ### Known problems
481 /// The order of the arguments is not in execution order.
485 /// # let opt = Some(1);
486 /// opt.map_or(None, |a| Some(a + 1));
491 /// # let opt = Some(1);
492 /// opt.and_then(|a| Some(a + 1));
494 #[clippy::version = "pre 1.29.0"]
495 pub OPTION_MAP_OR_NONE,
497 "using `Option.map_or(None, f)`, which is more succinctly expressed as `and_then(f)`"
500 declare_clippy_lint! {
502 /// Checks for usage of `_.map_or(None, Some)`.
504 /// ### Why is this bad?
505 /// Readability, this can be written more concisely as
510 /// # let r: Result<u32, &str> = Ok(1);
511 /// assert_eq!(Some(1), r.map_or(None, Some));
516 /// # let r: Result<u32, &str> = Ok(1);
517 /// assert_eq!(Some(1), r.ok());
519 #[clippy::version = "1.44.0"]
520 pub RESULT_MAP_OR_INTO_OPTION,
522 "using `Result.map_or(None, Some)`, which is more succinctly expressed as `ok()`"
525 declare_clippy_lint! {
527 /// Checks for usage of `_.and_then(|x| Some(y))`, `_.and_then(|x| Ok(y))` or
528 /// `_.or_else(|x| Err(y))`.
530 /// ### Why is this bad?
531 /// Readability, this can be written more concisely as
532 /// `_.map(|x| y)` or `_.map_err(|x| y)`.
536 /// # fn opt() -> Option<&'static str> { Some("42") }
537 /// # fn res() -> Result<&'static str, &'static str> { Ok("42") }
538 /// let _ = opt().and_then(|s| Some(s.len()));
539 /// let _ = res().and_then(|s| if s.len() == 42 { Ok(10) } else { Ok(20) });
540 /// let _ = res().or_else(|s| if s.len() == 42 { Err(10) } else { Err(20) });
543 /// The correct use would be:
546 /// # fn opt() -> Option<&'static str> { Some("42") }
547 /// # fn res() -> Result<&'static str, &'static str> { Ok("42") }
548 /// let _ = opt().map(|s| s.len());
549 /// let _ = res().map(|s| if s.len() == 42 { 10 } else { 20 });
550 /// let _ = res().map_err(|s| if s.len() == 42 { 10 } else { 20 });
552 #[clippy::version = "1.45.0"]
553 pub BIND_INSTEAD_OF_MAP,
555 "using `Option.and_then(|x| Some(y))`, which is more succinctly expressed as `map(|x| y)`"
558 declare_clippy_lint! {
560 /// Checks for usage of `_.filter(_).next()`.
562 /// ### Why is this bad?
563 /// Readability, this can be written more concisely as
568 /// # let vec = vec![1];
569 /// vec.iter().filter(|x| **x == 0).next();
574 /// # let vec = vec![1];
575 /// vec.iter().find(|x| **x == 0);
577 #[clippy::version = "pre 1.29.0"]
580 "using `filter(p).next()`, which is more succinctly expressed as `.find(p)`"
583 declare_clippy_lint! {
585 /// Checks for usage of `_.skip_while(condition).next()`.
587 /// ### Why is this bad?
588 /// Readability, this can be written more concisely as
589 /// `_.find(!condition)`.
593 /// # let vec = vec![1];
594 /// vec.iter().skip_while(|x| **x == 0).next();
599 /// # let vec = vec![1];
600 /// vec.iter().find(|x| **x != 0);
602 #[clippy::version = "1.42.0"]
605 "using `skip_while(p).next()`, which is more succinctly expressed as `.find(!p)`"
608 declare_clippy_lint! {
610 /// Checks for usage of `_.map(_).flatten(_)` on `Iterator` and `Option`
612 /// ### Why is this bad?
613 /// Readability, this can be written more concisely as
614 /// `_.flat_map(_)` for `Iterator` or `_.and_then(_)` for `Option`
618 /// let vec = vec![vec![1]];
619 /// let opt = Some(5);
621 /// vec.iter().map(|x| x.iter()).flatten();
622 /// opt.map(|x| Some(x * 2)).flatten();
627 /// # let vec = vec![vec![1]];
628 /// # let opt = Some(5);
629 /// vec.iter().flat_map(|x| x.iter());
630 /// opt.and_then(|x| Some(x * 2));
632 #[clippy::version = "1.31.0"]
635 "using combinations of `flatten` and `map` which can usually be written as a single method call"
638 declare_clippy_lint! {
640 /// Checks for usage of `_.filter(_).map(_)` that can be written more simply
641 /// as `filter_map(_)`.
643 /// ### Why is this bad?
644 /// Redundant code in the `filter` and `map` operations is poor style and
649 /// # #![allow(unused)]
651 /// .filter(|n| n.checked_add(1).is_some())
652 /// .map(|n| n.checked_add(1).unwrap());
657 /// # #[allow(unused)]
658 /// (0_i32..10).filter_map(|n| n.checked_add(1));
660 #[clippy::version = "1.51.0"]
661 pub MANUAL_FILTER_MAP,
663 "using `_.filter(_).map(_)` in a way that can be written more simply as `filter_map(_)`"
666 declare_clippy_lint! {
668 /// Checks for usage of `_.find(_).map(_)` that can be written more simply
669 /// as `find_map(_)`.
671 /// ### Why is this bad?
672 /// Redundant code in the `find` and `map` operations is poor style and
678 /// .find(|n| n.checked_add(1).is_some())
679 /// .map(|n| n.checked_add(1).unwrap());
684 /// (0_i32..10).find_map(|n| n.checked_add(1));
686 #[clippy::version = "1.51.0"]
689 "using `_.find(_).map(_)` in a way that can be written more simply as `find_map(_)`"
692 declare_clippy_lint! {
694 /// Checks for usage of `_.filter_map(_).next()`.
696 /// ### Why is this bad?
697 /// Readability, this can be written more concisely as
702 /// (0..3).filter_map(|x| if x == 2 { Some(x) } else { None }).next();
704 /// Can be written as
707 /// (0..3).find_map(|x| if x == 2 { Some(x) } else { None });
709 #[clippy::version = "1.36.0"]
712 "using combination of `filter_map` and `next` which can usually be written as a single method call"
715 declare_clippy_lint! {
717 /// Checks for usage of `flat_map(|x| x)`.
719 /// ### Why is this bad?
720 /// Readability, this can be written more concisely by using `flatten`.
724 /// # let iter = vec![vec![0]].into_iter();
725 /// iter.flat_map(|x| x);
727 /// Can be written as
729 /// # let iter = vec![vec![0]].into_iter();
732 #[clippy::version = "1.39.0"]
733 pub FLAT_MAP_IDENTITY,
735 "call to `flat_map` where `flatten` is sufficient"
738 declare_clippy_lint! {
740 /// Checks for an iterator or string search (such as `find()`,
741 /// `position()`, or `rposition()`) followed by a call to `is_some()` or `is_none()`.
743 /// ### Why is this bad?
744 /// Readability, this can be written more concisely as:
745 /// * `_.any(_)`, or `_.contains(_)` for `is_some()`,
746 /// * `!_.any(_)`, or `!_.contains(_)` for `is_none()`.
750 /// # #![allow(unused)]
751 /// let vec = vec![1];
752 /// vec.iter().find(|x| **x == 0).is_some();
754 /// "hello world".find("world").is_none();
759 /// let vec = vec![1];
760 /// vec.iter().any(|x| *x == 0);
762 /// # #[allow(unused)]
763 /// !"hello world".contains("world");
765 #[clippy::version = "pre 1.29.0"]
768 "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()`)"
771 declare_clippy_lint! {
773 /// Checks for usage of `.chars().next()` on a `str` to check
774 /// if it starts with a given char.
776 /// ### Why is this bad?
777 /// Readability, this can be written more concisely as
778 /// `_.starts_with(_)`.
782 /// let name = "foo";
783 /// if name.chars().next() == Some('_') {};
788 /// let name = "foo";
789 /// if name.starts_with('_') {};
791 #[clippy::version = "pre 1.29.0"]
794 "using `.chars().next()` to check if a string starts with a char"
797 declare_clippy_lint! {
799 /// Checks for calls to `.or(foo(..))`, `.unwrap_or(foo(..))`,
800 /// etc., and suggests to use `or_else`, `unwrap_or_else`, etc., or
801 /// `unwrap_or_default` instead.
803 /// ### Why is this bad?
804 /// The function will always be called and potentially
805 /// allocate an object acting as the default.
807 /// ### Known problems
808 /// If the function has side-effects, not calling it will
809 /// change the semantic of the program, but you shouldn't rely on that anyway.
813 /// # let foo = Some(String::new());
814 /// foo.unwrap_or(String::new());
819 /// # let foo = Some(String::new());
820 /// foo.unwrap_or_else(String::new);
824 /// # let foo = Some(String::new());
825 /// foo.unwrap_or_default();
827 #[clippy::version = "pre 1.29.0"]
830 "using any `*or` method with a function call, which suggests `*or_else`"
833 declare_clippy_lint! {
835 /// Checks for `.or(…).unwrap()` calls to Options and Results.
837 /// ### Why is this bad?
838 /// You should use `.unwrap_or(…)` instead for clarity.
842 /// # let fallback = "fallback";
844 /// # type Error = &'static str;
845 /// # let result: Result<&str, Error> = Err("error");
846 /// let value = result.or::<Error>(Ok(fallback)).unwrap();
849 /// # let option: Option<&str> = None;
850 /// let value = option.or(Some(fallback)).unwrap();
854 /// # let fallback = "fallback";
856 /// # let result: Result<&str, &str> = Err("error");
857 /// let value = result.unwrap_or(fallback);
860 /// # let option: Option<&str> = None;
861 /// let value = option.unwrap_or(fallback);
863 #[clippy::version = "1.61.0"]
866 "checks for `.or(…).unwrap()` calls to Options and Results."
869 declare_clippy_lint! {
871 /// Checks for calls to `.expect(&format!(...))`, `.expect(foo(..))`,
872 /// etc., and suggests to use `unwrap_or_else` instead
874 /// ### Why is this bad?
875 /// The function will always be called.
877 /// ### Known problems
878 /// If the function has side-effects, not calling it will
879 /// change the semantics of the program, but you shouldn't rely on that anyway.
883 /// # let foo = Some(String::new());
884 /// # let err_code = "418";
885 /// # let err_msg = "I'm a teapot";
886 /// foo.expect(&format!("Err {}: {}", err_code, err_msg));
890 /// # let foo = Some(String::new());
891 /// foo.expect(format!("Err {}: {}", err_code, err_msg).as_str());
896 /// # let foo = Some(String::new());
897 /// # let err_code = "418";
898 /// # let err_msg = "I'm a teapot";
899 /// foo.unwrap_or_else(|| panic!("Err {}: {}", err_code, err_msg));
901 #[clippy::version = "pre 1.29.0"]
904 "using any `expect` method with a function call"
907 declare_clippy_lint! {
909 /// Checks for usage of `.clone()` on a `Copy` type.
911 /// ### Why is this bad?
912 /// The only reason `Copy` types implement `Clone` is for
913 /// generics, not for using the `clone` method on a concrete type.
919 #[clippy::version = "pre 1.29.0"]
922 "using `clone` on a `Copy` type"
925 declare_clippy_lint! {
927 /// Checks for usage of `.clone()` on a ref-counted pointer,
928 /// (`Rc`, `Arc`, `rc::Weak`, or `sync::Weak`), and suggests calling Clone via unified
929 /// function syntax instead (e.g., `Rc::clone(foo)`).
931 /// ### Why is this bad?
932 /// Calling '.clone()' on an Rc, Arc, or Weak
933 /// can obscure the fact that only the pointer is being cloned, not the underlying
938 /// # use std::rc::Rc;
939 /// let x = Rc::new(1);
946 /// # use std::rc::Rc;
947 /// # let x = Rc::new(1);
950 #[clippy::version = "pre 1.29.0"]
951 pub CLONE_ON_REF_PTR,
953 "using 'clone' on a ref-counted pointer"
956 declare_clippy_lint! {
958 /// Checks for usage of `.clone()` on an `&&T`.
960 /// ### Why is this bad?
961 /// Cloning an `&&T` copies the inner `&T`, instead of
962 /// cloning the underlying `T`.
969 /// let z = y.clone();
970 /// println!("{:p} {:p}", *y, z); // prints out the same pointer
973 #[clippy::version = "pre 1.29.0"]
974 pub CLONE_DOUBLE_REF,
976 "using `clone` on `&&T`"
979 declare_clippy_lint! {
981 /// Checks for usage of `.to_string()` on an `&&T` where
982 /// `T` implements `ToString` directly (like `&&str` or `&&String`).
984 /// ### Why is this bad?
985 /// This bypasses the specialized implementation of
986 /// `ToString` and instead goes through the more expensive string formatting
991 /// // Generic implementation for `T: Display` is used (slow)
992 /// ["foo", "bar"].iter().map(|s| s.to_string());
994 /// // OK, the specialized impl is used
995 /// ["foo", "bar"].iter().map(|&s| s.to_string());
997 #[clippy::version = "1.40.0"]
998 pub INEFFICIENT_TO_STRING,
1000 "using `to_string` on `&&T` where `T: ToString`"
1003 declare_clippy_lint! {
1004 /// ### What it does
1005 /// Checks for `new` not returning a type that contains `Self`.
1007 /// ### Why is this bad?
1008 /// As a convention, `new` methods are used to make a new
1009 /// instance of a type.
1012 /// In an impl block:
1015 /// # struct NotAFoo;
1017 /// fn new() -> NotAFoo {
1025 /// struct Bar(Foo);
1027 /// // Bad. The type name must contain `Self`
1028 /// fn new() -> Bar {
1036 /// # struct FooError;
1038 /// // Good. Return type contains `Self`
1039 /// fn new() -> Result<Foo, FooError> {
1045 /// Or in a trait definition:
1047 /// pub trait Trait {
1048 /// // Bad. The type name must contain `Self`
1054 /// pub trait Trait {
1055 /// // Good. Return type contains `Self`
1056 /// fn new() -> Self;
1059 #[clippy::version = "pre 1.29.0"]
1060 pub NEW_RET_NO_SELF,
1062 "not returning type containing `Self` in a `new` method"
1065 declare_clippy_lint! {
1066 /// ### What it does
1067 /// Checks for string methods that receive a single-character
1068 /// `str` as an argument, e.g., `_.split("x")`.
1070 /// ### Why is this bad?
1071 /// Performing these methods using a `char` is faster than
1074 /// ### Known problems
1075 /// Does not catch multi-byte unicode characters.
1086 #[clippy::version = "pre 1.29.0"]
1087 pub SINGLE_CHAR_PATTERN,
1089 "using a single-character str where a char could be used, e.g., `_.split(\"x\")`"
1092 declare_clippy_lint! {
1093 /// ### What it does
1094 /// Checks for calling `.step_by(0)` on iterators which panics.
1096 /// ### Why is this bad?
1097 /// This very much looks like an oversight. Use `panic!()` instead if you
1098 /// actually intend to panic.
1101 /// ```rust,should_panic
1102 /// for x in (0..100).step_by(0) {
1106 #[clippy::version = "pre 1.29.0"]
1107 pub ITERATOR_STEP_BY_ZERO,
1109 "using `Iterator::step_by(0)`, which will panic at runtime"
1112 declare_clippy_lint! {
1113 /// ### What it does
1114 /// Checks for indirect collection of populated `Option`
1116 /// ### Why is this bad?
1117 /// `Option` is like a collection of 0-1 things, so `flatten`
1118 /// automatically does this without suspicious-looking `unwrap` calls.
1122 /// let _ = std::iter::empty::<Option<i32>>().filter(Option::is_some).map(Option::unwrap);
1126 /// let _ = std::iter::empty::<Option<i32>>().flatten();
1128 #[clippy::version = "1.53.0"]
1129 pub OPTION_FILTER_MAP,
1131 "filtering `Option` for `Some` then force-unwrapping, which can be one type-safe operation"
1134 declare_clippy_lint! {
1135 /// ### What it does
1136 /// Checks for the use of `iter.nth(0)`.
1138 /// ### Why is this bad?
1139 /// `iter.next()` is equivalent to
1140 /// `iter.nth(0)`, as they both consume the next element,
1141 /// but is more readable.
1145 /// # use std::collections::HashSet;
1146 /// # let mut s = HashSet::new();
1148 /// let x = s.iter().nth(0);
1153 /// # use std::collections::HashSet;
1154 /// # let mut s = HashSet::new();
1156 /// let x = s.iter().next();
1158 #[clippy::version = "1.42.0"]
1161 "replace `iter.nth(0)` with `iter.next()`"
1164 declare_clippy_lint! {
1165 /// ### What it does
1166 /// Checks for use of `.iter().nth()` (and the related
1167 /// `.iter_mut().nth()`) on standard library types with *O*(1) element access.
1169 /// ### Why is this bad?
1170 /// `.get()` and `.get_mut()` are more efficient and more
1175 /// let some_vec = vec![0, 1, 2, 3];
1176 /// let bad_vec = some_vec.iter().nth(3);
1177 /// let bad_slice = &some_vec[..].iter().nth(3);
1179 /// The correct use would be:
1181 /// let some_vec = vec![0, 1, 2, 3];
1182 /// let bad_vec = some_vec.get(3);
1183 /// let bad_slice = &some_vec[..].get(3);
1185 #[clippy::version = "pre 1.29.0"]
1188 "using `.iter().nth()` on a standard library type with O(1) element access"
1191 declare_clippy_lint! {
1192 /// ### What it does
1193 /// Checks for use of `.skip(x).next()` on iterators.
1195 /// ### Why is this bad?
1196 /// `.nth(x)` is cleaner
1200 /// let some_vec = vec![0, 1, 2, 3];
1201 /// let bad_vec = some_vec.iter().skip(3).next();
1202 /// let bad_slice = &some_vec[..].iter().skip(3).next();
1204 /// The correct use would be:
1206 /// let some_vec = vec![0, 1, 2, 3];
1207 /// let bad_vec = some_vec.iter().nth(3);
1208 /// let bad_slice = &some_vec[..].iter().nth(3);
1210 #[clippy::version = "pre 1.29.0"]
1213 "using `.skip(x).next()` on an iterator"
1216 declare_clippy_lint! {
1217 /// ### What it does
1218 /// Checks for use of `.drain(..)` on `Vec` and `VecDeque` for iteration.
1220 /// ### Why is this bad?
1221 /// `.into_iter()` is simpler with better performance.
1225 /// # use std::collections::HashSet;
1226 /// let mut foo = vec![0, 1, 2, 3];
1227 /// let bar: HashSet<usize> = foo.drain(..).collect();
1231 /// # use std::collections::HashSet;
1232 /// let foo = vec![0, 1, 2, 3];
1233 /// let bar: HashSet<usize> = foo.into_iter().collect();
1235 #[clippy::version = "1.61.0"]
1236 pub ITER_WITH_DRAIN,
1238 "replace `.drain(..)` with `.into_iter()`"
1241 declare_clippy_lint! {
1242 /// ### What it does
1243 /// Checks for using `x.get(x.len() - 1)` instead of
1246 /// ### Why is this bad?
1247 /// Using `x.last()` is easier to read and has the same
1250 /// Note that using `x[x.len() - 1]` is semantically different from
1251 /// `x.last()`. Indexing into the array will panic on out-of-bounds
1252 /// accesses, while `x.get()` and `x.last()` will return `None`.
1254 /// There is another lint (get_unwrap) that covers the case of using
1255 /// `x.get(index).unwrap()` instead of `x[index]`.
1259 /// let x = vec![2, 3, 5];
1260 /// let last_element = x.get(x.len() - 1);
1265 /// let x = vec![2, 3, 5];
1266 /// let last_element = x.last();
1268 #[clippy::version = "1.37.0"]
1269 pub GET_LAST_WITH_LEN,
1271 "Using `x.get(x.len() - 1)` when `x.last()` is correct and simpler"
1274 declare_clippy_lint! {
1275 /// ### What it does
1276 /// Checks for use of `.get().unwrap()` (or
1277 /// `.get_mut().unwrap`) on a standard library type which implements `Index`
1279 /// ### Why is this bad?
1280 /// Using the Index trait (`[]`) is more clear and more
1283 /// ### Known problems
1284 /// Not a replacement for error handling: Using either
1285 /// `.unwrap()` or the Index trait (`[]`) carries the risk of causing a `panic`
1286 /// if the value being accessed is `None`. If the use of `.get().unwrap()` is a
1287 /// temporary placeholder for dealing with the `Option` type, then this does
1288 /// not mitigate the need for error handling. If there is a chance that `.get()`
1289 /// will be `None` in your program, then it is advisable that the `None` case
1290 /// is handled in a future refactor instead of using `.unwrap()` or the Index
1295 /// let mut some_vec = vec![0, 1, 2, 3];
1296 /// let last = some_vec.get(3).unwrap();
1297 /// *some_vec.get_mut(0).unwrap() = 1;
1299 /// The correct use would be:
1301 /// let mut some_vec = vec![0, 1, 2, 3];
1302 /// let last = some_vec[3];
1303 /// some_vec[0] = 1;
1305 #[clippy::version = "pre 1.29.0"]
1308 "using `.get().unwrap()` or `.get_mut().unwrap()` when using `[]` would work instead"
1311 declare_clippy_lint! {
1312 /// ### What it does
1313 /// Checks for occurrences where one vector gets extended instead of append
1315 /// ### Why is this bad?
1316 /// Using `append` instead of `extend` is more concise and faster
1320 /// let mut a = vec![1, 2, 3];
1321 /// let mut b = vec![4, 5, 6];
1323 /// a.extend(b.drain(..));
1328 /// let mut a = vec![1, 2, 3];
1329 /// let mut b = vec![4, 5, 6];
1331 /// a.append(&mut b);
1333 #[clippy::version = "1.55.0"]
1334 pub EXTEND_WITH_DRAIN,
1336 "using vec.append(&mut vec) to move the full range of a vector to another"
1339 declare_clippy_lint! {
1340 /// ### What it does
1341 /// Checks for the use of `.extend(s.chars())` where s is a
1342 /// `&str` or `String`.
1344 /// ### Why is this bad?
1345 /// `.push_str(s)` is clearer
1349 /// let abc = "abc";
1350 /// let def = String::from("def");
1351 /// let mut s = String::new();
1352 /// s.extend(abc.chars());
1353 /// s.extend(def.chars());
1355 /// The correct use would be:
1357 /// let abc = "abc";
1358 /// let def = String::from("def");
1359 /// let mut s = String::new();
1360 /// s.push_str(abc);
1361 /// s.push_str(&def);
1363 #[clippy::version = "pre 1.29.0"]
1364 pub STRING_EXTEND_CHARS,
1366 "using `x.extend(s.chars())` where s is a `&str` or `String`"
1369 declare_clippy_lint! {
1370 /// ### What it does
1371 /// Checks for the use of `.cloned().collect()` on slice to
1374 /// ### Why is this bad?
1375 /// `.to_vec()` is clearer
1379 /// let s = [1, 2, 3, 4, 5];
1380 /// let s2: Vec<isize> = s[..].iter().cloned().collect();
1382 /// The better use would be:
1384 /// let s = [1, 2, 3, 4, 5];
1385 /// let s2: Vec<isize> = s.to_vec();
1387 #[clippy::version = "pre 1.29.0"]
1388 pub ITER_CLONED_COLLECT,
1390 "using `.cloned().collect()` on slice to create a `Vec`"
1393 declare_clippy_lint! {
1394 /// ### What it does
1395 /// Checks for usage of `_.chars().last()` or
1396 /// `_.chars().next_back()` on a `str` to check if it ends with a given char.
1398 /// ### Why is this bad?
1399 /// Readability, this can be written more concisely as
1400 /// `_.ends_with(_)`.
1404 /// # let name = "_";
1405 /// name.chars().last() == Some('_') || name.chars().next_back() == Some('-');
1410 /// # let name = "_";
1411 /// name.ends_with('_') || name.ends_with('-');
1413 #[clippy::version = "pre 1.29.0"]
1416 "using `.chars().last()` or `.chars().next_back()` to check if a string ends with a char"
1419 declare_clippy_lint! {
1420 /// ### What it does
1421 /// Checks for usage of `.as_ref()` or `.as_mut()` where the
1422 /// types before and after the call are the same.
1424 /// ### Why is this bad?
1425 /// The call is unnecessary.
1429 /// # fn do_stuff(x: &[i32]) {}
1430 /// let x: &[i32] = &[1, 2, 3, 4, 5];
1431 /// do_stuff(x.as_ref());
1433 /// The correct use would be:
1435 /// # fn do_stuff(x: &[i32]) {}
1436 /// let x: &[i32] = &[1, 2, 3, 4, 5];
1439 #[clippy::version = "pre 1.29.0"]
1442 "using `as_ref` where the types before and after the call are the same"
1445 declare_clippy_lint! {
1446 /// ### What it does
1447 /// Checks for using `fold` when a more succinct alternative exists.
1448 /// Specifically, this checks for `fold`s which could be replaced by `any`, `all`,
1449 /// `sum` or `product`.
1451 /// ### Why is this bad?
1456 /// # #[allow(unused)]
1457 /// (0..3).fold(false, |acc, x| acc || x > 2);
1462 /// (0..3).any(|x| x > 2);
1464 #[clippy::version = "pre 1.29.0"]
1465 pub UNNECESSARY_FOLD,
1467 "using `fold` when a more succinct alternative exists"
1470 declare_clippy_lint! {
1471 /// ### What it does
1472 /// Checks for `filter_map` calls that could be replaced by `filter` or `map`.
1473 /// More specifically it checks if the closure provided is only performing one of the
1474 /// filter or map operations and suggests the appropriate option.
1476 /// ### Why is this bad?
1477 /// Complexity. The intent is also clearer if only a single
1478 /// operation is being performed.
1482 /// let _ = (0..3).filter_map(|x| if x > 2 { Some(x) } else { None });
1484 /// // As there is no transformation of the argument this could be written as:
1485 /// let _ = (0..3).filter(|&x| x > 2);
1489 /// let _ = (0..4).filter_map(|x| Some(x + 1));
1491 /// // As there is no conditional check on the argument this could be written as:
1492 /// let _ = (0..4).map(|x| x + 1);
1494 #[clippy::version = "1.31.0"]
1495 pub UNNECESSARY_FILTER_MAP,
1497 "using `filter_map` when a more succinct alternative exists"
1500 declare_clippy_lint! {
1501 /// ### What it does
1502 /// Checks for `find_map` calls that could be replaced by `find` or `map`. More
1503 /// specifically it checks if the closure provided is only performing one of the
1504 /// find or map operations and suggests the appropriate option.
1506 /// ### Why is this bad?
1507 /// Complexity. The intent is also clearer if only a single
1508 /// operation is being performed.
1512 /// let _ = (0..3).find_map(|x| if x > 2 { Some(x) } else { None });
1514 /// // As there is no transformation of the argument this could be written as:
1515 /// let _ = (0..3).find(|&x| x > 2);
1519 /// let _ = (0..4).find_map(|x| Some(x + 1));
1521 /// // As there is no conditional check on the argument this could be written as:
1522 /// let _ = (0..4).map(|x| x + 1).next();
1524 #[clippy::version = "1.61.0"]
1525 pub UNNECESSARY_FIND_MAP,
1527 "using `find_map` when a more succinct alternative exists"
1530 declare_clippy_lint! {
1531 /// ### What it does
1532 /// Checks for `into_iter` calls on references which should be replaced by `iter`
1535 /// ### Why is this bad?
1536 /// Readability. Calling `into_iter` on a reference will not move out its
1537 /// content into the resulting iterator, which is confusing. It is better just call `iter` or
1538 /// `iter_mut` directly.
1542 /// # let vec = vec![3, 4, 5];
1543 /// (&vec).into_iter();
1548 /// # let vec = vec![3, 4, 5];
1551 #[clippy::version = "1.32.0"]
1552 pub INTO_ITER_ON_REF,
1554 "using `.into_iter()` on a reference"
1557 declare_clippy_lint! {
1558 /// ### What it does
1559 /// Checks for calls to `map` followed by a `count`.
1561 /// ### Why is this bad?
1562 /// It looks suspicious. Maybe `map` was confused with `filter`.
1563 /// If the `map` call is intentional, this should be rewritten
1564 /// using `inspect`. Or, if you intend to drive the iterator to
1565 /// completion, you can just use `for_each` instead.
1569 /// let _ = (0..3).map(|x| x + 2).count();
1571 #[clippy::version = "1.39.0"]
1574 "suspicious usage of map"
1577 declare_clippy_lint! {
1578 /// ### What it does
1579 /// Checks for `MaybeUninit::uninit().assume_init()`.
1581 /// ### Why is this bad?
1582 /// For most types, this is undefined behavior.
1584 /// ### Known problems
1585 /// For now, we accept empty tuples and tuples / arrays
1586 /// of `MaybeUninit`. There may be other types that allow uninitialized
1587 /// data, but those are not yet rigorously defined.
1591 /// // Beware the UB
1592 /// use std::mem::MaybeUninit;
1594 /// let _: usize = unsafe { MaybeUninit::uninit().assume_init() };
1597 /// Note that the following is OK:
1600 /// use std::mem::MaybeUninit;
1602 /// let _: [MaybeUninit<bool>; 5] = unsafe {
1603 /// MaybeUninit::uninit().assume_init()
1606 #[clippy::version = "1.39.0"]
1607 pub UNINIT_ASSUMED_INIT,
1609 "`MaybeUninit::uninit().assume_init()`"
1612 declare_clippy_lint! {
1613 /// ### What it does
1614 /// Checks for `.checked_add/sub(x).unwrap_or(MAX/MIN)`.
1616 /// ### Why is this bad?
1617 /// These can be written simply with `saturating_add/sub` methods.
1621 /// # let y: u32 = 0;
1622 /// # let x: u32 = 100;
1623 /// let add = x.checked_add(y).unwrap_or(u32::MAX);
1624 /// let sub = x.checked_sub(y).unwrap_or(u32::MIN);
1627 /// can be written using dedicated methods for saturating addition/subtraction as:
1630 /// # let y: u32 = 0;
1631 /// # let x: u32 = 100;
1632 /// let add = x.saturating_add(y);
1633 /// let sub = x.saturating_sub(y);
1635 #[clippy::version = "1.39.0"]
1636 pub MANUAL_SATURATING_ARITHMETIC,
1638 "`.checked_add/sub(x).unwrap_or(MAX/MIN)`"
1641 declare_clippy_lint! {
1642 /// ### What it does
1643 /// Checks for `offset(_)`, `wrapping_`{`add`, `sub`}, etc. on raw pointers to
1644 /// zero-sized types
1646 /// ### Why is this bad?
1647 /// This is a no-op, and likely unintended
1651 /// unsafe { (&() as *const ()).offset(1) };
1653 #[clippy::version = "1.41.0"]
1656 "Check for offset calculations on raw pointers to zero-sized types"
1659 declare_clippy_lint! {
1660 /// ### What it does
1661 /// Checks for `FileType::is_file()`.
1663 /// ### Why is this bad?
1664 /// When people testing a file type with `FileType::is_file`
1665 /// they are testing whether a path is something they can get bytes from. But
1666 /// `is_file` doesn't cover special file types in unix-like systems, and doesn't cover
1667 /// symlink in windows. Using `!FileType::is_dir()` is a better way to that intention.
1672 /// let metadata = std::fs::metadata("foo.txt")?;
1673 /// let filetype = metadata.file_type();
1675 /// if filetype.is_file() {
1678 /// # Ok::<_, std::io::Error>(())
1682 /// should be written as:
1686 /// let metadata = std::fs::metadata("foo.txt")?;
1687 /// let filetype = metadata.file_type();
1689 /// if !filetype.is_dir() {
1692 /// # Ok::<_, std::io::Error>(())
1695 #[clippy::version = "1.42.0"]
1696 pub FILETYPE_IS_FILE,
1698 "`FileType::is_file` is not recommended to test for readable file type"
1701 declare_clippy_lint! {
1702 /// ### What it does
1703 /// Checks for usage of `_.as_ref().map(Deref::deref)` or it's aliases (such as String::as_str).
1705 /// ### Why is this bad?
1706 /// Readability, this can be written more concisely as
1711 /// # let opt = Some("".to_string());
1712 /// opt.as_ref().map(String::as_str)
1715 /// Can be written as
1717 /// # let opt = Some("".to_string());
1721 #[clippy::version = "1.42.0"]
1722 pub OPTION_AS_REF_DEREF,
1724 "using `as_ref().map(Deref::deref)`, which is more succinctly expressed as `as_deref()`"
1727 declare_clippy_lint! {
1728 /// ### What it does
1729 /// Checks for usage of `iter().next()` on a Slice or an Array
1731 /// ### Why is this bad?
1732 /// These can be shortened into `.get()`
1736 /// # let a = [1, 2, 3];
1737 /// # let b = vec![1, 2, 3];
1738 /// a[2..].iter().next();
1739 /// b.iter().next();
1741 /// should be written as:
1743 /// # let a = [1, 2, 3];
1744 /// # let b = vec![1, 2, 3];
1748 #[clippy::version = "1.46.0"]
1749 pub ITER_NEXT_SLICE,
1751 "using `.iter().next()` on a sliced array, which can be shortened to just `.get()`"
1754 declare_clippy_lint! {
1755 /// ### What it does
1756 /// Warns when using `push_str`/`insert_str` with a single-character string literal
1757 /// where `push`/`insert` with a `char` would work fine.
1759 /// ### Why is this bad?
1760 /// It's less clear that we are pushing a single character.
1764 /// # let mut string = String::new();
1765 /// string.insert_str(0, "R");
1766 /// string.push_str("R");
1771 /// # let mut string = String::new();
1772 /// string.insert(0, 'R');
1773 /// string.push('R');
1775 #[clippy::version = "1.49.0"]
1776 pub SINGLE_CHAR_ADD_STR,
1778 "`push_str()` or `insert_str()` used with a single-character string literal as parameter"
1781 declare_clippy_lint! {
1782 /// ### What it does
1783 /// As the counterpart to `or_fun_call`, this lint looks for unnecessary
1784 /// lazily evaluated closures on `Option` and `Result`.
1786 /// This lint suggests changing the following functions, when eager evaluation results in
1788 /// - `unwrap_or_else` to `unwrap_or`
1789 /// - `and_then` to `and`
1790 /// - `or_else` to `or`
1791 /// - `get_or_insert_with` to `get_or_insert`
1792 /// - `ok_or_else` to `ok_or`
1794 /// ### Why is this bad?
1795 /// Using eager evaluation is shorter and simpler in some cases.
1797 /// ### Known problems
1798 /// It is possible, but not recommended for `Deref` and `Index` to have
1799 /// side effects. Eagerly evaluating them can change the semantics of the program.
1803 /// // example code where clippy issues a warning
1804 /// let opt: Option<u32> = None;
1806 /// opt.unwrap_or_else(|| 42);
1810 /// let opt: Option<u32> = None;
1812 /// opt.unwrap_or(42);
1814 #[clippy::version = "1.48.0"]
1815 pub UNNECESSARY_LAZY_EVALUATIONS,
1817 "using unnecessary lazy evaluation, which can be replaced with simpler eager evaluation"
1820 declare_clippy_lint! {
1821 /// ### What it does
1822 /// Checks for usage of `_.map(_).collect::<Result<(), _>()`.
1824 /// ### Why is this bad?
1825 /// Using `try_for_each` instead is more readable and idiomatic.
1829 /// (0..3).map(|t| Err(t)).collect::<Result<(), _>>();
1833 /// (0..3).try_for_each(|t| Err(t));
1835 #[clippy::version = "1.49.0"]
1836 pub MAP_COLLECT_RESULT_UNIT,
1838 "using `.map(_).collect::<Result<(),_>()`, which can be replaced with `try_for_each`"
1841 declare_clippy_lint! {
1842 /// ### What it does
1843 /// Checks for `from_iter()` function calls on types that implement the `FromIterator`
1846 /// ### Why is this bad?
1847 /// It is recommended style to use collect. See
1848 /// [FromIterator documentation](https://doc.rust-lang.org/std/iter/trait.FromIterator.html)
1852 /// let five_fives = std::iter::repeat(5).take(5);
1854 /// let v = Vec::from_iter(five_fives);
1856 /// assert_eq!(v, vec![5, 5, 5, 5, 5]);
1860 /// let five_fives = std::iter::repeat(5).take(5);
1862 /// let v: Vec<i32> = five_fives.collect();
1864 /// assert_eq!(v, vec![5, 5, 5, 5, 5]);
1866 #[clippy::version = "1.49.0"]
1867 pub FROM_ITER_INSTEAD_OF_COLLECT,
1869 "use `.collect()` instead of `::from_iter()`"
1872 declare_clippy_lint! {
1873 /// ### What it does
1874 /// Checks for usage of `inspect().for_each()`.
1876 /// ### Why is this bad?
1877 /// It is the same as performing the computation
1878 /// inside `inspect` at the beginning of the closure in `for_each`.
1882 /// [1,2,3,4,5].iter()
1883 /// .inspect(|&x| println!("inspect the number: {}", x))
1884 /// .for_each(|&x| {
1885 /// assert!(x >= 0);
1888 /// Can be written as
1890 /// [1,2,3,4,5].iter()
1891 /// .for_each(|&x| {
1892 /// println!("inspect the number: {}", x);
1893 /// assert!(x >= 0);
1896 #[clippy::version = "1.51.0"]
1897 pub INSPECT_FOR_EACH,
1899 "using `.inspect().for_each()`, which can be replaced with `.for_each()`"
1902 declare_clippy_lint! {
1903 /// ### What it does
1904 /// Checks for usage of `filter_map(|x| x)`.
1906 /// ### Why is this bad?
1907 /// Readability, this can be written more concisely by using `flatten`.
1911 /// # let iter = vec![Some(1)].into_iter();
1912 /// iter.filter_map(|x| x);
1916 /// # let iter = vec![Some(1)].into_iter();
1919 #[clippy::version = "1.52.0"]
1920 pub FILTER_MAP_IDENTITY,
1922 "call to `filter_map` where `flatten` is sufficient"
1925 declare_clippy_lint! {
1926 /// ### What it does
1927 /// Checks for instances of `map(f)` where `f` is the identity function.
1929 /// ### Why is this bad?
1930 /// It can be written more concisely without the call to `map`.
1934 /// let x = [1, 2, 3];
1935 /// let y: Vec<_> = x.iter().map(|x| x).map(|x| 2*x).collect();
1939 /// let x = [1, 2, 3];
1940 /// let y: Vec<_> = x.iter().map(|x| 2*x).collect();
1942 #[clippy::version = "1.47.0"]
1945 "using iterator.map(|x| x)"
1948 declare_clippy_lint! {
1949 /// ### What it does
1950 /// Checks for the use of `.bytes().nth()`.
1952 /// ### Why is this bad?
1953 /// `.as_bytes().get()` is more efficient and more
1958 /// # #[allow(unused)]
1959 /// "Hello".bytes().nth(3);
1964 /// # #[allow(unused)]
1965 /// "Hello".as_bytes().get(3);
1967 #[clippy::version = "1.52.0"]
1970 "replace `.bytes().nth()` with `.as_bytes().get()`"
1973 declare_clippy_lint! {
1974 /// ### What it does
1975 /// Checks for the usage of `_.to_owned()`, `vec.to_vec()`, or similar when calling `_.clone()` would be clearer.
1977 /// ### Why is this bad?
1978 /// These methods do the same thing as `_.clone()` but may be confusing as
1979 /// to why we are calling `to_vec` on something that is already a `Vec` or calling `to_owned` on something that is already owned.
1983 /// let a = vec![1, 2, 3];
1984 /// let b = a.to_vec();
1985 /// let c = a.to_owned();
1989 /// let a = vec![1, 2, 3];
1990 /// let b = a.clone();
1991 /// let c = a.clone();
1993 #[clippy::version = "1.52.0"]
1996 "implicitly cloning a value by invoking a function on its dereferenced type"
1999 declare_clippy_lint! {
2000 /// ### What it does
2001 /// Checks for the use of `.iter().count()`.
2003 /// ### Why is this bad?
2004 /// `.len()` is more efficient and more
2009 /// # #![allow(unused)]
2010 /// let some_vec = vec![0, 1, 2, 3];
2012 /// some_vec.iter().count();
2013 /// &some_vec[..].iter().count();
2018 /// let some_vec = vec![0, 1, 2, 3];
2021 /// &some_vec[..].len();
2023 #[clippy::version = "1.52.0"]
2026 "replace `.iter().count()` with `.len()`"
2029 declare_clippy_lint! {
2030 /// ### What it does
2031 /// Checks for calls to [`splitn`]
2032 /// (https://doc.rust-lang.org/std/primitive.str.html#method.splitn) and
2033 /// related functions with either zero or one splits.
2035 /// ### Why is this bad?
2036 /// These calls don't actually split the value and are
2037 /// likely to be intended as a different number.
2042 /// for x in s.splitn(1, ":") {
2050 /// for x in s.splitn(2, ":") {
2054 #[clippy::version = "1.54.0"]
2055 pub SUSPICIOUS_SPLITN,
2057 "checks for `.splitn(0, ..)` and `.splitn(1, ..)`"
2060 declare_clippy_lint! {
2061 /// ### What it does
2062 /// Checks for manual implementations of `str::repeat`
2064 /// ### Why is this bad?
2065 /// These are both harder to read, as well as less performant.
2069 /// let x: String = std::iter::repeat('x').take(10).collect();
2074 /// let x: String = "x".repeat(10);
2076 #[clippy::version = "1.54.0"]
2077 pub MANUAL_STR_REPEAT,
2079 "manual implementation of `str::repeat`"
2082 declare_clippy_lint! {
2083 /// ### What it does
2084 /// Checks for usages of `str::splitn(2, _)`
2086 /// ### Why is this bad?
2087 /// `split_once` is both clearer in intent and slightly more efficient.
2091 /// let s = "key=value=add";
2092 /// let (key, value) = s.splitn(2, '=').next_tuple()?;
2093 /// let value = s.splitn(2, '=').nth(1)?;
2095 /// let mut parts = s.splitn(2, '=');
2096 /// let key = parts.next()?;
2097 /// let value = parts.next()?;
2102 /// let s = "key=value=add";
2103 /// let (key, value) = s.split_once('=')?;
2104 /// let value = s.split_once('=')?.1;
2106 /// let (key, value) = s.split_once('=')?;
2110 /// The multiple statement variant currently only detects `iter.next()?`/`iter.next().unwrap()`
2111 /// in two separate `let` statements that immediately follow the `splitn()`
2112 #[clippy::version = "1.57.0"]
2113 pub MANUAL_SPLIT_ONCE,
2115 "replace `.splitn(2, pat)` with `.split_once(pat)`"
2118 declare_clippy_lint! {
2119 /// ### What it does
2120 /// Checks for usages of `str::splitn` (or `str::rsplitn`) where using `str::split` would be the same.
2121 /// ### Why is this bad?
2122 /// The function `split` is simpler and there is no performance difference in these cases, considering
2123 /// that both functions return a lazy iterator.
2126 /// let str = "key=value=add";
2127 /// let _ = str.splitn(3, '=').next().unwrap();
2132 /// let str = "key=value=add";
2133 /// let _ = str.split('=').next().unwrap();
2135 #[clippy::version = "1.59.0"]
2136 pub NEEDLESS_SPLITN,
2138 "usages of `str::splitn` that can be replaced with `str::split`"
2141 declare_clippy_lint! {
2142 /// ### What it does
2143 /// Checks for unnecessary calls to [`ToOwned::to_owned`](https://doc.rust-lang.org/std/borrow/trait.ToOwned.html#tymethod.to_owned)
2144 /// and other `to_owned`-like functions.
2146 /// ### Why is this bad?
2147 /// The unnecessary calls result in useless allocations.
2149 /// ### Known problems
2150 /// `unnecessary_to_owned` can falsely trigger if `IntoIterator::into_iter` is applied to an
2151 /// owned copy of a resource and the resource is later used mutably. See
2152 /// [#8148](https://github.com/rust-lang/rust-clippy/issues/8148).
2156 /// let path = std::path::Path::new("x");
2157 /// foo(&path.to_string_lossy().to_string());
2158 /// fn foo(s: &str) {}
2162 /// let path = std::path::Path::new("x");
2163 /// foo(&path.to_string_lossy());
2164 /// fn foo(s: &str) {}
2166 #[clippy::version = "1.59.0"]
2167 pub UNNECESSARY_TO_OWNED,
2169 "unnecessary calls to `to_owned`-like functions"
2172 declare_clippy_lint! {
2173 /// ### What it does
2174 /// Checks for use of `.collect::<Vec<String>>().join("")` on iterators.
2176 /// ### Why is this bad?
2177 /// `.collect::<String>()` is more concise and might be more performant
2181 /// let vector = vec!["hello", "world"];
2182 /// let output = vector.iter().map(|item| item.to_uppercase()).collect::<Vec<String>>().join("");
2183 /// println!("{}", output);
2185 /// The correct use would be:
2187 /// let vector = vec!["hello", "world"];
2188 /// let output = vector.iter().map(|item| item.to_uppercase()).collect::<String>();
2189 /// println!("{}", output);
2191 /// ### Known problems
2192 /// While `.collect::<String>()` is sometimes more performant, there are cases where
2193 /// using `.collect::<String>()` over `.collect::<Vec<String>>().join("")`
2194 /// will prevent loop unrolling and will result in a negative performance impact.
2196 /// Additionally, differences have been observed between aarch64 and x86_64 assembly output,
2197 /// with aarch64 tending to producing faster assembly in more cases when using `.collect::<String>()`
2198 #[clippy::version = "1.61.0"]
2199 pub UNNECESSARY_JOIN,
2201 "using `.collect::<Vec<String>>().join(\"\")` on an iterator"
2204 declare_clippy_lint! {
2205 /// ### What it does
2206 /// Checks for no-op uses of `Option::{as_deref, as_deref_mut}`,
2207 /// for example, `Option<&T>::as_deref()` returns the same type.
2209 /// ### Why is this bad?
2210 /// Redundant code and improving readability.
2214 /// let a = Some(&1);
2215 /// let b = a.as_deref(); // goes from Option<&i32> to Option<&i32>
2220 /// let a = Some(&1);
2223 #[clippy::version = "1.57.0"]
2224 pub NEEDLESS_OPTION_AS_DEREF,
2226 "no-op use of `deref` or `deref_mut` method to `Option`."
2229 declare_clippy_lint! {
2230 /// ### What it does
2231 /// Finds usages of [`char::is_digit`](https://doc.rust-lang.org/stable/std/primitive.char.html#method.is_digit) that
2232 /// can be replaced with [`is_ascii_digit`](https://doc.rust-lang.org/stable/std/primitive.char.html#method.is_ascii_digit) or
2233 /// [`is_ascii_hexdigit`](https://doc.rust-lang.org/stable/std/primitive.char.html#method.is_ascii_hexdigit).
2235 /// ### Why is this bad?
2236 /// `is_digit(..)` is slower and requires specifying the radix.
2240 /// let c: char = '6';
2246 /// let c: char = '6';
2247 /// c.is_ascii_digit();
2248 /// c.is_ascii_hexdigit();
2250 #[clippy::version = "1.62.0"]
2251 pub IS_DIGIT_ASCII_RADIX,
2253 "use of `char::is_digit(..)` with literal radix of 10 or 16"
2256 declare_clippy_lint! {
2257 /// ### What it does
2258 /// Checks for calling `take` function after `as_ref`.
2260 /// ### Why is this bad?
2261 /// Redundant code. `take` writes `None` to its argument.
2262 /// In this case the modification is useless as it's a temporary that cannot be read from afterwards.
2266 /// let x = Some(3);
2267 /// x.as_ref().take();
2271 /// let x = Some(3);
2274 #[clippy::version = "1.62.0"]
2275 pub NEEDLESS_OPTION_TAKE,
2277 "using `.as_ref().take()` on a temporary value"
2280 declare_clippy_lint! {
2281 /// ### What it does
2282 /// Checks for `replace` statements which have no effect.
2284 /// ### Why is this bad?
2285 /// It's either a mistake or confusing.
2289 /// "1234".replace("12", "12");
2290 /// "1234".replacen("12", "12", 1);
2292 #[clippy::version = "1.63.0"]
2293 pub NO_EFFECT_REPLACE,
2295 "replace with no effect"
2298 declare_clippy_lint! {
2299 /// ### What it does
2300 /// Checks for usages of `.then_some(..).unwrap_or(..)`
2302 /// ### Why is this bad?
2303 /// This can be written more clearly with `if .. else ..`
2306 /// This lint currently only looks for usages of
2307 /// `.then_some(..).unwrap_or(..)`, but will be expanded
2308 /// to account for similar patterns.
2313 /// x.then_some("a").unwrap_or("b");
2318 /// if x { "a" } else { "b" };
2320 #[clippy::version = "1.64.0"]
2321 pub OBFUSCATED_IF_ELSE,
2323 "use of `.then_some(..).unwrap_or(..)` can be written \
2324 more clearly with `if .. else ..`"
2327 declare_clippy_lint! {
2328 /// ### What it does
2330 /// Checks for calls to `iter`, `iter_mut` or `into_iter` on collections containing a single item
2332 /// ### Why is this bad?
2334 /// It is simpler to use the once function from the standard library:
2339 /// let a = [123].iter();
2340 /// let b = Some(123).into_iter();
2345 /// let a = iter::once(&123);
2346 /// let b = iter::once(123);
2349 /// ### Known problems
2351 /// The type of the resulting iterator might become incompatible with its usage
2352 #[clippy::version = "1.64.0"]
2353 pub ITER_ON_SINGLE_ITEMS,
2355 "Iterator for array of length 1"
2358 declare_clippy_lint! {
2359 /// ### What it does
2361 /// Checks for calls to `iter`, `iter_mut` or `into_iter` on empty collections
2363 /// ### Why is this bad?
2365 /// It is simpler to use the empty function from the standard library:
2370 /// use std::{slice, option};
2371 /// let a: slice::Iter<i32> = [].iter();
2372 /// let f: option::IntoIter<i32> = None.into_iter();
2377 /// let a: iter::Empty<i32> = iter::empty();
2378 /// let b: iter::Empty<i32> = iter::empty();
2381 /// ### Known problems
2383 /// The type of the resulting iterator might become incompatible with its usage
2384 #[clippy::version = "1.64.0"]
2385 pub ITER_ON_EMPTY_COLLECTIONS,
2387 "Iterator for empty array"
2390 declare_clippy_lint! {
2391 /// ### What it does
2392 /// Checks for naive byte counts
2394 /// ### Why is this bad?
2395 /// The [`bytecount`](https://crates.io/crates/bytecount)
2396 /// crate has methods to count your bytes faster, especially for large slices.
2398 /// ### Known problems
2399 /// If you have predominantly small slices, the
2400 /// `bytecount::count(..)` method may actually be slower. However, if you can
2401 /// ensure that less than 2³²-1 matches arise, the `naive_count_32(..)` can be
2402 /// faster in those cases.
2406 /// # let vec = vec![1_u8];
2407 /// let count = vec.iter().filter(|x| **x == 0u8).count();
2412 /// # let vec = vec![1_u8];
2413 /// let count = bytecount::count(&vec, 0u8);
2415 #[clippy::version = "pre 1.29.0"]
2416 pub NAIVE_BYTECOUNT,
2418 "use of naive `<slice>.filter(|&x| x == y).count()` to count byte values"
2421 declare_clippy_lint! {
2422 /// ### What it does
2423 /// It checks for `str::bytes().count()` and suggests replacing it with
2426 /// ### Why is this bad?
2427 /// `str::bytes().count()` is longer and may not be as performant as using
2432 /// "hello".bytes().count();
2433 /// String::from("hello").bytes().count();
2438 /// String::from("hello").len();
2440 #[clippy::version = "1.62.0"]
2441 pub BYTES_COUNT_TO_LEN,
2443 "Using `bytes().count()` when `len()` performs the same functionality"
2446 declare_clippy_lint! {
2447 /// ### What it does
2448 /// Checks for calls to `ends_with` with possible file extensions
2449 /// and suggests to use a case-insensitive approach instead.
2451 /// ### Why is this bad?
2452 /// `ends_with` is case-sensitive and may not detect files with a valid extension.
2456 /// fn is_rust_file(filename: &str) -> bool {
2457 /// filename.ends_with(".rs")
2462 /// fn is_rust_file(filename: &str) -> bool {
2463 /// let filename = std::path::Path::new(filename);
2464 /// filename.extension()
2465 /// .map_or(false, |ext| ext.eq_ignore_ascii_case("rs"))
2468 #[clippy::version = "1.51.0"]
2469 pub CASE_SENSITIVE_FILE_EXTENSION_COMPARISONS,
2471 "Checks for calls to ends_with with case-sensitive file extensions"
2474 declare_clippy_lint! {
2475 /// ### What it does
2476 /// Checks for using `x.get(0)` instead of
2479 /// ### Why is this bad?
2480 /// Using `x.first()` is easier to read and has the same
2485 /// let x = vec![2, 3, 5];
2486 /// let first_element = x.get(0);
2491 /// let x = vec![2, 3, 5];
2492 /// let first_element = x.first();
2494 #[clippy::version = "1.63.0"]
2497 "Using `x.get(0)` when `x.first()` is simpler"
2500 declare_clippy_lint! {
2501 /// ### What it does
2503 /// Finds patterns that reimplement `Option::ok_or`.
2505 /// ### Why is this bad?
2507 /// Concise code helps focusing on behavior instead of boilerplate.
2511 /// let foo: Option<i32> = None;
2512 /// foo.map_or(Err("error"), |v| Ok(v));
2517 /// let foo: Option<i32> = None;
2518 /// foo.ok_or("error");
2520 #[clippy::version = "1.49.0"]
2523 "finds patterns that can be encoded more concisely with `Option::ok_or`"
2526 declare_clippy_lint! {
2527 /// ### What it does
2528 /// Checks for usage of `map(|x| x.clone())` or
2529 /// dereferencing closures for `Copy` types, on `Iterator` or `Option`,
2530 /// and suggests `cloned()` or `copied()` instead
2532 /// ### Why is this bad?
2533 /// Readability, this can be written more concisely
2537 /// let x = vec![42, 43];
2538 /// let y = x.iter();
2539 /// let z = y.map(|i| *i);
2542 /// The correct use would be:
2545 /// let x = vec![42, 43];
2546 /// let y = x.iter();
2547 /// let z = y.cloned();
2549 #[clippy::version = "pre 1.29.0"]
2552 "using `iterator.map(|x| x.clone())`, or dereferencing closures for `Copy` types"
2555 declare_clippy_lint! {
2556 /// ### What it does
2557 /// Checks for instances of `map_err(|_| Some::Enum)`
2559 /// ### Why is this bad?
2560 /// This `map_err` throws away the original error rather than allowing the enum to contain and report the cause of the error
2567 /// #[derive(Debug)]
2573 /// impl fmt::Display for Error {
2574 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2576 /// Error::Indivisible => write!(f, "could not divide input by three"),
2577 /// Error::Remainder(remainder) => write!(
2579 /// "input is not divisible by three, remainder = {}",
2586 /// impl std::error::Error for Error {}
2588 /// fn divisible_by_3(input: &str) -> Result<(), Error> {
2591 /// .map_err(|_| Error::Indivisible)
2593 /// .and_then(|remainder| {
2594 /// if remainder == 0 {
2597 /// Err(Error::Remainder(remainder as u8))
2605 /// use std::{fmt, num::ParseIntError};
2607 /// #[derive(Debug)]
2609 /// Indivisible(ParseIntError),
2613 /// impl fmt::Display for Error {
2614 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2616 /// Error::Indivisible(_) => write!(f, "could not divide input by three"),
2617 /// Error::Remainder(remainder) => write!(
2619 /// "input is not divisible by three, remainder = {}",
2626 /// impl std::error::Error for Error {
2627 /// fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
2629 /// Error::Indivisible(source) => Some(source),
2635 /// fn divisible_by_3(input: &str) -> Result<(), Error> {
2638 /// .map_err(Error::Indivisible)
2640 /// .and_then(|remainder| {
2641 /// if remainder == 0 {
2644 /// Err(Error::Remainder(remainder as u8))
2649 #[clippy::version = "1.48.0"]
2652 "`map_err` should not ignore the original error"
2655 declare_clippy_lint! {
2656 /// ### What it does
2657 /// Checks for `&mut Mutex::lock` calls
2659 /// ### Why is this bad?
2660 /// `Mutex::lock` is less efficient than
2661 /// calling `Mutex::get_mut`. In addition you also have a statically
2662 /// guarantee that the mutex isn't locked, instead of just a runtime
2667 /// use std::sync::{Arc, Mutex};
2669 /// let mut value_rc = Arc::new(Mutex::new(42_u8));
2670 /// let value_mutex = Arc::get_mut(&mut value_rc).unwrap();
2672 /// let mut value = value_mutex.lock().unwrap();
2677 /// use std::sync::{Arc, Mutex};
2679 /// let mut value_rc = Arc::new(Mutex::new(42_u8));
2680 /// let value_mutex = Arc::get_mut(&mut value_rc).unwrap();
2682 /// let value = value_mutex.get_mut().unwrap();
2685 #[clippy::version = "1.49.0"]
2688 "`&mut Mutex::lock` does unnecessary locking"
2691 declare_clippy_lint! {
2692 /// ### What it does
2693 /// Checks for duplicate open options as well as combinations
2694 /// that make no sense.
2696 /// ### Why is this bad?
2697 /// In the best case, the code will be harder to read than
2698 /// necessary. I don't know the worst case.
2702 /// use std::fs::OpenOptions;
2704 /// OpenOptions::new().read(true).truncate(true);
2706 #[clippy::version = "pre 1.29.0"]
2707 pub NONSENSICAL_OPEN_OPTIONS,
2709 "nonsensical combination of options for opening a file"
2712 declare_clippy_lint! {
2713 /// ### What it does
2714 ///* Checks for [push](https://doc.rust-lang.org/std/path/struct.PathBuf.html#method.push)
2715 /// calls on `PathBuf` that can cause overwrites.
2717 /// ### Why is this bad?
2718 /// Calling `push` with a root path at the start can overwrite the
2719 /// previous defined path.
2723 /// use std::path::PathBuf;
2725 /// let mut x = PathBuf::from("/foo");
2727 /// assert_eq!(x, PathBuf::from("/bar"));
2729 /// Could be written:
2732 /// use std::path::PathBuf;
2734 /// let mut x = PathBuf::from("/foo");
2736 /// assert_eq!(x, PathBuf::from("/foo/bar"));
2738 #[clippy::version = "1.36.0"]
2739 pub PATH_BUF_PUSH_OVERWRITE,
2741 "calling `push` with file system root on `PathBuf` can overwrite it"
2744 declare_clippy_lint! {
2745 /// ### What it does
2746 /// Checks for zipping a collection with the range of
2749 /// ### Why is this bad?
2750 /// The code is better expressed with `.enumerate()`.
2754 /// # let x = vec![1];
2755 /// let _ = x.iter().zip(0..x.len());
2760 /// # let x = vec![1];
2761 /// let _ = x.iter().enumerate();
2763 #[clippy::version = "pre 1.29.0"]
2764 pub RANGE_ZIP_WITH_LEN,
2766 "zipping iterator with a range when `enumerate()` would do"
2769 declare_clippy_lint! {
2770 /// ### What it does
2771 /// Checks for usage of `.repeat(1)` and suggest the following method for each types.
2772 /// - `.to_string()` for `str`
2773 /// - `.clone()` for `String`
2774 /// - `.to_vec()` for `slice`
2776 /// The lint will evaluate constant expressions and values as arguments of `.repeat(..)` and emit a message if
2777 /// they are equivalent to `1`. (Related discussion in [rust-clippy#7306](https://github.com/rust-lang/rust-clippy/issues/7306))
2779 /// ### Why is this bad?
2780 /// For example, `String.repeat(1)` is equivalent to `.clone()`. If cloning
2781 /// the string is the intention behind this, `clone()` should be used.
2786 /// let x = String::from("hello world").repeat(1);
2792 /// let x = String::from("hello world").clone();
2795 #[clippy::version = "1.47.0"]
2798 "using `.repeat(1)` instead of `String.clone()`, `str.to_string()` or `slice.to_vec()` "
2801 declare_clippy_lint! {
2802 /// ### What it does
2803 /// When sorting primitive values (integers, bools, chars, as well
2804 /// as arrays, slices, and tuples of such items), it is typically better to
2805 /// use an unstable sort than a stable sort.
2807 /// ### Why is this bad?
2808 /// Typically, using a stable sort consumes more memory and cpu cycles.
2809 /// Because values which compare equal are identical, preserving their
2810 /// relative order (the guarantee that a stable sort provides) means
2811 /// nothing, while the extra costs still apply.
2813 /// ### Known problems
2815 /// As pointed out in
2816 /// [issue #8241](https://github.com/rust-lang/rust-clippy/issues/8241),
2817 /// a stable sort can instead be significantly faster for certain scenarios
2818 /// (eg. when a sorted vector is extended with new data and resorted).
2820 /// For more information and benchmarking results, please refer to the
2821 /// issue linked above.
2825 /// let mut vec = vec![2, 1, 3];
2830 /// let mut vec = vec![2, 1, 3];
2831 /// vec.sort_unstable();
2833 #[clippy::version = "1.47.0"]
2834 pub STABLE_SORT_PRIMITIVE,
2836 "use of sort() when sort_unstable() is equivalent"
2839 declare_clippy_lint! {
2840 /// ### What it does
2841 /// Detects `().hash(_)`.
2843 /// ### Why is this bad?
2844 /// Hashing a unit value doesn't do anything as the implementation of `Hash` for `()` is a no-op.
2848 /// # use std::hash::Hash;
2849 /// # use std::collections::hash_map::DefaultHasher;
2850 /// # enum Foo { Empty, WithValue(u8) }
2852 /// # let mut state = DefaultHasher::new();
2853 /// # let my_enum = Foo::Empty;
2855 /// Empty => ().hash(&mut state),
2856 /// WithValue(x) => x.hash(&mut state),
2861 /// # use std::hash::Hash;
2862 /// # use std::collections::hash_map::DefaultHasher;
2863 /// # enum Foo { Empty, WithValue(u8) }
2865 /// # let mut state = DefaultHasher::new();
2866 /// # let my_enum = Foo::Empty;
2868 /// Empty => 0_u8.hash(&mut state),
2869 /// WithValue(x) => x.hash(&mut state),
2872 #[clippy::version = "1.58.0"]
2875 "hashing a unit value, which does nothing"
2878 declare_clippy_lint! {
2879 /// ### What it does
2880 /// Detects uses of `Vec::sort_by` passing in a closure
2881 /// which compares the two arguments, either directly or indirectly.
2883 /// ### Why is this bad?
2884 /// It is more clear to use `Vec::sort_by_key` (or `Vec::sort` if
2885 /// possible) than to use `Vec::sort_by` and a more complicated
2888 /// ### Known problems
2889 /// If the suggested `Vec::sort_by_key` uses Reverse and it isn't already
2890 /// imported by a use statement, then it will need to be added manually.
2895 /// # impl A { fn foo(&self) {} }
2896 /// # let mut vec: Vec<A> = Vec::new();
2897 /// vec.sort_by(|a, b| a.foo().cmp(&b.foo()));
2902 /// # impl A { fn foo(&self) {} }
2903 /// # let mut vec: Vec<A> = Vec::new();
2904 /// vec.sort_by_key(|a| a.foo());
2906 #[clippy::version = "1.46.0"]
2907 pub UNNECESSARY_SORT_BY,
2909 "Use of `Vec::sort_by` when `Vec::sort_by_key` or `Vec::sort` would be clearer"
2912 declare_clippy_lint! {
2913 /// ### What it does
2914 /// Finds occurrences of `Vec::resize(0, an_int)`
2916 /// ### Why is this bad?
2917 /// This is probably an argument inversion mistake.
2921 /// vec!(1, 2, 3, 4, 5).resize(0, 5)
2926 /// vec!(1, 2, 3, 4, 5).clear()
2928 #[clippy::version = "1.46.0"]
2929 pub VEC_RESIZE_TO_ZERO,
2931 "emptying a vector with `resize(0, an_int)` instead of `clear()` is probably an argument inversion mistake"
2934 declare_clippy_lint! {
2935 /// ### What it does
2936 /// Checks for use of File::read_to_end and File::read_to_string.
2938 /// ### Why is this bad?
2939 /// `fs::{read, read_to_string}` provide the same functionality when `buf` is empty with fewer imports and no intermediate values.
2940 /// See also: [fs::read docs](https://doc.rust-lang.org/std/fs/fn.read.html), [fs::read_to_string docs](https://doc.rust-lang.org/std/fs/fn.read_to_string.html)
2944 /// # use std::io::Read;
2945 /// # use std::fs::File;
2946 /// let mut f = File::open("foo.txt").unwrap();
2947 /// let mut bytes = Vec::new();
2948 /// f.read_to_end(&mut bytes).unwrap();
2950 /// Can be written more concisely as
2953 /// let mut bytes = fs::read("foo.txt").unwrap();
2955 #[clippy::version = "1.44.0"]
2956 pub VERBOSE_FILE_READS,
2958 "use of `File::read_to_end` or `File::read_to_string`"
2961 pub struct Methods {
2962 avoid_breaking_exported_api: bool,
2963 msrv: Option<RustcVersion>,
2964 allow_expect_in_tests: bool,
2965 allow_unwrap_in_tests: bool,
2971 avoid_breaking_exported_api: bool,
2972 msrv: Option<RustcVersion>,
2973 allow_expect_in_tests: bool,
2974 allow_unwrap_in_tests: bool,
2977 avoid_breaking_exported_api,
2979 allow_expect_in_tests,
2980 allow_unwrap_in_tests,
2985 impl_lint_pass!(Methods => [
2988 SHOULD_IMPLEMENT_TRAIT,
2989 WRONG_SELF_CONVENTION,
2991 UNWRAP_OR_ELSE_DEFAULT,
2993 RESULT_MAP_OR_INTO_OPTION,
2995 BIND_INSTEAD_OF_MAP,
3004 ITER_OVEREAGER_CLONED,
3005 CLONED_INSTEAD_OF_COPIED,
3007 INEFFICIENT_TO_STRING,
3009 SINGLE_CHAR_PATTERN,
3010 SINGLE_CHAR_ADD_STR,
3014 FILTER_MAP_IDENTITY,
3022 ITERATOR_STEP_BY_ZERO,
3031 STRING_EXTEND_CHARS,
3032 ITER_CLONED_COLLECT,
3036 UNNECESSARY_FILTER_MAP,
3037 UNNECESSARY_FIND_MAP,
3040 UNINIT_ASSUMED_INIT,
3041 MANUAL_SATURATING_ARITHMETIC,
3044 OPTION_AS_REF_DEREF,
3045 UNNECESSARY_LAZY_EVALUATIONS,
3046 MAP_COLLECT_RESULT_UNIT,
3047 FROM_ITER_INSTEAD_OF_COLLECT,
3055 UNNECESSARY_TO_OWNED,
3058 NEEDLESS_OPTION_AS_DEREF,
3059 IS_DIGIT_ASCII_RADIX,
3060 NEEDLESS_OPTION_TAKE,
3063 ITER_ON_SINGLE_ITEMS,
3064 ITER_ON_EMPTY_COLLECTIONS,
3067 CASE_SENSITIVE_FILE_EXTENSION_COMPARISONS,
3073 NONSENSICAL_OPEN_OPTIONS,
3074 PATH_BUF_PUSH_OVERWRITE,
3077 STABLE_SORT_PRIMITIVE,
3079 UNNECESSARY_SORT_BY,
3084 /// Extracts a method call name, args, and `Span` of the method name.
3085 fn method_call<'tcx>(recv: &'tcx hir::Expr<'tcx>) -> Option<(&'tcx str, &'tcx [hir::Expr<'tcx>], Span)> {
3086 if let ExprKind::MethodCall(path, args, _) = recv.kind {
3087 if !args.iter().any(|e| e.span.from_expansion()) {
3088 let name = path.ident.name.as_str();
3089 return Some((name, args, path.ident.span));
3095 impl<'tcx> LateLintPass<'tcx> for Methods {
3096 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) {
3097 if expr.span.from_expansion() {
3101 self.check_methods(cx, expr);
3104 hir::ExprKind::Call(func, args) => {
3105 from_iter_instead_of_collect::check(cx, expr, args, func);
3107 hir::ExprKind::MethodCall(method_call, args, _) => {
3108 let method_span = method_call.ident.span;
3109 or_fun_call::check(cx, expr, method_span, method_call.ident.as_str(), args);
3110 expect_fun_call::check(cx, expr, method_span, method_call.ident.as_str(), args);
3111 clone_on_copy::check(cx, expr, method_call.ident.name, args);
3112 clone_on_ref_ptr::check(cx, expr, method_call.ident.name, args);
3113 inefficient_to_string::check(cx, expr, method_call.ident.name, args);
3114 single_char_add_str::check(cx, expr, args);
3115 into_iter_on_ref::check(cx, expr, method_span, method_call.ident.name, args);
3116 single_char_pattern::check(cx, expr, method_call.ident.name, args);
3117 unnecessary_to_owned::check(cx, expr, method_call.ident.name, args, self.msrv);
3119 hir::ExprKind::Binary(op, lhs, rhs) if op.node == hir::BinOpKind::Eq || op.node == hir::BinOpKind::Ne => {
3120 let mut info = BinaryExprInfo {
3124 eq: op.node == hir::BinOpKind::Eq,
3126 lint_binary_expr_with_method_call(cx, &mut info);
3132 #[allow(clippy::too_many_lines)]
3133 fn check_impl_item(&mut self, cx: &LateContext<'tcx>, impl_item: &'tcx hir::ImplItem<'_>) {
3134 if in_external_macro(cx.sess(), impl_item.span) {
3137 let name = impl_item.ident.name.as_str();
3138 let parent = cx.tcx.hir().get_parent_item(impl_item.hir_id());
3139 let item = cx.tcx.hir().expect_item(parent);
3140 let self_ty = cx.tcx.type_of(item.def_id);
3142 let implements_trait = matches!(item.kind, hir::ItemKind::Impl(hir::Impl { of_trait: Some(_), .. }));
3144 if let hir::ImplItemKind::Fn(ref sig, id) = impl_item.kind;
3145 if let Some(first_arg) = iter_input_pats(sig.decl, cx.tcx.hir().body(id)).next();
3147 let method_sig = cx.tcx.fn_sig(impl_item.def_id);
3148 let method_sig = cx.tcx.erase_late_bound_regions(method_sig);
3150 let first_arg_ty = method_sig.inputs().iter().next();
3152 // check conventions w.r.t. conversion method names and predicates
3153 if let Some(first_arg_ty) = first_arg_ty;
3156 // if this impl block implements a trait, lint in trait definition instead
3157 if !implements_trait && cx.access_levels.is_exported(impl_item.def_id) {
3158 // check missing trait implementations
3159 for method_config in &TRAIT_METHODS {
3160 if name == method_config.method_name &&
3161 sig.decl.inputs.len() == method_config.param_count &&
3162 method_config.output_type.matches(&sig.decl.output) &&
3163 method_config.self_kind.matches(cx, self_ty, *first_arg_ty) &&
3164 fn_header_equals(method_config.fn_header, sig.header) &&
3165 method_config.lifetime_param_cond(impl_item)
3169 SHOULD_IMPLEMENT_TRAIT,
3172 "method `{}` can be confused for the standard trait method `{}::{}`",
3173 method_config.method_name,
3174 method_config.trait_name,
3175 method_config.method_name
3179 "consider implementing the trait `{}` or choosing a less ambiguous method name",
3180 method_config.trait_name
3187 if sig.decl.implicit_self.has_implicit_self()
3188 && !(self.avoid_breaking_exported_api
3189 && cx.access_levels.is_exported(impl_item.def_id))
3191 wrong_self_convention::check(
3204 // if this impl block implements a trait, lint in trait definition instead
3205 if implements_trait {
3209 if let hir::ImplItemKind::Fn(_, _) = impl_item.kind {
3210 let ret_ty = return_ty(cx, impl_item.hir_id());
3212 // walk the return type and check for Self (this does not check associated types)
3213 if let Some(self_adt) = self_ty.ty_adt_def() {
3214 if contains_adt_constructor(ret_ty, self_adt) {
3217 } else if contains_ty(ret_ty, self_ty) {
3221 // if return type is impl trait, check the associated types
3222 if let ty::Opaque(def_id, _) = *ret_ty.kind() {
3223 // one of the associated types must be Self
3224 for &(predicate, _span) in cx.tcx.explicit_item_bounds(def_id) {
3225 if let ty::PredicateKind::Projection(projection_predicate) = predicate.kind().skip_binder() {
3226 let assoc_ty = match projection_predicate.term {
3227 ty::Term::Ty(ty) => ty,
3228 ty::Term::Const(_c) => continue,
3230 // walk the associated type and check for Self
3231 if let Some(self_adt) = self_ty.ty_adt_def() {
3232 if contains_adt_constructor(assoc_ty, self_adt) {
3235 } else if contains_ty(assoc_ty, self_ty) {
3242 if name == "new" && ret_ty != self_ty {
3247 "methods called `new` usually return `Self`",
3253 fn check_trait_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx TraitItem<'_>) {
3254 if in_external_macro(cx.tcx.sess, item.span) {
3259 if let TraitItemKind::Fn(ref sig, _) = item.kind;
3260 if sig.decl.implicit_self.has_implicit_self();
3261 if let Some(first_arg_ty) = sig.decl.inputs.iter().next();
3264 let first_arg_span = first_arg_ty.span;
3265 let first_arg_ty = hir_ty_to_ty(cx.tcx, first_arg_ty);
3266 let self_ty = TraitRef::identity(cx.tcx, item.def_id.to_def_id()).self_ty().skip_binder();
3267 wrong_self_convention::check(
3269 item.ident.name.as_str(),
3280 if item.ident.name == sym::new;
3281 if let TraitItemKind::Fn(_, _) = item.kind;
3282 let ret_ty = return_ty(cx, item.hir_id());
3283 let self_ty = TraitRef::identity(cx.tcx, item.def_id.to_def_id()).self_ty().skip_binder();
3284 if !contains_ty(ret_ty, self_ty);
3291 "methods called `new` usually return `Self`",
3297 extract_msrv_attr!(LateContext);
3301 #[allow(clippy::too_many_lines)]
3302 fn check_methods<'tcx>(&self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
3303 if let Some((name, [recv, args @ ..], span)) = method_call(expr) {
3304 match (name, args) {
3305 ("add" | "offset" | "sub" | "wrapping_offset" | "wrapping_add" | "wrapping_sub", [_arg]) => {
3306 zst_offset::check(cx, expr, recv);
3308 ("and_then", [arg]) => {
3309 let biom_option_linted = bind_instead_of_map::OptionAndThenSome::check(cx, expr, recv, arg);
3310 let biom_result_linted = bind_instead_of_map::ResultAndThenOk::check(cx, expr, recv, arg);
3311 if !biom_option_linted && !biom_result_linted {
3312 unnecessary_lazy_eval::check(cx, expr, recv, arg, "and");
3315 ("as_deref" | "as_deref_mut", []) => {
3316 needless_option_as_deref::check(cx, expr, recv, name);
3318 ("as_mut", []) => useless_asref::check(cx, expr, "as_mut", recv),
3319 ("as_ref", []) => useless_asref::check(cx, expr, "as_ref", recv),
3320 ("assume_init", []) => uninit_assumed_init::check(cx, expr, recv),
3321 ("cloned", []) => cloned_instead_of_copied::check(cx, expr, recv, span, self.msrv),
3322 ("collect", []) => match method_call(recv) {
3323 Some((name @ ("cloned" | "copied"), [recv2], _)) => {
3324 iter_cloned_collect::check(cx, name, expr, recv2);
3326 Some(("map", [m_recv, m_arg], _)) => {
3327 map_collect_result_unit::check(cx, expr, m_recv, m_arg, recv);
3329 Some(("take", [take_self_arg, take_arg], _)) => {
3330 if meets_msrv(self.msrv, msrvs::STR_REPEAT) {
3331 manual_str_repeat::check(cx, expr, recv, take_self_arg, take_arg);
3336 ("count", []) if is_trait_method(cx, expr, sym::Iterator) => match method_call(recv) {
3337 Some(("cloned", [recv2], _)) => iter_overeager_cloned::check(cx, expr, recv, recv2, true, false),
3338 Some((name2 @ ("into_iter" | "iter" | "iter_mut"), [recv2], _)) => {
3339 iter_count::check(cx, expr, recv2, name2);
3341 Some(("map", [_, arg], _)) => suspicious_map::check(cx, expr, recv, arg),
3342 Some(("filter", [recv2, arg], _)) => bytecount::check(cx, expr, recv2, arg),
3343 Some(("bytes", [recv2], _)) => bytes_count_to_len::check(cx, expr, recv, recv2),
3346 ("drain", [arg]) => {
3347 iter_with_drain::check(cx, expr, recv, span, arg);
3349 ("ends_with", [arg]) => {
3350 if let ExprKind::MethodCall(_, _, span) = expr.kind {
3351 case_sensitive_file_extension_comparisons::check(cx, expr, span, recv, arg);
3354 ("expect", [_]) => match method_call(recv) {
3355 Some(("ok", [recv], _)) => ok_expect::check(cx, expr, recv),
3356 Some(("err", [recv], err_span)) => err_expect::check(cx, expr, recv, self.msrv, span, err_span),
3357 _ => expect_used::check(cx, expr, recv, false, self.allow_expect_in_tests),
3359 ("expect_err", [_]) => expect_used::check(cx, expr, recv, true, self.allow_expect_in_tests),
3360 ("extend", [arg]) => {
3361 string_extend_chars::check(cx, expr, recv, arg);
3362 extend_with_drain::check(cx, expr, recv, arg);
3364 ("filter_map", [arg]) => {
3365 unnecessary_filter_map::check(cx, expr, arg, name);
3366 filter_map_identity::check(cx, expr, arg, span);
3368 ("find_map", [arg]) => {
3369 unnecessary_filter_map::check(cx, expr, arg, name);
3371 ("flat_map", [arg]) => {
3372 flat_map_identity::check(cx, expr, arg, span);
3373 flat_map_option::check(cx, expr, arg, span);
3375 ("flatten", []) => match method_call(recv) {
3376 Some(("map", [recv, map_arg], map_span)) => map_flatten::check(cx, expr, recv, map_arg, map_span),
3377 Some(("cloned", [recv2], _)) => iter_overeager_cloned::check(cx, expr, recv, recv2, false, true),
3380 ("fold", [init, acc]) => unnecessary_fold::check(cx, expr, init, acc, span),
3381 ("for_each", [_]) => {
3382 if let Some(("inspect", [_, _], span2)) = method_call(recv) {
3383 inspect_for_each::check(cx, expr, span2);
3387 get_first::check(cx, expr, recv, arg);
3388 get_last_with_len::check(cx, expr, recv, arg);
3390 ("get_or_insert_with", [arg]) => unnecessary_lazy_eval::check(cx, expr, recv, arg, "get_or_insert"),
3391 ("hash", [arg]) => {
3392 unit_hash::check(cx, expr, recv, arg);
3394 ("is_file", []) => filetype_is_file::check(cx, expr, recv),
3395 ("is_digit", [radix]) => is_digit_ascii_radix::check(cx, expr, recv, radix, self.msrv),
3396 ("is_none", []) => check_is_some_is_none(cx, expr, recv, false),
3397 ("is_some", []) => check_is_some_is_none(cx, expr, recv, true),
3398 ("iter" | "iter_mut" | "into_iter", []) => {
3399 iter_on_single_or_empty_collections::check(cx, expr, name, recv);
3401 ("join", [join_arg]) => {
3402 if let Some(("collect", _, span)) = method_call(recv) {
3403 unnecessary_join::check(cx, expr, recv, join_arg, span);
3406 ("last", []) | ("skip", [_]) => {
3407 if let Some((name2, [recv2, args2 @ ..], _span2)) = method_call(recv) {
3408 if let ("cloned", []) = (name2, args2) {
3409 iter_overeager_cloned::check(cx, expr, recv, recv2, false, false);
3414 mut_mutex_lock::check(cx, expr, recv, span);
3416 (name @ ("map" | "map_err"), [m_arg]) => {
3418 map_clone::check(cx, expr, recv, m_arg, self.msrv);
3420 map_err_ignore::check(cx, expr, m_arg);
3422 if let Some((name, [recv2, args @ ..], span2)) = method_call(recv) {
3423 match (name, args) {
3424 ("as_mut", []) => option_as_ref_deref::check(cx, expr, recv2, m_arg, true, self.msrv),
3425 ("as_ref", []) => option_as_ref_deref::check(cx, expr, recv2, m_arg, false, self.msrv),
3426 ("filter", [f_arg]) => {
3427 filter_map::check(cx, expr, recv2, f_arg, span2, recv, m_arg, span, false);
3429 ("find", [f_arg]) => {
3430 filter_map::check(cx, expr, recv2, f_arg, span2, recv, m_arg, span, true);
3435 map_identity::check(cx, expr, recv, m_arg, name, span);
3437 ("map_or", [def, map]) => {
3438 option_map_or_none::check(cx, expr, recv, def, map);
3439 manual_ok_or::check(cx, expr, recv, def, map);
3442 if let Some((name2, [recv2, args2 @ ..], _)) = method_call(recv) {
3443 match (name2, args2) {
3444 ("cloned", []) => iter_overeager_cloned::check(cx, expr, recv, recv2, false, false),
3445 ("filter", [arg]) => filter_next::check(cx, expr, recv2, arg),
3446 ("filter_map", [arg]) => filter_map_next::check(cx, expr, recv2, arg, self.msrv),
3447 ("iter", []) => iter_next_slice::check(cx, expr, recv2),
3448 ("skip", [arg]) => iter_skip_next::check(cx, expr, recv2, arg),
3449 ("skip_while", [_]) => skip_while_next::check(cx, expr),
3454 ("nth", [n_arg]) => match method_call(recv) {
3455 Some(("bytes", [recv2], _)) => bytes_nth::check(cx, expr, recv2, n_arg),
3456 Some(("cloned", [recv2], _)) => iter_overeager_cloned::check(cx, expr, recv, recv2, false, false),
3457 Some(("iter", [recv2], _)) => iter_nth::check(cx, expr, recv2, recv, n_arg, false),
3458 Some(("iter_mut", [recv2], _)) => iter_nth::check(cx, expr, recv2, recv, n_arg, true),
3459 _ => iter_nth_zero::check(cx, expr, recv, n_arg),
3461 ("ok_or_else", [arg]) => unnecessary_lazy_eval::check(cx, expr, recv, arg, "ok_or"),
3463 open_options::check(cx, expr, recv);
3465 ("or_else", [arg]) => {
3466 if !bind_instead_of_map::ResultOrElseErrInfo::check(cx, expr, recv, arg) {
3467 unnecessary_lazy_eval::check(cx, expr, recv, arg, "or");
3470 ("push", [arg]) => {
3471 path_buf_push_overwrite::check(cx, expr, arg);
3473 ("read_to_end", [_]) => {
3474 verbose_file_reads::check(cx, expr, recv, verbose_file_reads::READ_TO_END_MSG);
3476 ("read_to_string", [_]) => {
3477 verbose_file_reads::check(cx, expr, recv, verbose_file_reads::READ_TO_STRING_MSG);
3479 ("repeat", [arg]) => {
3480 repeat_once::check(cx, expr, recv, arg);
3482 ("resize", [count_arg, default_arg]) => {
3483 vec_resize_to_zero::check(cx, expr, count_arg, default_arg, span);
3486 stable_sort_primitive::check(cx, expr, recv);
3488 ("sort_by", [arg]) => {
3489 unnecessary_sort_by::check(cx, expr, recv, arg, false);
3491 ("sort_unstable_by", [arg]) => {
3492 unnecessary_sort_by::check(cx, expr, recv, arg, true);
3494 ("splitn" | "rsplitn", [count_arg, pat_arg]) => {
3495 if let Some((Constant::Int(count), _)) = constant(cx, cx.typeck_results(), count_arg) {
3496 suspicious_splitn::check(cx, name, expr, recv, count);
3497 str_splitn::check(cx, name, expr, recv, pat_arg, count, self.msrv);
3500 ("splitn_mut" | "rsplitn_mut", [count_arg, _]) => {
3501 if let Some((Constant::Int(count), _)) = constant(cx, cx.typeck_results(), count_arg) {
3502 suspicious_splitn::check(cx, name, expr, recv, count);
3505 ("step_by", [arg]) => iterator_step_by_zero::check(cx, expr, arg),
3506 ("take", [_arg]) => {
3507 if let Some((name2, [recv2, args2 @ ..], _span2)) = method_call(recv) {
3508 if let ("cloned", []) = (name2, args2) {
3509 iter_overeager_cloned::check(cx, expr, recv, recv2, false, false);
3513 ("take", []) => needless_option_take::check(cx, expr, recv),
3514 ("then", [arg]) => {
3515 if !meets_msrv(self.msrv, msrvs::BOOL_THEN_SOME) {
3518 unnecessary_lazy_eval::check(cx, expr, recv, arg, "then_some");
3520 ("to_os_string" | "to_owned" | "to_path_buf" | "to_vec", []) => {
3521 implicit_clone::check(cx, name, expr, recv);
3524 match method_call(recv) {
3525 Some(("get", [recv, get_arg], _)) => {
3526 get_unwrap::check(cx, expr, recv, get_arg, false);
3528 Some(("get_mut", [recv, get_arg], _)) => {
3529 get_unwrap::check(cx, expr, recv, get_arg, true);
3531 Some(("or", [recv, or_arg], or_span)) => {
3532 or_then_unwrap::check(cx, expr, recv, or_arg, or_span);
3536 unwrap_used::check(cx, expr, recv, false, self.allow_unwrap_in_tests);
3538 ("unwrap_err", []) => unwrap_used::check(cx, expr, recv, true, self.allow_unwrap_in_tests),
3539 ("unwrap_or", [u_arg]) => match method_call(recv) {
3540 Some((arith @ ("checked_add" | "checked_sub" | "checked_mul"), [lhs, rhs], _)) => {
3541 manual_saturating_arithmetic::check(cx, expr, lhs, rhs, u_arg, &arith["checked_".len()..]);
3543 Some(("map", [m_recv, m_arg], span)) => {
3544 option_map_unwrap_or::check(cx, expr, m_recv, m_arg, recv, u_arg, span);
3546 Some(("then_some", [t_recv, t_arg], _)) => {
3547 obfuscated_if_else::check(cx, expr, t_recv, t_arg, u_arg);
3551 ("unwrap_or_else", [u_arg]) => match method_call(recv) {
3552 Some(("map", [recv, map_arg], _))
3553 if map_unwrap_or::check(cx, expr, recv, map_arg, u_arg, self.msrv) => {},
3555 unwrap_or_else_default::check(cx, expr, recv, u_arg);
3556 unnecessary_lazy_eval::check(cx, expr, recv, u_arg, "unwrap_or");
3559 ("replace" | "replacen", [arg1, arg2] | [arg1, arg2, _]) => {
3560 no_effect_replace::check(cx, expr, arg1, arg2);
3563 if let ExprKind::MethodCall(name, [iter_recv], _) = recv.kind
3564 && name.ident.name == sym::iter
3566 range_zip_with_len::check(cx, expr, iter_recv, arg);
3575 fn check_is_some_is_none(cx: &LateContext<'_>, expr: &Expr<'_>, recv: &Expr<'_>, is_some: bool) {
3576 if let Some((name @ ("find" | "position" | "rposition"), [f_recv, arg], span)) = method_call(recv) {
3577 search_is_some::check(cx, expr, name, is_some, f_recv, arg, recv, span);
3581 /// Used for `lint_binary_expr_with_method_call`.
3582 #[derive(Copy, Clone)]
3583 struct BinaryExprInfo<'a> {
3584 expr: &'a hir::Expr<'a>,
3585 chain: &'a hir::Expr<'a>,
3586 other: &'a hir::Expr<'a>,
3590 /// Checks for the `CHARS_NEXT_CMP` and `CHARS_LAST_CMP` lints.
3591 fn lint_binary_expr_with_method_call(cx: &LateContext<'_>, info: &mut BinaryExprInfo<'_>) {
3592 macro_rules! lint_with_both_lhs_and_rhs {
3593 ($func:expr, $cx:expr, $info:ident) => {
3594 if !$func($cx, $info) {
3595 ::std::mem::swap(&mut $info.chain, &mut $info.other);
3596 if $func($cx, $info) {
3603 lint_with_both_lhs_and_rhs!(chars_next_cmp::check, cx, info);
3604 lint_with_both_lhs_and_rhs!(chars_last_cmp::check, cx, info);
3605 lint_with_both_lhs_and_rhs!(chars_next_cmp_with_unwrap::check, cx, info);
3606 lint_with_both_lhs_and_rhs!(chars_last_cmp_with_unwrap::check, cx, info);
3609 const FN_HEADER: hir::FnHeader = hir::FnHeader {
3610 unsafety: hir::Unsafety::Normal,
3611 constness: hir::Constness::NotConst,
3612 asyncness: hir::IsAsync::NotAsync,
3613 abi: rustc_target::spec::abi::Abi::Rust,
3616 struct ShouldImplTraitCase {
3617 trait_name: &'static str,
3618 method_name: &'static str,
3620 fn_header: hir::FnHeader,
3621 // implicit self kind expected (none, self, &self, ...)
3622 self_kind: SelfKind,
3623 // checks against the output type
3624 output_type: OutType,
3625 // certain methods with explicit lifetimes can't implement the equivalent trait method
3626 lint_explicit_lifetime: bool,
3628 impl ShouldImplTraitCase {
3630 trait_name: &'static str,
3631 method_name: &'static str,
3633 fn_header: hir::FnHeader,
3634 self_kind: SelfKind,
3635 output_type: OutType,
3636 lint_explicit_lifetime: bool,
3637 ) -> ShouldImplTraitCase {
3638 ShouldImplTraitCase {
3645 lint_explicit_lifetime,
3649 fn lifetime_param_cond(&self, impl_item: &hir::ImplItem<'_>) -> bool {
3650 self.lint_explicit_lifetime
3651 || !impl_item.generics.params.iter().any(|p| {
3654 hir::GenericParamKind::Lifetime {
3655 kind: hir::LifetimeParamKind::Explicit
3663 const TRAIT_METHODS: [ShouldImplTraitCase; 30] = [
3664 ShouldImplTraitCase::new("std::ops::Add", "add", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3665 ShouldImplTraitCase::new("std::convert::AsMut", "as_mut", 1, FN_HEADER, SelfKind::RefMut, OutType::Ref, true),
3666 ShouldImplTraitCase::new("std::convert::AsRef", "as_ref", 1, FN_HEADER, SelfKind::Ref, OutType::Ref, true),
3667 ShouldImplTraitCase::new("std::ops::BitAnd", "bitand", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3668 ShouldImplTraitCase::new("std::ops::BitOr", "bitor", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3669 ShouldImplTraitCase::new("std::ops::BitXor", "bitxor", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3670 ShouldImplTraitCase::new("std::borrow::Borrow", "borrow", 1, FN_HEADER, SelfKind::Ref, OutType::Ref, true),
3671 ShouldImplTraitCase::new("std::borrow::BorrowMut", "borrow_mut", 1, FN_HEADER, SelfKind::RefMut, OutType::Ref, true),
3672 ShouldImplTraitCase::new("std::clone::Clone", "clone", 1, FN_HEADER, SelfKind::Ref, OutType::Any, true),
3673 ShouldImplTraitCase::new("std::cmp::Ord", "cmp", 2, FN_HEADER, SelfKind::Ref, OutType::Any, true),
3674 // FIXME: default doesn't work
3675 ShouldImplTraitCase::new("std::default::Default", "default", 0, FN_HEADER, SelfKind::No, OutType::Any, true),
3676 ShouldImplTraitCase::new("std::ops::Deref", "deref", 1, FN_HEADER, SelfKind::Ref, OutType::Ref, true),
3677 ShouldImplTraitCase::new("std::ops::DerefMut", "deref_mut", 1, FN_HEADER, SelfKind::RefMut, OutType::Ref, true),
3678 ShouldImplTraitCase::new("std::ops::Div", "div", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3679 ShouldImplTraitCase::new("std::ops::Drop", "drop", 1, FN_HEADER, SelfKind::RefMut, OutType::Unit, true),
3680 ShouldImplTraitCase::new("std::cmp::PartialEq", "eq", 2, FN_HEADER, SelfKind::Ref, OutType::Bool, true),
3681 ShouldImplTraitCase::new("std::iter::FromIterator", "from_iter", 1, FN_HEADER, SelfKind::No, OutType::Any, true),
3682 ShouldImplTraitCase::new("std::str::FromStr", "from_str", 1, FN_HEADER, SelfKind::No, OutType::Any, true),
3683 ShouldImplTraitCase::new("std::hash::Hash", "hash", 2, FN_HEADER, SelfKind::Ref, OutType::Unit, true),
3684 ShouldImplTraitCase::new("std::ops::Index", "index", 2, FN_HEADER, SelfKind::Ref, OutType::Ref, true),
3685 ShouldImplTraitCase::new("std::ops::IndexMut", "index_mut", 2, FN_HEADER, SelfKind::RefMut, OutType::Ref, true),
3686 ShouldImplTraitCase::new("std::iter::IntoIterator", "into_iter", 1, FN_HEADER, SelfKind::Value, OutType::Any, true),
3687 ShouldImplTraitCase::new("std::ops::Mul", "mul", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3688 ShouldImplTraitCase::new("std::ops::Neg", "neg", 1, FN_HEADER, SelfKind::Value, OutType::Any, true),
3689 ShouldImplTraitCase::new("std::iter::Iterator", "next", 1, FN_HEADER, SelfKind::RefMut, OutType::Any, false),
3690 ShouldImplTraitCase::new("std::ops::Not", "not", 1, FN_HEADER, SelfKind::Value, OutType::Any, true),
3691 ShouldImplTraitCase::new("std::ops::Rem", "rem", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3692 ShouldImplTraitCase::new("std::ops::Shl", "shl", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3693 ShouldImplTraitCase::new("std::ops::Shr", "shr", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3694 ShouldImplTraitCase::new("std::ops::Sub", "sub", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3697 #[derive(Clone, Copy, PartialEq, Eq, Debug)]
3706 fn matches<'a>(self, cx: &LateContext<'a>, parent_ty: Ty<'a>, ty: Ty<'a>) -> bool {
3707 fn matches_value<'a>(cx: &LateContext<'a>, parent_ty: Ty<'a>, ty: Ty<'a>) -> bool {
3708 if ty == parent_ty {
3710 } else if ty.is_box() {
3711 ty.boxed_ty() == parent_ty
3712 } else if is_type_diagnostic_item(cx, ty, sym::Rc) || is_type_diagnostic_item(cx, ty, sym::Arc) {
3713 if let ty::Adt(_, substs) = ty.kind() {
3714 substs.types().next().map_or(false, |t| t == parent_ty)
3723 fn matches_ref<'a>(cx: &LateContext<'a>, mutability: hir::Mutability, parent_ty: Ty<'a>, ty: Ty<'a>) -> bool {
3724 if let ty::Ref(_, t, m) = *ty.kind() {
3725 return m == mutability && t == parent_ty;
3728 let trait_path = match mutability {
3729 hir::Mutability::Not => &paths::ASREF_TRAIT,
3730 hir::Mutability::Mut => &paths::ASMUT_TRAIT,
3733 let trait_def_id = match get_trait_def_id(cx, trait_path) {
3735 None => return false,
3737 implements_trait(cx, ty, trait_def_id, &[parent_ty.into()])
3740 fn matches_none<'a>(cx: &LateContext<'a>, parent_ty: Ty<'a>, ty: Ty<'a>) -> bool {
3741 !matches_value(cx, parent_ty, ty)
3742 && !matches_ref(cx, hir::Mutability::Not, parent_ty, ty)
3743 && !matches_ref(cx, hir::Mutability::Mut, parent_ty, ty)
3747 Self::Value => matches_value(cx, parent_ty, ty),
3748 Self::Ref => matches_ref(cx, hir::Mutability::Not, parent_ty, ty) || ty == parent_ty && is_copy(cx, ty),
3749 Self::RefMut => matches_ref(cx, hir::Mutability::Mut, parent_ty, ty),
3750 Self::No => matches_none(cx, parent_ty, ty),
3755 fn description(self) -> &'static str {
3757 Self::Value => "`self` by value",
3758 Self::Ref => "`self` by reference",
3759 Self::RefMut => "`self` by mutable reference",
3760 Self::No => "no `self`",
3765 #[derive(Clone, Copy)]
3774 fn matches(self, ty: &hir::FnRetTy<'_>) -> bool {
3775 let is_unit = |ty: &hir::Ty<'_>| matches!(ty.kind, hir::TyKind::Tup(&[]));
3777 (Self::Unit, &hir::FnRetTy::DefaultReturn(_)) => true,
3778 (Self::Unit, &hir::FnRetTy::Return(ty)) if is_unit(ty) => true,
3779 (Self::Bool, &hir::FnRetTy::Return(ty)) if is_bool(ty) => true,
3780 (Self::Any, &hir::FnRetTy::Return(ty)) if !is_unit(ty) => true,
3781 (Self::Ref, &hir::FnRetTy::Return(ty)) => matches!(ty.kind, hir::TyKind::Rptr(_, _)),
3787 fn is_bool(ty: &hir::Ty<'_>) -> bool {
3788 if let hir::TyKind::Path(QPath::Resolved(_, path)) = ty.kind {
3789 matches!(path.res, Res::PrimTy(PrimTy::Bool))
3795 fn fn_header_equals(expected: hir::FnHeader, actual: hir::FnHeader) -> bool {
3796 expected.constness == actual.constness
3797 && expected.unsafety == actual.unsafety
3798 && expected.asyncness == actual.asyncness