1 mod bind_instead_of_map;
4 mod chars_cmp_with_unwrap;
6 mod chars_last_cmp_with_unwrap;
8 mod chars_next_cmp_with_unwrap;
11 mod cloned_instead_of_copied;
15 mod extend_with_drain;
18 mod filter_map_identity;
21 mod flat_map_identity;
23 mod from_iter_instead_of_collect;
24 mod get_last_with_len;
27 mod inefficient_to_string;
30 mod is_digit_ascii_radix;
31 mod iter_cloned_collect;
36 mod iter_overeager_cloned;
39 mod iterator_step_by_zero;
40 mod manual_saturating_arithmetic;
41 mod manual_str_repeat;
42 mod map_collect_result_unit;
46 mod needless_option_as_deref;
47 mod needless_option_take;
48 mod no_effect_replace;
50 mod option_as_ref_deref;
51 mod option_map_or_none;
52 mod option_map_unwrap_or;
56 mod single_char_add_str;
57 mod single_char_insert_string;
58 mod single_char_pattern;
59 mod single_char_push_string;
62 mod string_extend_chars;
64 mod suspicious_splitn;
65 mod uninit_assumed_init;
66 mod unnecessary_filter_map;
68 mod unnecessary_iter_cloned;
70 mod unnecessary_lazy_eval;
71 mod unnecessary_to_owned;
72 mod unwrap_or_else_default;
76 mod wrong_self_convention;
79 use bind_instead_of_map::BindInsteadOfMap;
80 use clippy_utils::consts::{constant, Constant};
81 use clippy_utils::diagnostics::{span_lint, span_lint_and_help};
82 use clippy_utils::ty::{contains_adt_constructor, contains_ty, implements_trait, is_copy, is_type_diagnostic_item};
83 use clippy_utils::{contains_return, get_trait_def_id, iter_input_pats, meets_msrv, msrvs, paths, return_ty};
84 use if_chain::if_chain;
86 use rustc_hir::def::Res;
87 use rustc_hir::{Expr, ExprKind, PrimTy, QPath, TraitItem, TraitItemKind};
88 use rustc_lint::{LateContext, LateLintPass, LintContext};
89 use rustc_middle::lint::in_external_macro;
90 use rustc_middle::ty::{self, TraitRef, Ty};
91 use rustc_semver::RustcVersion;
92 use rustc_session::{declare_tool_lint, impl_lint_pass};
93 use rustc_span::{sym, Span};
94 use rustc_typeck::hir_ty_to_ty;
96 declare_clippy_lint! {
98 /// Checks for usages of `cloned()` on an `Iterator` or `Option` where
99 /// `copied()` could be used instead.
101 /// ### Why is this bad?
102 /// `copied()` is better because it guarantees that the type being cloned
103 /// implements `Copy`.
107 /// [1, 2, 3].iter().cloned();
111 /// [1, 2, 3].iter().copied();
113 #[clippy::version = "1.53.0"]
114 pub CLONED_INSTEAD_OF_COPIED,
116 "used `cloned` where `copied` could be used instead"
119 declare_clippy_lint! {
121 /// Checks for usage of `_.cloned().<func>()` where call to `.cloned()` can be postponed.
123 /// ### Why is this bad?
124 /// It's often inefficient to clone all elements of an iterator, when eventually, only some
125 /// of them will be consumed.
129 /// # let vec = vec!["string".to_string()];
132 /// vec.iter().cloned().take(10);
135 /// vec.iter().take(10).cloned();
138 /// vec.iter().cloned().last();
141 /// vec.iter().last().cloned();
144 /// ### Known Problems
145 /// This `lint` removes the side of effect of cloning items in the iterator.
146 /// A code that relies on that side-effect could fail.
148 #[clippy::version = "1.59.0"]
149 pub ITER_OVEREAGER_CLONED,
151 "using `cloned()` early with `Iterator::iter()` can lead to some performance inefficiencies"
154 declare_clippy_lint! {
156 /// Checks for usages of `Iterator::flat_map()` where `filter_map()` could be
159 /// ### Why is this bad?
160 /// When applicable, `filter_map()` is more clear since it shows that
161 /// `Option` is used to produce 0 or 1 items.
165 /// let nums: Vec<i32> = ["1", "2", "whee!"].iter().flat_map(|x| x.parse().ok()).collect();
169 /// let nums: Vec<i32> = ["1", "2", "whee!"].iter().filter_map(|x| x.parse().ok()).collect();
171 #[clippy::version = "1.53.0"]
174 "used `flat_map` where `filter_map` could be used instead"
177 declare_clippy_lint! {
179 /// Checks for `.unwrap()` calls on `Option`s and on `Result`s.
181 /// ### Why is this bad?
182 /// It is better to handle the `None` or `Err` case,
183 /// or at least call `.expect(_)` with a more helpful message. Still, for a lot of
184 /// quick-and-dirty code, `unwrap` is a good choice, which is why this lint is
185 /// `Allow` by default.
187 /// `result.unwrap()` will let the thread panic on `Err` values.
188 /// Normally, you want to implement more sophisticated error handling,
189 /// and propagate errors upwards with `?` operator.
191 /// Even if you want to panic on errors, not all `Error`s implement good
192 /// messages on display. Therefore, it may be beneficial to look at the places
193 /// where they may get displayed. Activate this lint to do just that.
197 /// # let option = Some(1);
198 /// # let result: Result<usize, ()> = Ok(1);
205 /// # let option = Some(1);
206 /// # let result: Result<usize, ()> = Ok(1);
207 /// option.expect("more helpful message");
208 /// result.expect("more helpful message");
210 #[clippy::version = "1.45.0"]
213 "using `.unwrap()` on `Result` or `Option`, which should at least get a better message using `expect()`"
216 declare_clippy_lint! {
218 /// Checks for `.expect()` calls on `Option`s and `Result`s.
220 /// ### Why is this bad?
221 /// Usually it is better to handle the `None` or `Err` case.
222 /// Still, for a lot of quick-and-dirty code, `expect` is a good choice, which is why
223 /// this lint is `Allow` by default.
225 /// `result.expect()` will let the thread panic on `Err`
226 /// values. Normally, you want to implement more sophisticated error handling,
227 /// and propagate errors upwards with `?` operator.
231 /// # let option = Some(1);
232 /// # let result: Result<usize, ()> = Ok(1);
233 /// option.expect("one");
234 /// result.expect("one");
239 /// # let option = Some(1);
240 /// # let result: Result<usize, ()> = Ok(1);
247 #[clippy::version = "1.45.0"]
250 "using `.expect()` on `Result` or `Option`, which might be better handled"
253 declare_clippy_lint! {
255 /// Checks for methods that should live in a trait
256 /// implementation of a `std` trait (see [llogiq's blog
257 /// post](http://llogiq.github.io/2015/07/30/traits.html) for further
258 /// information) instead of an inherent implementation.
260 /// ### Why is this bad?
261 /// Implementing the traits improve ergonomics for users of
262 /// the code, often with very little cost. Also people seeing a `mul(...)`
264 /// may expect `*` to work equally, so you should have good reason to disappoint
271 /// fn add(&self, other: &X) -> X {
277 #[clippy::version = "pre 1.29.0"]
278 pub SHOULD_IMPLEMENT_TRAIT,
280 "defining a method that should be implementing a std trait"
283 declare_clippy_lint! {
285 /// Checks for methods with certain name prefixes and which
286 /// doesn't match how self is taken. The actual rules are:
288 /// |Prefix |Postfix |`self` taken | `self` type |
289 /// |-------|------------|-------------------------------|--------------|
290 /// |`as_` | none |`&self` or `&mut self` | any |
291 /// |`from_`| none | none | any |
292 /// |`into_`| none |`self` | any |
293 /// |`is_` | none |`&mut self` or `&self` or none | any |
294 /// |`to_` | `_mut` |`&mut self` | any |
295 /// |`to_` | not `_mut` |`self` | `Copy` |
296 /// |`to_` | not `_mut` |`&self` | not `Copy` |
298 /// Note: Clippy doesn't trigger methods with `to_` prefix in:
299 /// - Traits definition.
300 /// Clippy can not tell if a type that implements a trait is `Copy` or not.
301 /// - Traits implementation, when `&self` is taken.
302 /// The method signature is controlled by the trait and often `&self` is required for all types that implement the trait
303 /// (see e.g. the `std::string::ToString` trait).
305 /// Clippy allows `Pin<&Self>` and `Pin<&mut Self>` if `&self` and `&mut self` is required.
307 /// Please find more info here:
308 /// https://rust-lang.github.io/api-guidelines/naming.html#ad-hoc-conversions-follow-as_-to_-into_-conventions-c-conv
310 /// ### Why is this bad?
311 /// Consistency breeds readability. If you follow the
312 /// conventions, your users won't be surprised that they, e.g., need to supply a
313 /// mutable reference to a `as_..` function.
319 /// fn as_str(self) -> &'static str {
325 #[clippy::version = "pre 1.29.0"]
326 pub WRONG_SELF_CONVENTION,
328 "defining a method named with an established prefix (like \"into_\") that takes `self` with the wrong convention"
331 declare_clippy_lint! {
333 /// Checks for usage of `ok().expect(..)`.
335 /// ### Why is this bad?
336 /// Because you usually call `expect()` on the `Result`
337 /// directly to get a better error message.
339 /// ### Known problems
340 /// The error type needs to implement `Debug`
344 /// # let x = Ok::<_, ()>(());
347 /// x.ok().expect("why did I do this again?");
350 /// x.expect("why did I do this again?");
352 #[clippy::version = "pre 1.29.0"]
355 "using `ok().expect()`, which gives worse error messages than calling `expect` directly on the Result"
358 declare_clippy_lint! {
360 /// Checks for `.err().expect()` calls on the `Result` type.
362 /// ### Why is this bad?
363 /// `.expect_err()` can be called directly to avoid the extra type conversion from `err()`.
367 /// let x: Result<u32, &str> = Ok(10);
368 /// x.err().expect("Testing err().expect()");
372 /// let x: Result<u32, &str> = Ok(10);
373 /// x.expect_err("Testing expect_err");
375 #[clippy::version = "1.61.0"]
378 r#"using `.err().expect("")` when `.expect_err("")` can be used"#
381 declare_clippy_lint! {
383 /// Checks for usages of `_.unwrap_or_else(Default::default)` on `Option` and
386 /// ### Why is this bad?
387 /// Readability, these can be written as `_.unwrap_or_default`, which is
388 /// simpler and more concise.
392 /// # let x = Some(1);
395 /// x.unwrap_or_else(Default::default);
396 /// x.unwrap_or_else(u32::default);
399 /// x.unwrap_or_default();
401 #[clippy::version = "1.56.0"]
402 pub UNWRAP_OR_ELSE_DEFAULT,
404 "using `.unwrap_or_else(Default::default)`, which is more succinctly expressed as `.unwrap_or_default()`"
407 declare_clippy_lint! {
409 /// Checks for usage of `option.map(_).unwrap_or(_)` or `option.map(_).unwrap_or_else(_)` or
410 /// `result.map(_).unwrap_or_else(_)`.
412 /// ### Why is this bad?
413 /// Readability, these can be written more concisely (resp.) as
414 /// `option.map_or(_, _)`, `option.map_or_else(_, _)` and `result.map_or_else(_, _)`.
416 /// ### Known problems
417 /// The order of the arguments is not in execution order
421 /// # let option = Some(1);
422 /// # let result: Result<usize, ()> = Ok(1);
423 /// # fn some_function(foo: ()) -> usize { 1 }
424 /// option.map(|a| a + 1).unwrap_or(0);
425 /// result.map(|a| a + 1).unwrap_or_else(some_function);
430 /// # let option = Some(1);
431 /// # let result: Result<usize, ()> = Ok(1);
432 /// # fn some_function(foo: ()) -> usize { 1 }
433 /// option.map_or(0, |a| a + 1);
434 /// result.map_or_else(some_function, |a| a + 1);
436 #[clippy::version = "1.45.0"]
439 "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)`"
442 declare_clippy_lint! {
444 /// Checks for usage of `_.map_or(None, _)`.
446 /// ### Why is this bad?
447 /// Readability, this can be written more concisely as
450 /// ### Known problems
451 /// The order of the arguments is not in execution order.
455 /// # let opt = Some(1);
458 /// opt.map_or(None, |a| Some(a + 1));
461 /// opt.and_then(|a| Some(a + 1));
463 #[clippy::version = "pre 1.29.0"]
464 pub OPTION_MAP_OR_NONE,
466 "using `Option.map_or(None, f)`, which is more succinctly expressed as `and_then(f)`"
469 declare_clippy_lint! {
471 /// Checks for usage of `_.map_or(None, Some)`.
473 /// ### Why is this bad?
474 /// Readability, this can be written more concisely as
480 /// # let r: Result<u32, &str> = Ok(1);
481 /// assert_eq!(Some(1), r.map_or(None, Some));
486 /// # let r: Result<u32, &str> = Ok(1);
487 /// assert_eq!(Some(1), r.ok());
489 #[clippy::version = "1.44.0"]
490 pub RESULT_MAP_OR_INTO_OPTION,
492 "using `Result.map_or(None, Some)`, which is more succinctly expressed as `ok()`"
495 declare_clippy_lint! {
497 /// Checks for usage of `_.and_then(|x| Some(y))`, `_.and_then(|x| Ok(y))` or
498 /// `_.or_else(|x| Err(y))`.
500 /// ### Why is this bad?
501 /// Readability, this can be written more concisely as
502 /// `_.map(|x| y)` or `_.map_err(|x| y)`.
506 /// # fn opt() -> Option<&'static str> { Some("42") }
507 /// # fn res() -> Result<&'static str, &'static str> { Ok("42") }
508 /// let _ = opt().and_then(|s| Some(s.len()));
509 /// let _ = res().and_then(|s| if s.len() == 42 { Ok(10) } else { Ok(20) });
510 /// let _ = res().or_else(|s| if s.len() == 42 { Err(10) } else { Err(20) });
513 /// The correct use would be:
516 /// # fn opt() -> Option<&'static str> { Some("42") }
517 /// # fn res() -> Result<&'static str, &'static str> { Ok("42") }
518 /// let _ = opt().map(|s| s.len());
519 /// let _ = res().map(|s| if s.len() == 42 { 10 } else { 20 });
520 /// let _ = res().map_err(|s| if s.len() == 42 { 10 } else { 20 });
522 #[clippy::version = "1.45.0"]
523 pub BIND_INSTEAD_OF_MAP,
525 "using `Option.and_then(|x| Some(y))`, which is more succinctly expressed as `map(|x| y)`"
528 declare_clippy_lint! {
530 /// Checks for usage of `_.filter(_).next()`.
532 /// ### Why is this bad?
533 /// Readability, this can be written more concisely as
538 /// # let vec = vec![1];
539 /// vec.iter().filter(|x| **x == 0).next();
541 /// Could be written as
543 /// # let vec = vec![1];
544 /// vec.iter().find(|x| **x == 0);
546 #[clippy::version = "pre 1.29.0"]
549 "using `filter(p).next()`, which is more succinctly expressed as `.find(p)`"
552 declare_clippy_lint! {
554 /// Checks for usage of `_.skip_while(condition).next()`.
556 /// ### Why is this bad?
557 /// Readability, this can be written more concisely as
558 /// `_.find(!condition)`.
562 /// # let vec = vec![1];
563 /// vec.iter().skip_while(|x| **x == 0).next();
565 /// Could be written as
567 /// # let vec = vec![1];
568 /// vec.iter().find(|x| **x != 0);
570 #[clippy::version = "1.42.0"]
573 "using `skip_while(p).next()`, which is more succinctly expressed as `.find(!p)`"
576 declare_clippy_lint! {
578 /// Checks for usage of `_.map(_).flatten(_)` on `Iterator` and `Option`
580 /// ### Why is this bad?
581 /// Readability, this can be written more concisely as
582 /// `_.flat_map(_)` for `Iterator` or `_.and_then(_)` for `Option`
586 /// let vec = vec![vec![1]];
587 /// let opt = Some(5);
590 /// vec.iter().map(|x| x.iter()).flatten();
591 /// opt.map(|x| Some(x * 2)).flatten();
594 /// vec.iter().flat_map(|x| x.iter());
595 /// opt.and_then(|x| Some(x * 2));
597 #[clippy::version = "1.31.0"]
600 "using combinations of `flatten` and `map` which can usually be written as a single method call"
603 declare_clippy_lint! {
605 /// Checks for usage of `_.filter(_).map(_)` that can be written more simply
606 /// as `filter_map(_)`.
608 /// ### Why is this bad?
609 /// Redundant code in the `filter` and `map` operations is poor style and
616 /// .filter(|n| n.checked_add(1).is_some())
617 /// .map(|n| n.checked_add(1).unwrap());
622 /// (0_i32..10).filter_map(|n| n.checked_add(1));
624 #[clippy::version = "1.51.0"]
625 pub MANUAL_FILTER_MAP,
627 "using `_.filter(_).map(_)` in a way that can be written more simply as `filter_map(_)`"
630 declare_clippy_lint! {
632 /// Checks for usage of `_.find(_).map(_)` that can be written more simply
633 /// as `find_map(_)`.
635 /// ### Why is this bad?
636 /// Redundant code in the `find` and `map` operations is poor style and
643 /// .find(|n| n.checked_add(1).is_some())
644 /// .map(|n| n.checked_add(1).unwrap());
649 /// (0_i32..10).find_map(|n| n.checked_add(1));
651 #[clippy::version = "1.51.0"]
654 "using `_.find(_).map(_)` in a way that can be written more simply as `find_map(_)`"
657 declare_clippy_lint! {
659 /// Checks for usage of `_.filter_map(_).next()`.
661 /// ### Why is this bad?
662 /// Readability, this can be written more concisely as
667 /// (0..3).filter_map(|x| if x == 2 { Some(x) } else { None }).next();
669 /// Can be written as
672 /// (0..3).find_map(|x| if x == 2 { Some(x) } else { None });
674 #[clippy::version = "1.36.0"]
677 "using combination of `filter_map` and `next` which can usually be written as a single method call"
680 declare_clippy_lint! {
682 /// Checks for usage of `flat_map(|x| x)`.
684 /// ### Why is this bad?
685 /// Readability, this can be written more concisely by using `flatten`.
689 /// # let iter = vec![vec![0]].into_iter();
690 /// iter.flat_map(|x| x);
692 /// Can be written as
694 /// # let iter = vec![vec![0]].into_iter();
697 #[clippy::version = "1.39.0"]
698 pub FLAT_MAP_IDENTITY,
700 "call to `flat_map` where `flatten` is sufficient"
703 declare_clippy_lint! {
705 /// Checks for an iterator or string search (such as `find()`,
706 /// `position()`, or `rposition()`) followed by a call to `is_some()` or `is_none()`.
708 /// ### Why is this bad?
709 /// Readability, this can be written more concisely as:
710 /// * `_.any(_)`, or `_.contains(_)` for `is_some()`,
711 /// * `!_.any(_)`, or `!_.contains(_)` for `is_none()`.
715 /// let vec = vec![1];
716 /// vec.iter().find(|x| **x == 0).is_some();
718 /// let _ = "hello world".find("world").is_none();
720 /// Could be written as
722 /// let vec = vec![1];
723 /// vec.iter().any(|x| *x == 0);
725 /// let _ = !"hello world".contains("world");
727 #[clippy::version = "pre 1.29.0"]
730 "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()`)"
733 declare_clippy_lint! {
735 /// Checks for usage of `.chars().next()` on a `str` to check
736 /// if it starts with a given char.
738 /// ### Why is this bad?
739 /// Readability, this can be written more concisely as
740 /// `_.starts_with(_)`.
744 /// let name = "foo";
745 /// if name.chars().next() == Some('_') {};
747 /// Could be written as
749 /// let name = "foo";
750 /// if name.starts_with('_') {};
752 #[clippy::version = "pre 1.29.0"]
755 "using `.chars().next()` to check if a string starts with a char"
758 declare_clippy_lint! {
760 /// Checks for calls to `.or(foo(..))`, `.unwrap_or(foo(..))`,
761 /// etc., and suggests to use `or_else`, `unwrap_or_else`, etc., or
762 /// `unwrap_or_default` instead.
764 /// ### Why is this bad?
765 /// The function will always be called and potentially
766 /// allocate an object acting as the default.
768 /// ### Known problems
769 /// If the function has side-effects, not calling it will
770 /// change the semantic of the program, but you shouldn't rely on that anyway.
774 /// # let foo = Some(String::new());
775 /// foo.unwrap_or(String::new());
780 /// # let foo = Some(String::new());
781 /// foo.unwrap_or_else(String::new);
785 /// # let foo = Some(String::new());
786 /// foo.unwrap_or_default();
788 #[clippy::version = "pre 1.29.0"]
791 "using any `*or` method with a function call, which suggests `*or_else`"
794 declare_clippy_lint! {
796 /// Checks for `.or(…).unwrap()` calls to Options and Results.
798 /// ### Why is this bad?
799 /// You should use `.unwrap_or(…)` instead for clarity.
803 /// # let fallback = "fallback";
805 /// # type Error = &'static str;
806 /// # let result: Result<&str, Error> = Err("error");
807 /// let value = result.or::<Error>(Ok(fallback)).unwrap();
810 /// # let option: Option<&str> = None;
811 /// let value = option.or(Some(fallback)).unwrap();
815 /// # let fallback = "fallback";
817 /// # let result: Result<&str, &str> = Err("error");
818 /// let value = result.unwrap_or(fallback);
821 /// # let option: Option<&str> = None;
822 /// let value = option.unwrap_or(fallback);
824 #[clippy::version = "1.61.0"]
827 "checks for `.or(…).unwrap()` calls to Options and Results."
830 declare_clippy_lint! {
832 /// Checks for calls to `.expect(&format!(...))`, `.expect(foo(..))`,
833 /// etc., and suggests to use `unwrap_or_else` instead
835 /// ### Why is this bad?
836 /// The function will always be called.
838 /// ### Known problems
839 /// If the function has side-effects, not calling it will
840 /// change the semantics of the program, but you shouldn't rely on that anyway.
844 /// # let foo = Some(String::new());
845 /// # let err_code = "418";
846 /// # let err_msg = "I'm a teapot";
847 /// foo.expect(&format!("Err {}: {}", err_code, err_msg));
851 /// # let foo = Some(String::new());
852 /// foo.expect(format!("Err {}: {}", err_code, err_msg).as_str());
857 /// # let foo = Some(String::new());
858 /// # let err_code = "418";
859 /// # let err_msg = "I'm a teapot";
860 /// foo.unwrap_or_else(|| panic!("Err {}: {}", err_code, err_msg));
862 #[clippy::version = "pre 1.29.0"]
865 "using any `expect` method with a function call"
868 declare_clippy_lint! {
870 /// Checks for usage of `.clone()` on a `Copy` type.
872 /// ### Why is this bad?
873 /// The only reason `Copy` types implement `Clone` is for
874 /// generics, not for using the `clone` method on a concrete type.
880 #[clippy::version = "pre 1.29.0"]
883 "using `clone` on a `Copy` type"
886 declare_clippy_lint! {
888 /// Checks for usage of `.clone()` on a ref-counted pointer,
889 /// (`Rc`, `Arc`, `rc::Weak`, or `sync::Weak`), and suggests calling Clone via unified
890 /// function syntax instead (e.g., `Rc::clone(foo)`).
892 /// ### Why is this bad?
893 /// Calling '.clone()' on an Rc, Arc, or Weak
894 /// can obscure the fact that only the pointer is being cloned, not the underlying
899 /// # use std::rc::Rc;
900 /// let x = Rc::new(1);
908 #[clippy::version = "pre 1.29.0"]
909 pub CLONE_ON_REF_PTR,
911 "using 'clone' on a ref-counted pointer"
914 declare_clippy_lint! {
916 /// Checks for usage of `.clone()` on an `&&T`.
918 /// ### Why is this bad?
919 /// Cloning an `&&T` copies the inner `&T`, instead of
920 /// cloning the underlying `T`.
927 /// let z = y.clone();
928 /// println!("{:p} {:p}", *y, z); // prints out the same pointer
931 #[clippy::version = "pre 1.29.0"]
932 pub CLONE_DOUBLE_REF,
934 "using `clone` on `&&T`"
937 declare_clippy_lint! {
939 /// Checks for usage of `.to_string()` on an `&&T` where
940 /// `T` implements `ToString` directly (like `&&str` or `&&String`).
942 /// ### Why is this bad?
943 /// This bypasses the specialized implementation of
944 /// `ToString` and instead goes through the more expensive string formatting
949 /// // Generic implementation for `T: Display` is used (slow)
950 /// ["foo", "bar"].iter().map(|s| s.to_string());
952 /// // OK, the specialized impl is used
953 /// ["foo", "bar"].iter().map(|&s| s.to_string());
955 #[clippy::version = "1.40.0"]
956 pub INEFFICIENT_TO_STRING,
958 "using `to_string` on `&&T` where `T: ToString`"
961 declare_clippy_lint! {
963 /// Checks for `new` not returning a type that contains `Self`.
965 /// ### Why is this bad?
966 /// As a convention, `new` methods are used to make a new
967 /// instance of a type.
970 /// In an impl block:
973 /// # struct NotAFoo;
975 /// fn new() -> NotAFoo {
985 /// // Bad. The type name must contain `Self`
986 /// fn new() -> Bar {
994 /// # struct FooError;
996 /// // Good. Return type contains `Self`
997 /// fn new() -> Result<Foo, FooError> {
1003 /// Or in a trait definition:
1005 /// pub trait Trait {
1006 /// // Bad. The type name must contain `Self`
1012 /// pub trait Trait {
1013 /// // Good. Return type contains `Self`
1014 /// fn new() -> Self;
1017 #[clippy::version = "pre 1.29.0"]
1018 pub NEW_RET_NO_SELF,
1020 "not returning type containing `Self` in a `new` method"
1023 declare_clippy_lint! {
1024 /// ### What it does
1025 /// Checks for string methods that receive a single-character
1026 /// `str` as an argument, e.g., `_.split("x")`.
1028 /// ### Why is this bad?
1029 /// Performing these methods using a `char` is faster than
1032 /// ### Known problems
1033 /// Does not catch multi-byte unicode characters.
1043 #[clippy::version = "pre 1.29.0"]
1044 pub SINGLE_CHAR_PATTERN,
1046 "using a single-character str where a char could be used, e.g., `_.split(\"x\")`"
1049 declare_clippy_lint! {
1050 /// ### What it does
1051 /// Checks for calling `.step_by(0)` on iterators which panics.
1053 /// ### Why is this bad?
1054 /// This very much looks like an oversight. Use `panic!()` instead if you
1055 /// actually intend to panic.
1058 /// ```rust,should_panic
1059 /// for x in (0..100).step_by(0) {
1063 #[clippy::version = "pre 1.29.0"]
1064 pub ITERATOR_STEP_BY_ZERO,
1066 "using `Iterator::step_by(0)`, which will panic at runtime"
1069 declare_clippy_lint! {
1070 /// ### What it does
1071 /// Checks for indirect collection of populated `Option`
1073 /// ### Why is this bad?
1074 /// `Option` is like a collection of 0-1 things, so `flatten`
1075 /// automatically does this without suspicious-looking `unwrap` calls.
1079 /// let _ = std::iter::empty::<Option<i32>>().filter(Option::is_some).map(Option::unwrap);
1083 /// let _ = std::iter::empty::<Option<i32>>().flatten();
1085 #[clippy::version = "1.53.0"]
1086 pub OPTION_FILTER_MAP,
1088 "filtering `Option` for `Some` then force-unwrapping, which can be one type-safe operation"
1091 declare_clippy_lint! {
1092 /// ### What it does
1093 /// Checks for the use of `iter.nth(0)`.
1095 /// ### Why is this bad?
1096 /// `iter.next()` is equivalent to
1097 /// `iter.nth(0)`, as they both consume the next element,
1098 /// but is more readable.
1102 /// # use std::collections::HashSet;
1104 /// # let mut s = HashSet::new();
1106 /// let x = s.iter().nth(0);
1109 /// # let mut s = HashSet::new();
1111 /// let x = s.iter().next();
1113 #[clippy::version = "1.42.0"]
1116 "replace `iter.nth(0)` with `iter.next()`"
1119 declare_clippy_lint! {
1120 /// ### What it does
1121 /// Checks for use of `.iter().nth()` (and the related
1122 /// `.iter_mut().nth()`) on standard library types with *O*(1) element access.
1124 /// ### Why is this bad?
1125 /// `.get()` and `.get_mut()` are more efficient and more
1130 /// let some_vec = vec![0, 1, 2, 3];
1131 /// let bad_vec = some_vec.iter().nth(3);
1132 /// let bad_slice = &some_vec[..].iter().nth(3);
1134 /// The correct use would be:
1136 /// let some_vec = vec![0, 1, 2, 3];
1137 /// let bad_vec = some_vec.get(3);
1138 /// let bad_slice = &some_vec[..].get(3);
1140 #[clippy::version = "pre 1.29.0"]
1143 "using `.iter().nth()` on a standard library type with O(1) element access"
1146 declare_clippy_lint! {
1147 /// ### What it does
1148 /// Checks for use of `.skip(x).next()` on iterators.
1150 /// ### Why is this bad?
1151 /// `.nth(x)` is cleaner
1155 /// let some_vec = vec![0, 1, 2, 3];
1156 /// let bad_vec = some_vec.iter().skip(3).next();
1157 /// let bad_slice = &some_vec[..].iter().skip(3).next();
1159 /// The correct use would be:
1161 /// let some_vec = vec![0, 1, 2, 3];
1162 /// let bad_vec = some_vec.iter().nth(3);
1163 /// let bad_slice = &some_vec[..].iter().nth(3);
1165 #[clippy::version = "pre 1.29.0"]
1168 "using `.skip(x).next()` on an iterator"
1171 declare_clippy_lint! {
1172 /// ### What it does
1173 /// Checks for use of `.drain(..)` on `Vec` and `VecDeque` for iteration.
1175 /// ### Why is this bad?
1176 /// `.into_iter()` is simpler with better performance.
1180 /// # use std::collections::HashSet;
1181 /// let mut foo = vec![0, 1, 2, 3];
1182 /// let bar: HashSet<usize> = foo.drain(..).collect();
1186 /// # use std::collections::HashSet;
1187 /// let foo = vec![0, 1, 2, 3];
1188 /// let bar: HashSet<usize> = foo.into_iter().collect();
1190 #[clippy::version = "1.61.0"]
1191 pub ITER_WITH_DRAIN,
1193 "replace `.drain(..)` with `.into_iter()`"
1196 declare_clippy_lint! {
1197 /// ### What it does
1198 /// Checks for using `x.get(x.len() - 1)` instead of
1201 /// ### Why is this bad?
1202 /// Using `x.last()` is easier to read and has the same
1205 /// Note that using `x[x.len() - 1]` is semantically different from
1206 /// `x.last()`. Indexing into the array will panic on out-of-bounds
1207 /// accesses, while `x.get()` and `x.last()` will return `None`.
1209 /// There is another lint (get_unwrap) that covers the case of using
1210 /// `x.get(index).unwrap()` instead of `x[index]`.
1215 /// let x = vec![2, 3, 5];
1216 /// let last_element = x.get(x.len() - 1);
1219 /// let x = vec![2, 3, 5];
1220 /// let last_element = x.last();
1222 #[clippy::version = "1.37.0"]
1223 pub GET_LAST_WITH_LEN,
1225 "Using `x.get(x.len() - 1)` when `x.last()` is correct and simpler"
1228 declare_clippy_lint! {
1229 /// ### What it does
1230 /// Checks for use of `.get().unwrap()` (or
1231 /// `.get_mut().unwrap`) on a standard library type which implements `Index`
1233 /// ### Why is this bad?
1234 /// Using the Index trait (`[]`) is more clear and more
1237 /// ### Known problems
1238 /// Not a replacement for error handling: Using either
1239 /// `.unwrap()` or the Index trait (`[]`) carries the risk of causing a `panic`
1240 /// if the value being accessed is `None`. If the use of `.get().unwrap()` is a
1241 /// temporary placeholder for dealing with the `Option` type, then this does
1242 /// not mitigate the need for error handling. If there is a chance that `.get()`
1243 /// will be `None` in your program, then it is advisable that the `None` case
1244 /// is handled in a future refactor instead of using `.unwrap()` or the Index
1249 /// let mut some_vec = vec![0, 1, 2, 3];
1250 /// let last = some_vec.get(3).unwrap();
1251 /// *some_vec.get_mut(0).unwrap() = 1;
1253 /// The correct use would be:
1255 /// let mut some_vec = vec![0, 1, 2, 3];
1256 /// let last = some_vec[3];
1257 /// some_vec[0] = 1;
1259 #[clippy::version = "pre 1.29.0"]
1262 "using `.get().unwrap()` or `.get_mut().unwrap()` when using `[]` would work instead"
1265 declare_clippy_lint! {
1266 /// ### What it does
1267 /// Checks for occurrences where one vector gets extended instead of append
1269 /// ### Why is this bad?
1270 /// Using `append` instead of `extend` is more concise and faster
1274 /// let mut a = vec![1, 2, 3];
1275 /// let mut b = vec![4, 5, 6];
1278 /// a.extend(b.drain(..));
1281 /// a.append(&mut b);
1283 #[clippy::version = "1.55.0"]
1284 pub EXTEND_WITH_DRAIN,
1286 "using vec.append(&mut vec) to move the full range of a vector to another"
1289 declare_clippy_lint! {
1290 /// ### What it does
1291 /// Checks for the use of `.extend(s.chars())` where s is a
1292 /// `&str` or `String`.
1294 /// ### Why is this bad?
1295 /// `.push_str(s)` is clearer
1299 /// let abc = "abc";
1300 /// let def = String::from("def");
1301 /// let mut s = String::new();
1302 /// s.extend(abc.chars());
1303 /// s.extend(def.chars());
1305 /// The correct use would be:
1307 /// let abc = "abc";
1308 /// let def = String::from("def");
1309 /// let mut s = String::new();
1310 /// s.push_str(abc);
1311 /// s.push_str(&def);
1313 #[clippy::version = "pre 1.29.0"]
1314 pub STRING_EXTEND_CHARS,
1316 "using `x.extend(s.chars())` where s is a `&str` or `String`"
1319 declare_clippy_lint! {
1320 /// ### What it does
1321 /// Checks for the use of `.cloned().collect()` on slice to
1324 /// ### Why is this bad?
1325 /// `.to_vec()` is clearer
1329 /// let s = [1, 2, 3, 4, 5];
1330 /// let s2: Vec<isize> = s[..].iter().cloned().collect();
1332 /// The better use would be:
1334 /// let s = [1, 2, 3, 4, 5];
1335 /// let s2: Vec<isize> = s.to_vec();
1337 #[clippy::version = "pre 1.29.0"]
1338 pub ITER_CLONED_COLLECT,
1340 "using `.cloned().collect()` on slice to create a `Vec`"
1343 declare_clippy_lint! {
1344 /// ### What it does
1345 /// Checks for usage of `_.chars().last()` or
1346 /// `_.chars().next_back()` on a `str` to check if it ends with a given char.
1348 /// ### Why is this bad?
1349 /// Readability, this can be written more concisely as
1350 /// `_.ends_with(_)`.
1354 /// # let name = "_";
1357 /// name.chars().last() == Some('_') || name.chars().next_back() == Some('-');
1360 /// name.ends_with('_') || name.ends_with('-');
1362 #[clippy::version = "pre 1.29.0"]
1365 "using `.chars().last()` or `.chars().next_back()` to check if a string ends with a char"
1368 declare_clippy_lint! {
1369 /// ### What it does
1370 /// Checks for usage of `.as_ref()` or `.as_mut()` where the
1371 /// types before and after the call are the same.
1373 /// ### Why is this bad?
1374 /// The call is unnecessary.
1378 /// # fn do_stuff(x: &[i32]) {}
1379 /// let x: &[i32] = &[1, 2, 3, 4, 5];
1380 /// do_stuff(x.as_ref());
1382 /// The correct use would be:
1384 /// # fn do_stuff(x: &[i32]) {}
1385 /// let x: &[i32] = &[1, 2, 3, 4, 5];
1388 #[clippy::version = "pre 1.29.0"]
1391 "using `as_ref` where the types before and after the call are the same"
1394 declare_clippy_lint! {
1395 /// ### What it does
1396 /// Checks for using `fold` when a more succinct alternative exists.
1397 /// Specifically, this checks for `fold`s which could be replaced by `any`, `all`,
1398 /// `sum` or `product`.
1400 /// ### Why is this bad?
1405 /// let _ = (0..3).fold(false, |acc, x| acc || x > 2);
1407 /// This could be written as:
1409 /// let _ = (0..3).any(|x| x > 2);
1411 #[clippy::version = "pre 1.29.0"]
1412 pub UNNECESSARY_FOLD,
1414 "using `fold` when a more succinct alternative exists"
1417 declare_clippy_lint! {
1418 /// ### What it does
1419 /// Checks for `filter_map` calls that could be replaced by `filter` or `map`.
1420 /// More specifically it checks if the closure provided is only performing one of the
1421 /// filter or map operations and suggests the appropriate option.
1423 /// ### Why is this bad?
1424 /// Complexity. The intent is also clearer if only a single
1425 /// operation is being performed.
1429 /// let _ = (0..3).filter_map(|x| if x > 2 { Some(x) } else { None });
1431 /// // As there is no transformation of the argument this could be written as:
1432 /// let _ = (0..3).filter(|&x| x > 2);
1436 /// let _ = (0..4).filter_map(|x| Some(x + 1));
1438 /// // As there is no conditional check on the argument this could be written as:
1439 /// let _ = (0..4).map(|x| x + 1);
1441 #[clippy::version = "1.31.0"]
1442 pub UNNECESSARY_FILTER_MAP,
1444 "using `filter_map` when a more succinct alternative exists"
1447 declare_clippy_lint! {
1448 /// ### What it does
1449 /// Checks for `find_map` calls that could be replaced by `find` or `map`. More
1450 /// specifically it checks if the closure provided is only performing one of the
1451 /// find or map operations and suggests the appropriate option.
1453 /// ### Why is this bad?
1454 /// Complexity. The intent is also clearer if only a single
1455 /// operation is being performed.
1459 /// let _ = (0..3).find_map(|x| if x > 2 { Some(x) } else { None });
1461 /// // As there is no transformation of the argument this could be written as:
1462 /// let _ = (0..3).find(|&x| x > 2);
1466 /// let _ = (0..4).find_map(|x| Some(x + 1));
1468 /// // As there is no conditional check on the argument this could be written as:
1469 /// let _ = (0..4).map(|x| x + 1).next();
1471 #[clippy::version = "1.61.0"]
1472 pub UNNECESSARY_FIND_MAP,
1474 "using `find_map` when a more succinct alternative exists"
1477 declare_clippy_lint! {
1478 /// ### What it does
1479 /// Checks for `into_iter` calls on references which should be replaced by `iter`
1482 /// ### Why is this bad?
1483 /// Readability. Calling `into_iter` on a reference will not move out its
1484 /// content into the resulting iterator, which is confusing. It is better just call `iter` or
1485 /// `iter_mut` directly.
1490 /// let _ = (&vec![3, 4, 5]).into_iter();
1493 /// let _ = (&vec![3, 4, 5]).iter();
1495 #[clippy::version = "1.32.0"]
1496 pub INTO_ITER_ON_REF,
1498 "using `.into_iter()` on a reference"
1501 declare_clippy_lint! {
1502 /// ### What it does
1503 /// Checks for calls to `map` followed by a `count`.
1505 /// ### Why is this bad?
1506 /// It looks suspicious. Maybe `map` was confused with `filter`.
1507 /// If the `map` call is intentional, this should be rewritten
1508 /// using `inspect`. Or, if you intend to drive the iterator to
1509 /// completion, you can just use `for_each` instead.
1513 /// let _ = (0..3).map(|x| x + 2).count();
1515 #[clippy::version = "1.39.0"]
1518 "suspicious usage of map"
1521 declare_clippy_lint! {
1522 /// ### What it does
1523 /// Checks for `MaybeUninit::uninit().assume_init()`.
1525 /// ### Why is this bad?
1526 /// For most types, this is undefined behavior.
1528 /// ### Known problems
1529 /// For now, we accept empty tuples and tuples / arrays
1530 /// of `MaybeUninit`. There may be other types that allow uninitialized
1531 /// data, but those are not yet rigorously defined.
1535 /// // Beware the UB
1536 /// use std::mem::MaybeUninit;
1538 /// let _: usize = unsafe { MaybeUninit::uninit().assume_init() };
1541 /// Note that the following is OK:
1544 /// use std::mem::MaybeUninit;
1546 /// let _: [MaybeUninit<bool>; 5] = unsafe {
1547 /// MaybeUninit::uninit().assume_init()
1550 #[clippy::version = "1.39.0"]
1551 pub UNINIT_ASSUMED_INIT,
1553 "`MaybeUninit::uninit().assume_init()`"
1556 declare_clippy_lint! {
1557 /// ### What it does
1558 /// Checks for `.checked_add/sub(x).unwrap_or(MAX/MIN)`.
1560 /// ### Why is this bad?
1561 /// These can be written simply with `saturating_add/sub` methods.
1565 /// # let y: u32 = 0;
1566 /// # let x: u32 = 100;
1567 /// let add = x.checked_add(y).unwrap_or(u32::MAX);
1568 /// let sub = x.checked_sub(y).unwrap_or(u32::MIN);
1571 /// can be written using dedicated methods for saturating addition/subtraction as:
1574 /// # let y: u32 = 0;
1575 /// # let x: u32 = 100;
1576 /// let add = x.saturating_add(y);
1577 /// let sub = x.saturating_sub(y);
1579 #[clippy::version = "1.39.0"]
1580 pub MANUAL_SATURATING_ARITHMETIC,
1582 "`.checked_add/sub(x).unwrap_or(MAX/MIN)`"
1585 declare_clippy_lint! {
1586 /// ### What it does
1587 /// Checks for `offset(_)`, `wrapping_`{`add`, `sub`}, etc. on raw pointers to
1588 /// zero-sized types
1590 /// ### Why is this bad?
1591 /// This is a no-op, and likely unintended
1595 /// unsafe { (&() as *const ()).offset(1) };
1597 #[clippy::version = "1.41.0"]
1600 "Check for offset calculations on raw pointers to zero-sized types"
1603 declare_clippy_lint! {
1604 /// ### What it does
1605 /// Checks for `FileType::is_file()`.
1607 /// ### Why is this bad?
1608 /// When people testing a file type with `FileType::is_file`
1609 /// they are testing whether a path is something they can get bytes from. But
1610 /// `is_file` doesn't cover special file types in unix-like systems, and doesn't cover
1611 /// symlink in windows. Using `!FileType::is_dir()` is a better way to that intention.
1616 /// let metadata = std::fs::metadata("foo.txt")?;
1617 /// let filetype = metadata.file_type();
1619 /// if filetype.is_file() {
1622 /// # Ok::<_, std::io::Error>(())
1626 /// should be written as:
1630 /// let metadata = std::fs::metadata("foo.txt")?;
1631 /// let filetype = metadata.file_type();
1633 /// if !filetype.is_dir() {
1636 /// # Ok::<_, std::io::Error>(())
1639 #[clippy::version = "1.42.0"]
1640 pub FILETYPE_IS_FILE,
1642 "`FileType::is_file` is not recommended to test for readable file type"
1645 declare_clippy_lint! {
1646 /// ### What it does
1647 /// Checks for usage of `_.as_ref().map(Deref::deref)` or it's aliases (such as String::as_str).
1649 /// ### Why is this bad?
1650 /// Readability, this can be written more concisely as
1655 /// # let opt = Some("".to_string());
1656 /// opt.as_ref().map(String::as_str)
1659 /// Can be written as
1661 /// # let opt = Some("".to_string());
1665 #[clippy::version = "1.42.0"]
1666 pub OPTION_AS_REF_DEREF,
1668 "using `as_ref().map(Deref::deref)`, which is more succinctly expressed as `as_deref()`"
1671 declare_clippy_lint! {
1672 /// ### What it does
1673 /// Checks for usage of `iter().next()` on a Slice or an Array
1675 /// ### Why is this bad?
1676 /// These can be shortened into `.get()`
1680 /// # let a = [1, 2, 3];
1681 /// # let b = vec![1, 2, 3];
1682 /// a[2..].iter().next();
1683 /// b.iter().next();
1685 /// should be written as:
1687 /// # let a = [1, 2, 3];
1688 /// # let b = vec![1, 2, 3];
1692 #[clippy::version = "1.46.0"]
1693 pub ITER_NEXT_SLICE,
1695 "using `.iter().next()` on a sliced array, which can be shortened to just `.get()`"
1698 declare_clippy_lint! {
1699 /// ### What it does
1700 /// Warns when using `push_str`/`insert_str` with a single-character string literal
1701 /// where `push`/`insert` with a `char` would work fine.
1703 /// ### Why is this bad?
1704 /// It's less clear that we are pushing a single character.
1708 /// let mut string = String::new();
1709 /// string.insert_str(0, "R");
1710 /// string.push_str("R");
1712 /// Could be written as
1714 /// let mut string = String::new();
1715 /// string.insert(0, 'R');
1716 /// string.push('R');
1718 #[clippy::version = "1.49.0"]
1719 pub SINGLE_CHAR_ADD_STR,
1721 "`push_str()` or `insert_str()` used with a single-character string literal as parameter"
1724 declare_clippy_lint! {
1725 /// ### What it does
1726 /// As the counterpart to `or_fun_call`, this lint looks for unnecessary
1727 /// lazily evaluated closures on `Option` and `Result`.
1729 /// This lint suggests changing the following functions, when eager evaluation results in
1731 /// - `unwrap_or_else` to `unwrap_or`
1732 /// - `and_then` to `and`
1733 /// - `or_else` to `or`
1734 /// - `get_or_insert_with` to `get_or_insert`
1735 /// - `ok_or_else` to `ok_or`
1737 /// ### Why is this bad?
1738 /// Using eager evaluation is shorter and simpler in some cases.
1740 /// ### Known problems
1741 /// It is possible, but not recommended for `Deref` and `Index` to have
1742 /// side effects. Eagerly evaluating them can change the semantics of the program.
1746 /// // example code where clippy issues a warning
1747 /// let opt: Option<u32> = None;
1749 /// opt.unwrap_or_else(|| 42);
1753 /// let opt: Option<u32> = None;
1755 /// opt.unwrap_or(42);
1757 #[clippy::version = "1.48.0"]
1758 pub UNNECESSARY_LAZY_EVALUATIONS,
1760 "using unnecessary lazy evaluation, which can be replaced with simpler eager evaluation"
1763 declare_clippy_lint! {
1764 /// ### What it does
1765 /// Checks for usage of `_.map(_).collect::<Result<(), _>()`.
1767 /// ### Why is this bad?
1768 /// Using `try_for_each` instead is more readable and idiomatic.
1772 /// (0..3).map(|t| Err(t)).collect::<Result<(), _>>();
1776 /// (0..3).try_for_each(|t| Err(t));
1778 #[clippy::version = "1.49.0"]
1779 pub MAP_COLLECT_RESULT_UNIT,
1781 "using `.map(_).collect::<Result<(),_>()`, which can be replaced with `try_for_each`"
1784 declare_clippy_lint! {
1785 /// ### What it does
1786 /// Checks for `from_iter()` function calls on types that implement the `FromIterator`
1789 /// ### Why is this bad?
1790 /// It is recommended style to use collect. See
1791 /// [FromIterator documentation](https://doc.rust-lang.org/std/iter/trait.FromIterator.html)
1795 /// let five_fives = std::iter::repeat(5).take(5);
1797 /// let v = Vec::from_iter(five_fives);
1799 /// assert_eq!(v, vec![5, 5, 5, 5, 5]);
1803 /// let five_fives = std::iter::repeat(5).take(5);
1805 /// let v: Vec<i32> = five_fives.collect();
1807 /// assert_eq!(v, vec![5, 5, 5, 5, 5]);
1809 #[clippy::version = "1.49.0"]
1810 pub FROM_ITER_INSTEAD_OF_COLLECT,
1812 "use `.collect()` instead of `::from_iter()`"
1815 declare_clippy_lint! {
1816 /// ### What it does
1817 /// Checks for usage of `inspect().for_each()`.
1819 /// ### Why is this bad?
1820 /// It is the same as performing the computation
1821 /// inside `inspect` at the beginning of the closure in `for_each`.
1825 /// [1,2,3,4,5].iter()
1826 /// .inspect(|&x| println!("inspect the number: {}", x))
1827 /// .for_each(|&x| {
1828 /// assert!(x >= 0);
1831 /// Can be written as
1833 /// [1,2,3,4,5].iter()
1834 /// .for_each(|&x| {
1835 /// println!("inspect the number: {}", x);
1836 /// assert!(x >= 0);
1839 #[clippy::version = "1.51.0"]
1840 pub INSPECT_FOR_EACH,
1842 "using `.inspect().for_each()`, which can be replaced with `.for_each()`"
1845 declare_clippy_lint! {
1846 /// ### What it does
1847 /// Checks for usage of `filter_map(|x| x)`.
1849 /// ### Why is this bad?
1850 /// Readability, this can be written more concisely by using `flatten`.
1854 /// # let iter = vec![Some(1)].into_iter();
1855 /// iter.filter_map(|x| x);
1859 /// # let iter = vec![Some(1)].into_iter();
1862 #[clippy::version = "1.52.0"]
1863 pub FILTER_MAP_IDENTITY,
1865 "call to `filter_map` where `flatten` is sufficient"
1868 declare_clippy_lint! {
1869 /// ### What it does
1870 /// Checks for instances of `map(f)` where `f` is the identity function.
1872 /// ### Why is this bad?
1873 /// It can be written more concisely without the call to `map`.
1877 /// let x = [1, 2, 3];
1878 /// let y: Vec<_> = x.iter().map(|x| x).map(|x| 2*x).collect();
1882 /// let x = [1, 2, 3];
1883 /// let y: Vec<_> = x.iter().map(|x| 2*x).collect();
1885 #[clippy::version = "1.52.0"]
1888 "using iterator.map(|x| x)"
1891 declare_clippy_lint! {
1892 /// ### What it does
1893 /// Checks for the use of `.bytes().nth()`.
1895 /// ### Why is this bad?
1896 /// `.as_bytes().get()` is more efficient and more
1902 /// let _ = "Hello".bytes().nth(3);
1905 /// let _ = "Hello".as_bytes().get(3);
1907 #[clippy::version = "1.52.0"]
1910 "replace `.bytes().nth()` with `.as_bytes().get()`"
1913 declare_clippy_lint! {
1914 /// ### What it does
1915 /// Checks for the usage of `_.to_owned()`, `vec.to_vec()`, or similar when calling `_.clone()` would be clearer.
1917 /// ### Why is this bad?
1918 /// These methods do the same thing as `_.clone()` but may be confusing as
1919 /// to why we are calling `to_vec` on something that is already a `Vec` or calling `to_owned` on something that is already owned.
1923 /// let a = vec![1, 2, 3];
1924 /// let b = a.to_vec();
1925 /// let c = a.to_owned();
1929 /// let a = vec![1, 2, 3];
1930 /// let b = a.clone();
1931 /// let c = a.clone();
1933 #[clippy::version = "1.52.0"]
1936 "implicitly cloning a value by invoking a function on its dereferenced type"
1939 declare_clippy_lint! {
1940 /// ### What it does
1941 /// Checks for the use of `.iter().count()`.
1943 /// ### Why is this bad?
1944 /// `.len()` is more efficient and more
1950 /// let some_vec = vec![0, 1, 2, 3];
1951 /// let _ = some_vec.iter().count();
1952 /// let _ = &some_vec[..].iter().count();
1955 /// let some_vec = vec![0, 1, 2, 3];
1956 /// let _ = some_vec.len();
1957 /// let _ = &some_vec[..].len();
1959 #[clippy::version = "1.52.0"]
1962 "replace `.iter().count()` with `.len()`"
1965 declare_clippy_lint! {
1966 /// ### What it does
1967 /// Checks for calls to [`splitn`]
1968 /// (https://doc.rust-lang.org/std/primitive.str.html#method.splitn) and
1969 /// related functions with either zero or one splits.
1971 /// ### Why is this bad?
1972 /// These calls don't actually split the value and are
1973 /// likely to be intended as a different number.
1979 /// for x in s.splitn(1, ":") {
1985 /// for x in s.splitn(2, ":") {
1989 #[clippy::version = "1.54.0"]
1990 pub SUSPICIOUS_SPLITN,
1992 "checks for `.splitn(0, ..)` and `.splitn(1, ..)`"
1995 declare_clippy_lint! {
1996 /// ### What it does
1997 /// Checks for manual implementations of `str::repeat`
1999 /// ### Why is this bad?
2000 /// These are both harder to read, as well as less performant.
2005 /// let x: String = std::iter::repeat('x').take(10).collect();
2008 /// let x: String = "x".repeat(10);
2010 #[clippy::version = "1.54.0"]
2011 pub MANUAL_STR_REPEAT,
2013 "manual implementation of `str::repeat`"
2016 declare_clippy_lint! {
2017 /// ### What it does
2018 /// Checks for usages of `str::splitn(2, _)`
2020 /// ### Why is this bad?
2021 /// `split_once` is both clearer in intent and slightly more efficient.
2026 /// let s = "key=value=add";
2027 /// let (key, value) = s.splitn(2, '=').next_tuple()?;
2028 /// let value = s.splitn(2, '=').nth(1)?;
2030 /// let mut parts = s.splitn(2, '=');
2031 /// let key = parts.next()?;
2032 /// let value = parts.next()?;
2037 /// let s = "key=value=add";
2038 /// let (key, value) = s.split_once('=')?;
2039 /// let value = s.split_once('=')?.1;
2041 /// let (key, value) = s.split_once('=')?;
2045 /// The multiple statement variant currently only detects `iter.next()?`/`iter.next().unwrap()`
2046 /// in two separate `let` statements that immediately follow the `splitn()`
2047 #[clippy::version = "1.57.0"]
2048 pub MANUAL_SPLIT_ONCE,
2050 "replace `.splitn(2, pat)` with `.split_once(pat)`"
2053 declare_clippy_lint! {
2054 /// ### What it does
2055 /// Checks for usages of `str::splitn` (or `str::rsplitn`) where using `str::split` would be the same.
2056 /// ### Why is this bad?
2057 /// The function `split` is simpler and there is no performance difference in these cases, considering
2058 /// that both functions return a lazy iterator.
2062 /// let str = "key=value=add";
2063 /// let _ = str.splitn(3, '=').next().unwrap();
2068 /// let str = "key=value=add";
2069 /// let _ = str.split('=').next().unwrap();
2071 #[clippy::version = "1.58.0"]
2072 pub NEEDLESS_SPLITN,
2074 "usages of `str::splitn` that can be replaced with `str::split`"
2077 declare_clippy_lint! {
2078 /// ### What it does
2079 /// Checks for unnecessary calls to [`ToOwned::to_owned`](https://doc.rust-lang.org/std/borrow/trait.ToOwned.html#tymethod.to_owned)
2080 /// and other `to_owned`-like functions.
2082 /// ### Why is this bad?
2083 /// The unnecessary calls result in useless allocations.
2085 /// ### Known problems
2086 /// `unnecessary_to_owned` can falsely trigger if `IntoIterator::into_iter` is applied to an
2087 /// owned copy of a resource and the resource is later used mutably. See
2088 /// [#8148](https://github.com/rust-lang/rust-clippy/issues/8148).
2092 /// let path = std::path::Path::new("x");
2093 /// foo(&path.to_string_lossy().to_string());
2094 /// fn foo(s: &str) {}
2098 /// let path = std::path::Path::new("x");
2099 /// foo(&path.to_string_lossy());
2100 /// fn foo(s: &str) {}
2102 #[clippy::version = "1.58.0"]
2103 pub UNNECESSARY_TO_OWNED,
2105 "unnecessary calls to `to_owned`-like functions"
2108 declare_clippy_lint! {
2109 /// ### What it does
2110 /// Checks for use of `.collect::<Vec<String>>().join("")` on iterators.
2112 /// ### Why is this bad?
2113 /// `.collect::<String>()` is more concise and might be more performant
2117 /// let vector = vec!["hello", "world"];
2118 /// let output = vector.iter().map(|item| item.to_uppercase()).collect::<Vec<String>>().join("");
2119 /// println!("{}", output);
2121 /// The correct use would be:
2123 /// let vector = vec!["hello", "world"];
2124 /// let output = vector.iter().map(|item| item.to_uppercase()).collect::<String>();
2125 /// println!("{}", output);
2127 /// ### Known problems
2128 /// While `.collect::<String>()` is sometimes more performant, there are cases where
2129 /// using `.collect::<String>()` over `.collect::<Vec<String>>().join("")`
2130 /// will prevent loop unrolling and will result in a negative performance impact.
2132 /// Additionally, differences have been observed between aarch64 and x86_64 assembly output,
2133 /// with aarch64 tending to producing faster assembly in more cases when using `.collect::<String>()`
2134 #[clippy::version = "1.61.0"]
2135 pub UNNECESSARY_JOIN,
2137 "using `.collect::<Vec<String>>().join(\"\")` on an iterator"
2140 declare_clippy_lint! {
2141 /// ### What it does
2142 /// Checks for no-op uses of `Option::{as_deref, as_deref_mut}`,
2143 /// for example, `Option<&T>::as_deref()` returns the same type.
2145 /// ### Why is this bad?
2146 /// Redundant code and improving readability.
2150 /// let a = Some(&1);
2151 /// let b = a.as_deref(); // goes from Option<&i32> to Option<&i32>
2153 /// Could be written as:
2155 /// let a = Some(&1);
2158 #[clippy::version = "1.57.0"]
2159 pub NEEDLESS_OPTION_AS_DEREF,
2161 "no-op use of `deref` or `deref_mut` method to `Option`."
2164 declare_clippy_lint! {
2165 /// ### What it does
2166 /// Finds usages of [`char::is_digit`]
2167 /// (https://doc.rust-lang.org/stable/std/primitive.char.html#method.is_digit) that
2168 /// can be replaced with [`is_ascii_digit`]
2169 /// (https://doc.rust-lang.org/stable/std/primitive.char.html#method.is_ascii_digit) or
2170 /// [`is_ascii_hexdigit`]
2171 /// (https://doc.rust-lang.org/stable/std/primitive.char.html#method.is_ascii_hexdigit).
2173 /// ### Why is this bad?
2174 /// `is_digit(..)` is slower and requires specifying the radix.
2178 /// let c: char = '6';
2184 /// let c: char = '6';
2185 /// c.is_ascii_digit();
2186 /// c.is_ascii_hexdigit();
2188 #[clippy::version = "1.61.0"]
2189 pub IS_DIGIT_ASCII_RADIX,
2191 "use of `char::is_digit(..)` with literal radix of 10 or 16"
2194 declare_clippy_lint! {
2196 /// ### Why is this bad?
2200 /// let x = Some(3);
2201 /// x.as_ref().take();
2205 /// let x = Some(3);
2208 #[clippy::version = "1.61.0"]
2209 pub NEEDLESS_OPTION_TAKE,
2211 "using `.as_ref().take()` on a temporary value"
2214 declare_clippy_lint! {
2215 /// ### What it does
2216 /// Checks for `replace` statements which have no effect.
2218 /// ### Why is this bad?
2219 /// It's either a mistake or confusing.
2223 /// "1234".replace("12", "12");
2224 /// "1234".replacen("12", "12", 1);
2226 #[clippy::version = "1.62.0"]
2227 pub NO_EFFECT_REPLACE,
2229 "replace with no effect"
2232 pub struct Methods {
2233 avoid_breaking_exported_api: bool,
2234 msrv: Option<RustcVersion>,
2235 allow_expect_in_tests: bool,
2236 allow_unwrap_in_tests: bool,
2242 avoid_breaking_exported_api: bool,
2243 msrv: Option<RustcVersion>,
2244 allow_expect_in_tests: bool,
2245 allow_unwrap_in_tests: bool,
2248 avoid_breaking_exported_api,
2250 allow_expect_in_tests,
2251 allow_unwrap_in_tests,
2256 impl_lint_pass!(Methods => [
2259 SHOULD_IMPLEMENT_TRAIT,
2260 WRONG_SELF_CONVENTION,
2262 UNWRAP_OR_ELSE_DEFAULT,
2264 RESULT_MAP_OR_INTO_OPTION,
2266 BIND_INSTEAD_OF_MAP,
2275 ITER_OVEREAGER_CLONED,
2276 CLONED_INSTEAD_OF_COPIED,
2278 INEFFICIENT_TO_STRING,
2280 SINGLE_CHAR_PATTERN,
2281 SINGLE_CHAR_ADD_STR,
2285 FILTER_MAP_IDENTITY,
2293 ITERATOR_STEP_BY_ZERO,
2302 STRING_EXTEND_CHARS,
2303 ITER_CLONED_COLLECT,
2307 UNNECESSARY_FILTER_MAP,
2308 UNNECESSARY_FIND_MAP,
2311 UNINIT_ASSUMED_INIT,
2312 MANUAL_SATURATING_ARITHMETIC,
2315 OPTION_AS_REF_DEREF,
2316 UNNECESSARY_LAZY_EVALUATIONS,
2317 MAP_COLLECT_RESULT_UNIT,
2318 FROM_ITER_INSTEAD_OF_COLLECT,
2326 UNNECESSARY_TO_OWNED,
2329 NEEDLESS_OPTION_AS_DEREF,
2330 IS_DIGIT_ASCII_RADIX,
2331 NEEDLESS_OPTION_TAKE,
2335 /// Extracts a method call name, args, and `Span` of the method name.
2336 fn method_call<'tcx>(recv: &'tcx hir::Expr<'tcx>) -> Option<(&'tcx str, &'tcx [hir::Expr<'tcx>], Span)> {
2337 if let ExprKind::MethodCall(path, args, _) = recv.kind {
2338 if !args.iter().any(|e| e.span.from_expansion()) {
2339 let name = path.ident.name.as_str();
2340 return Some((name, args, path.ident.span));
2346 impl<'tcx> LateLintPass<'tcx> for Methods {
2347 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) {
2348 if expr.span.from_expansion() {
2352 self.check_methods(cx, expr);
2355 hir::ExprKind::Call(func, args) => {
2356 from_iter_instead_of_collect::check(cx, expr, args, func);
2358 hir::ExprKind::MethodCall(method_call, args, _) => {
2359 let method_span = method_call.ident.span;
2360 or_fun_call::check(cx, expr, method_span, method_call.ident.as_str(), args);
2361 expect_fun_call::check(cx, expr, method_span, method_call.ident.as_str(), args);
2362 clone_on_copy::check(cx, expr, method_call.ident.name, args);
2363 clone_on_ref_ptr::check(cx, expr, method_call.ident.name, args);
2364 inefficient_to_string::check(cx, expr, method_call.ident.name, args);
2365 single_char_add_str::check(cx, expr, args);
2366 into_iter_on_ref::check(cx, expr, method_span, method_call.ident.name, args);
2367 single_char_pattern::check(cx, expr, method_call.ident.name, args);
2368 unnecessary_to_owned::check(cx, expr, method_call.ident.name, args, self.msrv);
2370 hir::ExprKind::Binary(op, lhs, rhs) if op.node == hir::BinOpKind::Eq || op.node == hir::BinOpKind::Ne => {
2371 let mut info = BinaryExprInfo {
2375 eq: op.node == hir::BinOpKind::Eq,
2377 lint_binary_expr_with_method_call(cx, &mut info);
2383 #[allow(clippy::too_many_lines)]
2384 fn check_impl_item(&mut self, cx: &LateContext<'tcx>, impl_item: &'tcx hir::ImplItem<'_>) {
2385 if in_external_macro(cx.sess(), impl_item.span) {
2388 let name = impl_item.ident.name.as_str();
2389 let parent = cx.tcx.hir().get_parent_item(impl_item.hir_id());
2390 let item = cx.tcx.hir().expect_item(parent);
2391 let self_ty = cx.tcx.type_of(item.def_id);
2393 let implements_trait = matches!(item.kind, hir::ItemKind::Impl(hir::Impl { of_trait: Some(_), .. }));
2395 if let hir::ImplItemKind::Fn(ref sig, id) = impl_item.kind;
2396 if let Some(first_arg) = iter_input_pats(sig.decl, cx.tcx.hir().body(id)).next();
2398 let method_sig = cx.tcx.fn_sig(impl_item.def_id);
2399 let method_sig = cx.tcx.erase_late_bound_regions(method_sig);
2401 let first_arg_ty = method_sig.inputs().iter().next();
2403 // check conventions w.r.t. conversion method names and predicates
2404 if let Some(first_arg_ty) = first_arg_ty;
2407 // if this impl block implements a trait, lint in trait definition instead
2408 if !implements_trait && cx.access_levels.is_exported(impl_item.def_id) {
2409 // check missing trait implementations
2410 for method_config in &TRAIT_METHODS {
2411 if name == method_config.method_name &&
2412 sig.decl.inputs.len() == method_config.param_count &&
2413 method_config.output_type.matches(&sig.decl.output) &&
2414 method_config.self_kind.matches(cx, self_ty, *first_arg_ty) &&
2415 fn_header_equals(method_config.fn_header, sig.header) &&
2416 method_config.lifetime_param_cond(impl_item)
2420 SHOULD_IMPLEMENT_TRAIT,
2423 "method `{}` can be confused for the standard trait method `{}::{}`",
2424 method_config.method_name,
2425 method_config.trait_name,
2426 method_config.method_name
2430 "consider implementing the trait `{}` or choosing a less ambiguous method name",
2431 method_config.trait_name
2438 if sig.decl.implicit_self.has_implicit_self()
2439 && !(self.avoid_breaking_exported_api
2440 && cx.access_levels.is_exported(impl_item.def_id))
2442 wrong_self_convention::check(
2455 // if this impl block implements a trait, lint in trait definition instead
2456 if implements_trait {
2460 if let hir::ImplItemKind::Fn(_, _) = impl_item.kind {
2461 let ret_ty = return_ty(cx, impl_item.hir_id());
2463 // walk the return type and check for Self (this does not check associated types)
2464 if let Some(self_adt) = self_ty.ty_adt_def() {
2465 if contains_adt_constructor(ret_ty, self_adt) {
2468 } else if contains_ty(ret_ty, self_ty) {
2472 // if return type is impl trait, check the associated types
2473 if let ty::Opaque(def_id, _) = *ret_ty.kind() {
2474 // one of the associated types must be Self
2475 for &(predicate, _span) in cx.tcx.explicit_item_bounds(def_id) {
2476 if let ty::PredicateKind::Projection(projection_predicate) = predicate.kind().skip_binder() {
2477 let assoc_ty = match projection_predicate.term {
2478 ty::Term::Ty(ty) => ty,
2479 ty::Term::Const(_c) => continue,
2481 // walk the associated type and check for Self
2482 if let Some(self_adt) = self_ty.ty_adt_def() {
2483 if contains_adt_constructor(assoc_ty, self_adt) {
2486 } else if contains_ty(assoc_ty, self_ty) {
2493 if name == "new" && ret_ty != self_ty {
2498 "methods called `new` usually return `Self`",
2504 fn check_trait_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx TraitItem<'_>) {
2505 if in_external_macro(cx.tcx.sess, item.span) {
2510 if let TraitItemKind::Fn(ref sig, _) = item.kind;
2511 if sig.decl.implicit_self.has_implicit_self();
2512 if let Some(first_arg_ty) = sig.decl.inputs.iter().next();
2515 let first_arg_span = first_arg_ty.span;
2516 let first_arg_ty = hir_ty_to_ty(cx.tcx, first_arg_ty);
2517 let self_ty = TraitRef::identity(cx.tcx, item.def_id.to_def_id()).self_ty().skip_binder();
2518 wrong_self_convention::check(
2520 item.ident.name.as_str(),
2531 if item.ident.name == sym::new;
2532 if let TraitItemKind::Fn(_, _) = item.kind;
2533 let ret_ty = return_ty(cx, item.hir_id());
2534 let self_ty = TraitRef::identity(cx.tcx, item.def_id.to_def_id()).self_ty().skip_binder();
2535 if !contains_ty(ret_ty, self_ty);
2542 "methods called `new` usually return `Self`",
2548 extract_msrv_attr!(LateContext);
2552 #[allow(clippy::too_many_lines)]
2553 fn check_methods<'tcx>(&self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
2554 if let Some((name, [recv, args @ ..], span)) = method_call(expr) {
2555 match (name, args) {
2556 ("add" | "offset" | "sub" | "wrapping_offset" | "wrapping_add" | "wrapping_sub", [_arg]) => {
2557 zst_offset::check(cx, expr, recv);
2559 ("and_then", [arg]) => {
2560 let biom_option_linted = bind_instead_of_map::OptionAndThenSome::check(cx, expr, recv, arg);
2561 let biom_result_linted = bind_instead_of_map::ResultAndThenOk::check(cx, expr, recv, arg);
2562 if !biom_option_linted && !biom_result_linted {
2563 unnecessary_lazy_eval::check(cx, expr, recv, arg, "and");
2566 ("as_deref" | "as_deref_mut", []) => {
2567 needless_option_as_deref::check(cx, expr, recv, name);
2569 ("as_mut", []) => useless_asref::check(cx, expr, "as_mut", recv),
2570 ("as_ref", []) => useless_asref::check(cx, expr, "as_ref", recv),
2571 ("assume_init", []) => uninit_assumed_init::check(cx, expr, recv),
2572 ("cloned", []) => cloned_instead_of_copied::check(cx, expr, recv, span, self.msrv),
2573 ("collect", []) => match method_call(recv) {
2574 Some((name @ ("cloned" | "copied"), [recv2], _)) => {
2575 iter_cloned_collect::check(cx, name, expr, recv2);
2577 Some(("map", [m_recv, m_arg], _)) => {
2578 map_collect_result_unit::check(cx, expr, m_recv, m_arg, recv);
2580 Some(("take", [take_self_arg, take_arg], _)) => {
2581 if meets_msrv(self.msrv, msrvs::STR_REPEAT) {
2582 manual_str_repeat::check(cx, expr, recv, take_self_arg, take_arg);
2587 (name @ "count", args @ []) => match method_call(recv) {
2588 Some(("cloned", [recv2], _)) => iter_overeager_cloned::check(cx, expr, recv2, name, args),
2589 Some((name2 @ ("into_iter" | "iter" | "iter_mut"), [recv2], _)) => {
2590 iter_count::check(cx, expr, recv2, name2);
2592 Some(("map", [_, arg], _)) => suspicious_map::check(cx, expr, recv, arg),
2595 ("drain", [arg]) => {
2596 iter_with_drain::check(cx, expr, recv, span, arg);
2598 ("expect", [_]) => match method_call(recv) {
2599 Some(("ok", [recv], _)) => ok_expect::check(cx, expr, recv),
2600 Some(("err", [recv], err_span)) => err_expect::check(cx, expr, recv, self.msrv, span, err_span),
2601 _ => expect_used::check(cx, expr, recv, self.allow_expect_in_tests),
2603 ("extend", [arg]) => {
2604 string_extend_chars::check(cx, expr, recv, arg);
2605 extend_with_drain::check(cx, expr, recv, arg);
2607 ("filter_map", [arg]) => {
2608 unnecessary_filter_map::check(cx, expr, arg, name);
2609 filter_map_identity::check(cx, expr, arg, span);
2611 ("find_map", [arg]) => {
2612 unnecessary_filter_map::check(cx, expr, arg, name);
2614 ("flat_map", [arg]) => {
2615 flat_map_identity::check(cx, expr, arg, span);
2616 flat_map_option::check(cx, expr, arg, span);
2618 (name @ "flatten", args @ []) => match method_call(recv) {
2619 Some(("map", [recv, map_arg], map_span)) => map_flatten::check(cx, expr, recv, map_arg, map_span),
2620 Some(("cloned", [recv2], _)) => iter_overeager_cloned::check(cx, expr, recv2, name, args),
2623 ("fold", [init, acc]) => unnecessary_fold::check(cx, expr, init, acc, span),
2624 ("for_each", [_]) => {
2625 if let Some(("inspect", [_, _], span2)) = method_call(recv) {
2626 inspect_for_each::check(cx, expr, span2);
2629 ("get", [arg]) => get_last_with_len::check(cx, expr, recv, arg),
2630 ("get_or_insert_with", [arg]) => unnecessary_lazy_eval::check(cx, expr, recv, arg, "get_or_insert"),
2631 ("is_file", []) => filetype_is_file::check(cx, expr, recv),
2632 ("is_digit", [radix]) => is_digit_ascii_radix::check(cx, expr, recv, radix, self.msrv),
2633 ("is_none", []) => check_is_some_is_none(cx, expr, recv, false),
2634 ("is_some", []) => check_is_some_is_none(cx, expr, recv, true),
2635 ("join", [join_arg]) => {
2636 if let Some(("collect", _, span)) = method_call(recv) {
2637 unnecessary_join::check(cx, expr, recv, join_arg, span);
2640 ("last", args @ []) | ("skip", args @ [_]) => {
2641 if let Some((name2, [recv2, args2 @ ..], _span2)) = method_call(recv) {
2642 if let ("cloned", []) = (name2, args2) {
2643 iter_overeager_cloned::check(cx, expr, recv2, name, args);
2647 (name @ ("map" | "map_err"), [m_arg]) => {
2648 if let Some((name, [recv2, args @ ..], span2)) = method_call(recv) {
2649 match (name, args) {
2650 ("as_mut", []) => option_as_ref_deref::check(cx, expr, recv2, m_arg, true, self.msrv),
2651 ("as_ref", []) => option_as_ref_deref::check(cx, expr, recv2, m_arg, false, self.msrv),
2652 ("filter", [f_arg]) => {
2653 filter_map::check(cx, expr, recv2, f_arg, span2, recv, m_arg, span, false);
2655 ("find", [f_arg]) => {
2656 filter_map::check(cx, expr, recv2, f_arg, span2, recv, m_arg, span, true);
2661 map_identity::check(cx, expr, recv, m_arg, name, span);
2663 ("map_or", [def, map]) => option_map_or_none::check(cx, expr, recv, def, map),
2664 (name @ "next", args @ []) => {
2665 if let Some((name2, [recv2, args2 @ ..], _)) = method_call(recv) {
2666 match (name2, args2) {
2667 ("cloned", []) => iter_overeager_cloned::check(cx, expr, recv2, name, args),
2668 ("filter", [arg]) => filter_next::check(cx, expr, recv2, arg),
2669 ("filter_map", [arg]) => filter_map_next::check(cx, expr, recv2, arg, self.msrv),
2670 ("iter", []) => iter_next_slice::check(cx, expr, recv2),
2671 ("skip", [arg]) => iter_skip_next::check(cx, expr, recv2, arg),
2672 ("skip_while", [_]) => skip_while_next::check(cx, expr),
2677 ("nth", args @ [n_arg]) => match method_call(recv) {
2678 Some(("bytes", [recv2], _)) => bytes_nth::check(cx, expr, recv2, n_arg),
2679 Some(("cloned", [recv2], _)) => iter_overeager_cloned::check(cx, expr, recv2, name, args),
2680 Some(("iter", [recv2], _)) => iter_nth::check(cx, expr, recv2, recv, n_arg, false),
2681 Some(("iter_mut", [recv2], _)) => iter_nth::check(cx, expr, recv2, recv, n_arg, true),
2682 _ => iter_nth_zero::check(cx, expr, recv, n_arg),
2684 ("ok_or_else", [arg]) => unnecessary_lazy_eval::check(cx, expr, recv, arg, "ok_or"),
2685 ("or_else", [arg]) => {
2686 if !bind_instead_of_map::ResultOrElseErrInfo::check(cx, expr, recv, arg) {
2687 unnecessary_lazy_eval::check(cx, expr, recv, arg, "or");
2690 ("splitn" | "rsplitn", [count_arg, pat_arg]) => {
2691 if let Some((Constant::Int(count), _)) = constant(cx, cx.typeck_results(), count_arg) {
2692 suspicious_splitn::check(cx, name, expr, recv, count);
2693 str_splitn::check(cx, name, expr, recv, pat_arg, count, self.msrv);
2696 ("splitn_mut" | "rsplitn_mut", [count_arg, _]) => {
2697 if let Some((Constant::Int(count), _)) = constant(cx, cx.typeck_results(), count_arg) {
2698 suspicious_splitn::check(cx, name, expr, recv, count);
2701 ("step_by", [arg]) => iterator_step_by_zero::check(cx, expr, arg),
2702 ("take", args @ [_arg]) => {
2703 if let Some((name2, [recv2, args2 @ ..], _span2)) = method_call(recv) {
2704 if let ("cloned", []) = (name2, args2) {
2705 iter_overeager_cloned::check(cx, expr, recv2, name, args);
2709 ("take", []) => needless_option_take::check(cx, expr, recv),
2710 ("to_os_string" | "to_owned" | "to_path_buf" | "to_vec", []) => {
2711 implicit_clone::check(cx, name, expr, recv);
2714 match method_call(recv) {
2715 Some(("get", [recv, get_arg], _)) => {
2716 get_unwrap::check(cx, expr, recv, get_arg, false);
2718 Some(("get_mut", [recv, get_arg], _)) => {
2719 get_unwrap::check(cx, expr, recv, get_arg, true);
2721 Some(("or", [recv, or_arg], or_span)) => {
2722 or_then_unwrap::check(cx, expr, recv, or_arg, or_span);
2726 unwrap_used::check(cx, expr, recv, self.allow_unwrap_in_tests);
2728 ("unwrap_or", [u_arg]) => match method_call(recv) {
2729 Some((arith @ ("checked_add" | "checked_sub" | "checked_mul"), [lhs, rhs], _)) => {
2730 manual_saturating_arithmetic::check(cx, expr, lhs, rhs, u_arg, &arith["checked_".len()..]);
2732 Some(("map", [m_recv, m_arg], span)) => {
2733 option_map_unwrap_or::check(cx, expr, m_recv, m_arg, recv, u_arg, span);
2737 ("unwrap_or_else", [u_arg]) => match method_call(recv) {
2738 Some(("map", [recv, map_arg], _))
2739 if map_unwrap_or::check(cx, expr, recv, map_arg, u_arg, self.msrv) => {},
2741 unwrap_or_else_default::check(cx, expr, recv, u_arg);
2742 unnecessary_lazy_eval::check(cx, expr, recv, u_arg, "unwrap_or");
2745 ("replace" | "replacen", [arg1, arg2] | [arg1, arg2, _]) => {
2746 no_effect_replace::check(cx, expr, arg1, arg2);
2754 fn check_is_some_is_none(cx: &LateContext<'_>, expr: &Expr<'_>, recv: &Expr<'_>, is_some: bool) {
2755 if let Some((name @ ("find" | "position" | "rposition"), [f_recv, arg], span)) = method_call(recv) {
2756 search_is_some::check(cx, expr, name, is_some, f_recv, arg, recv, span);
2760 /// Used for `lint_binary_expr_with_method_call`.
2761 #[derive(Copy, Clone)]
2762 struct BinaryExprInfo<'a> {
2763 expr: &'a hir::Expr<'a>,
2764 chain: &'a hir::Expr<'a>,
2765 other: &'a hir::Expr<'a>,
2769 /// Checks for the `CHARS_NEXT_CMP` and `CHARS_LAST_CMP` lints.
2770 fn lint_binary_expr_with_method_call(cx: &LateContext<'_>, info: &mut BinaryExprInfo<'_>) {
2771 macro_rules! lint_with_both_lhs_and_rhs {
2772 ($func:expr, $cx:expr, $info:ident) => {
2773 if !$func($cx, $info) {
2774 ::std::mem::swap(&mut $info.chain, &mut $info.other);
2775 if $func($cx, $info) {
2782 lint_with_both_lhs_and_rhs!(chars_next_cmp::check, cx, info);
2783 lint_with_both_lhs_and_rhs!(chars_last_cmp::check, cx, info);
2784 lint_with_both_lhs_and_rhs!(chars_next_cmp_with_unwrap::check, cx, info);
2785 lint_with_both_lhs_and_rhs!(chars_last_cmp_with_unwrap::check, cx, info);
2788 const FN_HEADER: hir::FnHeader = hir::FnHeader {
2789 unsafety: hir::Unsafety::Normal,
2790 constness: hir::Constness::NotConst,
2791 asyncness: hir::IsAsync::NotAsync,
2792 abi: rustc_target::spec::abi::Abi::Rust,
2795 struct ShouldImplTraitCase {
2796 trait_name: &'static str,
2797 method_name: &'static str,
2799 fn_header: hir::FnHeader,
2800 // implicit self kind expected (none, self, &self, ...)
2801 self_kind: SelfKind,
2802 // checks against the output type
2803 output_type: OutType,
2804 // certain methods with explicit lifetimes can't implement the equivalent trait method
2805 lint_explicit_lifetime: bool,
2807 impl ShouldImplTraitCase {
2809 trait_name: &'static str,
2810 method_name: &'static str,
2812 fn_header: hir::FnHeader,
2813 self_kind: SelfKind,
2814 output_type: OutType,
2815 lint_explicit_lifetime: bool,
2816 ) -> ShouldImplTraitCase {
2817 ShouldImplTraitCase {
2824 lint_explicit_lifetime,
2828 fn lifetime_param_cond(&self, impl_item: &hir::ImplItem<'_>) -> bool {
2829 self.lint_explicit_lifetime
2830 || !impl_item.generics.params.iter().any(|p| {
2833 hir::GenericParamKind::Lifetime {
2834 kind: hir::LifetimeParamKind::Explicit
2842 const TRAIT_METHODS: [ShouldImplTraitCase; 30] = [
2843 ShouldImplTraitCase::new("std::ops::Add", "add", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
2844 ShouldImplTraitCase::new("std::convert::AsMut", "as_mut", 1, FN_HEADER, SelfKind::RefMut, OutType::Ref, true),
2845 ShouldImplTraitCase::new("std::convert::AsRef", "as_ref", 1, FN_HEADER, SelfKind::Ref, OutType::Ref, true),
2846 ShouldImplTraitCase::new("std::ops::BitAnd", "bitand", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
2847 ShouldImplTraitCase::new("std::ops::BitOr", "bitor", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
2848 ShouldImplTraitCase::new("std::ops::BitXor", "bitxor", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
2849 ShouldImplTraitCase::new("std::borrow::Borrow", "borrow", 1, FN_HEADER, SelfKind::Ref, OutType::Ref, true),
2850 ShouldImplTraitCase::new("std::borrow::BorrowMut", "borrow_mut", 1, FN_HEADER, SelfKind::RefMut, OutType::Ref, true),
2851 ShouldImplTraitCase::new("std::clone::Clone", "clone", 1, FN_HEADER, SelfKind::Ref, OutType::Any, true),
2852 ShouldImplTraitCase::new("std::cmp::Ord", "cmp", 2, FN_HEADER, SelfKind::Ref, OutType::Any, true),
2853 // FIXME: default doesn't work
2854 ShouldImplTraitCase::new("std::default::Default", "default", 0, FN_HEADER, SelfKind::No, OutType::Any, true),
2855 ShouldImplTraitCase::new("std::ops::Deref", "deref", 1, FN_HEADER, SelfKind::Ref, OutType::Ref, true),
2856 ShouldImplTraitCase::new("std::ops::DerefMut", "deref_mut", 1, FN_HEADER, SelfKind::RefMut, OutType::Ref, true),
2857 ShouldImplTraitCase::new("std::ops::Div", "div", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
2858 ShouldImplTraitCase::new("std::ops::Drop", "drop", 1, FN_HEADER, SelfKind::RefMut, OutType::Unit, true),
2859 ShouldImplTraitCase::new("std::cmp::PartialEq", "eq", 2, FN_HEADER, SelfKind::Ref, OutType::Bool, true),
2860 ShouldImplTraitCase::new("std::iter::FromIterator", "from_iter", 1, FN_HEADER, SelfKind::No, OutType::Any, true),
2861 ShouldImplTraitCase::new("std::str::FromStr", "from_str", 1, FN_HEADER, SelfKind::No, OutType::Any, true),
2862 ShouldImplTraitCase::new("std::hash::Hash", "hash", 2, FN_HEADER, SelfKind::Ref, OutType::Unit, true),
2863 ShouldImplTraitCase::new("std::ops::Index", "index", 2, FN_HEADER, SelfKind::Ref, OutType::Ref, true),
2864 ShouldImplTraitCase::new("std::ops::IndexMut", "index_mut", 2, FN_HEADER, SelfKind::RefMut, OutType::Ref, true),
2865 ShouldImplTraitCase::new("std::iter::IntoIterator", "into_iter", 1, FN_HEADER, SelfKind::Value, OutType::Any, true),
2866 ShouldImplTraitCase::new("std::ops::Mul", "mul", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
2867 ShouldImplTraitCase::new("std::ops::Neg", "neg", 1, FN_HEADER, SelfKind::Value, OutType::Any, true),
2868 ShouldImplTraitCase::new("std::iter::Iterator", "next", 1, FN_HEADER, SelfKind::RefMut, OutType::Any, false),
2869 ShouldImplTraitCase::new("std::ops::Not", "not", 1, FN_HEADER, SelfKind::Value, OutType::Any, true),
2870 ShouldImplTraitCase::new("std::ops::Rem", "rem", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
2871 ShouldImplTraitCase::new("std::ops::Shl", "shl", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
2872 ShouldImplTraitCase::new("std::ops::Shr", "shr", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
2873 ShouldImplTraitCase::new("std::ops::Sub", "sub", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
2876 #[derive(Clone, Copy, PartialEq, Eq, Debug)]
2885 fn matches<'a>(self, cx: &LateContext<'a>, parent_ty: Ty<'a>, ty: Ty<'a>) -> bool {
2886 fn matches_value<'a>(cx: &LateContext<'a>, parent_ty: Ty<'a>, ty: Ty<'a>) -> bool {
2887 if ty == parent_ty {
2889 } else if ty.is_box() {
2890 ty.boxed_ty() == parent_ty
2891 } else if is_type_diagnostic_item(cx, ty, sym::Rc) || is_type_diagnostic_item(cx, ty, sym::Arc) {
2892 if let ty::Adt(_, substs) = ty.kind() {
2893 substs.types().next().map_or(false, |t| t == parent_ty)
2902 fn matches_ref<'a>(cx: &LateContext<'a>, mutability: hir::Mutability, parent_ty: Ty<'a>, ty: Ty<'a>) -> bool {
2903 if let ty::Ref(_, t, m) = *ty.kind() {
2904 return m == mutability && t == parent_ty;
2907 let trait_path = match mutability {
2908 hir::Mutability::Not => &paths::ASREF_TRAIT,
2909 hir::Mutability::Mut => &paths::ASMUT_TRAIT,
2912 let trait_def_id = match get_trait_def_id(cx, trait_path) {
2914 None => return false,
2916 implements_trait(cx, ty, trait_def_id, &[parent_ty.into()])
2919 fn matches_none<'a>(cx: &LateContext<'a>, parent_ty: Ty<'a>, ty: Ty<'a>) -> bool {
2920 !matches_value(cx, parent_ty, ty)
2921 && !matches_ref(cx, hir::Mutability::Not, parent_ty, ty)
2922 && !matches_ref(cx, hir::Mutability::Mut, parent_ty, ty)
2926 Self::Value => matches_value(cx, parent_ty, ty),
2927 Self::Ref => matches_ref(cx, hir::Mutability::Not, parent_ty, ty) || ty == parent_ty && is_copy(cx, ty),
2928 Self::RefMut => matches_ref(cx, hir::Mutability::Mut, parent_ty, ty),
2929 Self::No => matches_none(cx, parent_ty, ty),
2934 fn description(self) -> &'static str {
2936 Self::Value => "`self` by value",
2937 Self::Ref => "`self` by reference",
2938 Self::RefMut => "`self` by mutable reference",
2939 Self::No => "no `self`",
2944 #[derive(Clone, Copy)]
2953 fn matches(self, ty: &hir::FnRetTy<'_>) -> bool {
2954 let is_unit = |ty: &hir::Ty<'_>| matches!(ty.kind, hir::TyKind::Tup(&[]));
2956 (Self::Unit, &hir::FnRetTy::DefaultReturn(_)) => true,
2957 (Self::Unit, &hir::FnRetTy::Return(ty)) if is_unit(ty) => true,
2958 (Self::Bool, &hir::FnRetTy::Return(ty)) if is_bool(ty) => true,
2959 (Self::Any, &hir::FnRetTy::Return(ty)) if !is_unit(ty) => true,
2960 (Self::Ref, &hir::FnRetTy::Return(ty)) => matches!(ty.kind, hir::TyKind::Rptr(_, _)),
2966 fn is_bool(ty: &hir::Ty<'_>) -> bool {
2967 if let hir::TyKind::Path(QPath::Resolved(_, path)) = ty.kind {
2968 matches!(path.res, Res::PrimTy(PrimTy::Bool))
2974 fn fn_header_equals(expected: hir::FnHeader, actual: hir::FnHeader) -> bool {
2975 expected.constness == actual.constness
2976 && expected.unsafety == actual.unsafety
2977 && expected.asyncness == actual.asyncness